我正在尝试找出在 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))
}
这是 Go 的惯用语吗?这是我能用标准 http 库做的最好的事情吗?我更愿意做像 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 这样的第三方软件包更适合您。
呃,我实际上正在睡觉,因此查看 http://www.gorillatoolkit.org/pkg/mux 的快速评论非常好,并且可以满足您的要求,只需看一下文档即可。例如
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/products", ProductsHandler)
r.HandleFunc("/articles", ArticlesHandler)
http.Handle("/", r)
}
和
r.HandleFunc("/products", ProductsHandler).
Host("www.domain.com").
Methods("GET").
Schemes("http")
以及执行上述操作的许多其他可能性和方法。
但我觉得有必要解决问题的另一部分,“这是我能做的最好的事情吗”。如果 std 库有点太简单了,这里有一个很棒的资源可供查看:https://github.com/golang/go/wiki/Projects#web-libraries(专门链接到 Web 库)。
从 Go 1.22.0 开始,你可以将 HTTP 方法放在端点之前
package main
import (
"net/http"
)
func main() {
router := http.NewServeMux()
router.HandleFunc("GET /", myHandler)
http.ListenAndServe(":8080", router)
}