I need to define request handlers for specific requests in my Golang web server. The way I am doing this at present is as follows
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)
}
This works just fine. However, I am still a newcomer to Golang so it may not be the "right" way to do things. I'd be much obliged to anyone who might be able to indicate whether is a better way to go about achieving this result