我试图找出最好的方式来处理对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库做的最好的吗?我宁愿做一些http.HandleGet("/", handler)
快递或西纳特拉之类的事情。有没有编写简单REST服务的良好框架?web.go看起来很吸引人,但停滞不前。
感谢您的意见。