我需要在Golang Web服务器中为特定请求定义请求处理程序。我目前这样做的方式如下
package main
import "net/http"
type apiFunc func(rg string, w http.ResponseWriter, r *http.Request)
func h1(rg string, w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Bonjour"))
}
func h2(rg string, w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Guten Tag!"))
}
func h3(rg string, w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Good Morning!"))
}
type gHandlers map[string]apiFunc
var handlers gHandlers
func handleConnection(w http.ResponseWriter, r *http.Request) {
hh := r.URL.Query().Get("handler")
handlers[hh]("rg", w, r)
}
func main() {
handlers = make(map[string]apiFunc, 3)
handlers["h1"] = h1
handlers["h2"] = h2
handlers["h3"] = h3
http.HandleFunc("/", handleConnection)
http.ListenAndServe(":8080", nil)
}
这很好用。但是,我仍然是Golang的新手,所以它可能不是“正确”的做事方式。对于任何能够表明是否有更好的方法来实现这一结果的人,我都非常感激
答案 0 :(得分:0)
如何在switch
中使用handleConnection
语句?
switch hh {
case "h1":
h1("rg", w, r)
case "h2":
h2("rg", w, r)
case "h3":
h3("rg", w, r)
default:
// return HTTP 400 here
}
优点是:
apiFunc
和gHandlers
类型