Skip to content

Instantly share code, notes, and snippets.

@idiomatic
Created March 17, 2016 04:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idiomatic/fb6eb12cbff48dacd797 to your computer and use it in GitHub Desktop.
Save idiomatic/fb6eb12cbff48dacd797 to your computer and use it in GitHub Desktop.
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