Last active
December 12, 2016 10:32
-
-
Save guillermo/0eb7e53fa687acbf05ea to your computer and use it in GitHub Desktop.
Package verbs provides a simple method to filter request method with the net/http ServeMux
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
// Copyright 2015 Guillermo Alvarez. All rights reserved. | |
// Use of this source code is governed by standard BSD license. | |
/* | |
Package verbs provides a simple method to filter request method with the net/http ServeMux | |
func createUser(w http.ResponseWriter, r *http.Request) { | |
... | |
} | |
mux := http.NewServeMux() | |
mux.Handle("/users", Verbs{Post: createUser}) | |
*/ | |
package verbs | |
import "net/http" | |
type Verbs struct { | |
Get http.HandlerFunc | |
Post http.HandlerFunc | |
Put http.HandlerFunc | |
Delete http.HandlerFunc | |
Patch http.HandlerFunc | |
Head http.HandlerFunc | |
} | |
func (v Verbs) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
switch r.Method { | |
case "GET": | |
if v.Get != nil { | |
v.Get(w, r) | |
return | |
} | |
case "POST": | |
if v.Post != nil { | |
v.Post(w, r) | |
return | |
} | |
case "PUT": | |
if v.Put != nil { | |
v.Put(w, r) | |
return | |
} | |
case "DELETE": | |
if v.Delete != nil { | |
v.Delete(w, r) | |
return | |
} | |
case "PATCH": | |
if v.Patch != nil { | |
v.Patch(w, r) | |
return | |
} | |
case "HEAD": | |
if v.Head != nil { | |
v.Head(w, r) | |
return | |
} | |
} | |
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So the last line should actually read something like:
(ouch! much less readable)