Skip to content

Instantly share code, notes, and snippets.

@kalharbi
Last active May 27, 2022 01:42
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save kalharbi/eec82325f0852eaf5021de4e9d3b36f2 to your computer and use it in GitHub Desktop.
Save kalharbi/eec82325f0852eaf5021de4e9d3b36f2 to your computer and use it in GitHub Desktop.
Example of using a middleware with [httprouter](https://github.com/julienschmidt/httprouter)
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))
}
@davepile
Copy link

A very simple and straightforward example. Just what was after. Thank you.

@MustachedNinja
Copy link

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

@vanor89
Copy link

vanor89 commented Nov 4, 2019

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.

@cheolgyu
Copy link

thank you !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment