如何处理不同方法对/in Go 的 http 请求?

我正在试图找出最好的方法来处理对 /的请求,并且在 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 lib,这是我能做到的最好的事情吗?我更愿意做一些像 http.HandleGet("/", handler)的东西,比如 Express 或 Sinatra。有没有一个好的框架来编写简单的 REST 服务?Web. 走看起来很有吸引力,但似乎停滞不前。

谢谢你的建议。

62448 次浏览

eh, I was actually heading to bed and thus the quick comment on looking at http://www.gorillatoolkit.org/pkg/mux which is really nice and does what you want, just give the docs a look over. For example

func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/products", ProductsHandler)
r.HandleFunc("/articles", ArticlesHandler)
http.Handle("/", r)
}

and

r.HandleFunc("/products", ProductsHandler).
Host("www.domain.com").
Methods("GET").
Schemes("http")

and many other possibilities and ways to perform the above operations.

But I felt a need to address the other part of the question, "Is this the best I can do". If the std lib is a little too bare, a great resource to check out is here: https://github.com/golang/go/wiki/Projects#web-libraries (linked specifically to web libraries).

To ensure that you only serve the root: You're doing the right thing. In some cases you would want to call the ServeHttp method of an http.FileServer object instead of calling NotFound; it depends whether you have miscellaneous files that you want to serve as well.

To handle different methods differently: Many of my HTTP handlers contain nothing but a switch statement like this:

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)
}

Of course, you may find that a third-party package like gorilla works better for you.