我試圖找出處理對Go 的請求的最佳方法,/并且只/在 Go 中處理,并以不同的方式處理不同的方法。這是我想出的最好的:package mainimport ( "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.go看起來很有吸引力,但似乎停滯不前。
2 回答

幕布斯6054654
TA貢獻1876條經驗 獲得超7個贊
確保您只為根服務:您在做正確的事情。在某些情況下,您可能希望調用 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:
// Give an error message.
}
當然,您可能會發現像 gorilla 這樣的第三方軟件包更適合您。
- 2 回答
- 0 關注
- 213 瀏覽
添加回答
舉報
0/150
提交
取消