【发布时间】:2013-02-20 20:41:56
【问题描述】:
我正在尝试找出在 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 看起来很吸引人,但似乎停滞不前。
感谢您的建议。
【问题讨论】:
-
如果您只是在寻找路由抽象,您可能对gorillatoolkit.org/pkg/mux 感兴趣。
-
+1。 mux 或 gorillatoolkit.org/pkg/pat 非常适合抽象它。
标签: go