-
-
Save kalharbi/eec82325f0852eaf5021de4e9d3b36f2 to your computer and use it in GitHub Desktop.
| 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)) | |
| } |
Nice example, I think it will be more helpful if you add middleware2 and chain it with first middleware.
A very simple and straightforward example. Just what was after. Thank you.
I'm confused about line 22. How are you able to call func (variables) returnType { ... } without a function name? essentially, why didn't you write func middleHandler(variables) returnType { ... }? Thank you
I'm confused about line 22. How are you able to call func (variables) returnType { ... } without a function name? essentially, why didn't you write func middleHandler(variables) returnType { ... }? Thank you
func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request)
(m *Middleware) means that this function belongs to this type
ServeHTTP is the name of the function
w and r are parameters, both of them postceded by their types.
thank you !
thank you !