Forked from kalharbi/httprouter-middleware-example.go
Created
March 24, 2018 07:16
-
-
Save AlphaWong/f3a4a4e664e7312239817435f24b185d to your computer and use it in GitHub Desktop.
Example of using a middleware with [httprouter](https://github.com/julienschmidt/httprouter)
This file contains hidden or 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 ( | |
"fmt" | |
"github.com/julienschmidt/httprouter" | |
"log" | |
"net/http" | |
) | |
// The type of our middleware consists of the original handler we want to wrap and a message | |
type Middleware struct { | |
next http.Handler | |
message string | |
} | |
// Make a constructor for our middleware type since its fields are not exported (in lowercase) | |
func NewMiddleware(next http.Handler, message string) *Middleware { | |
return &Middleware{next: next, message: message} | |
} | |
// Our middleware handler | |
func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
// We can modify the request here; for simplicity, we will just log a message | |
log.Printf("msg: %s, Method: %s, URI: %s\n", m.message, r.Method, r.RequestURI) | |
m.next.ServeHTTP(w, r) | |
// We can modify the response here | |
} | |
// Our handle function | |
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { | |
fmt.Fprint(w, "Welcome!\n") | |
} | |
func main() { | |
router := httprouter.New() | |
router.GET("/", Index) | |
m := NewMiddleware(router, "I'm a middleware") | |
log.Fatal(http.ListenAndServe(":3000", m)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment