gpt4 book ai didi

go - 如何处理 Go 中不同方法的 http 请求?

转载 作者:IT老高 更新时间:2023-10-28 12:58:00 27 4
gpt4 key购买 nike

我正在尝试找出在 Go 中处理对 / 和仅 / 的请求的最佳方式,并以不同的方式处理不同的方法。这是我想出的最好的:

package main

import (
"fmt"
"html"
"log"
"net/http"
)

func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}

if r.Method == "GET" {
fmt.Fprintf(w, "GET, %q", html.EscapeString(r.URL.Path))
} else if r.Method == "POST" {
fmt.Fprintf(w, "POST, %q", html.EscapeString(r.URL.Path))
} else {
http.Error(w, "Invalid request method.", 405)
}
})

log.Fatal(http.ListenAndServe(":8080", nil))
}

这是惯用的围棋吗?这是我能用标准http lib做的最好的吗?我更愿意像在 express 或 Sinatra 中那样做类似 http.HandleGet("/", handler) 的事情。是否有编写简单 REST 服务的良好框架? web.go看起来很有吸引力,但似乎停滞不前。

感谢您的建议。

最佳答案

为了确保您只为根服务:您正在做正确的事情。在某些情况下,您可能希望调用 http.FileServer 对象的 ServeHttp 方法,而不是调用 NotFound;这取决于您是否还想要提供其他文件。

以不同的方式处理不同的方法:我的许多 HTTP 处理程序只包含这样的 switch 语句:

switch r.Method {
case http.MethodGet:
// Serve the resource.
case http.MethodPost:
// Create a new record.
case http.MethodPut:
// Update an existing record.
case http.MethodDelete:
// Remove the record.
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}

当然,您可能会发现像 gorilla 这样的第三方软件包更适合您。

关于go - 如何处理 Go 中不同方法的 http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15240884/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com