This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io" | |
"log" | |
"net/http" | |
) | |
type MethodMux struct { | |
GET http.Handler | |
POST http.Handler | |
PUT http.Handler | |
} | |
func (mux *MethodMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
var methodMux http.Handler | |
switch r.Method { | |
case "GET": | |
methodMux = mux.GET | |
case "POST": | |
methodMux = mux.POST | |
case "PUT": | |
methodMux = mux.PUT | |
} | |
if methodMux == nil { | |
methodMux = http.DefaultServeMux | |
} | |
methodMux.ServeHTTP(w, r) | |
} | |
func main() { | |
getMux := http.NewServeMux() | |
postMux := http.NewServeMux() | |
getMux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { | |
io.WriteString(w, "hello world\n") | |
}) | |
postMux.HandleFunc("/foo", func(w http.ResponseWriter, req *http.Request) { | |
io.WriteString(w, "post\n") | |
}) | |
log.Fatal(http.ListenAndServe(":8080", &MethodMux{ | |
GET: getMux, | |
POST: postMux, | |
})) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment