【Go】gorilla/muxでミドルウェア管理してみる

riki(Rikitake)
Mar 29 · 7 min read
オリジナルのThe Go gopher(Gopherくん)は、Renée Frenchによってデザインされました。

そもそもミドルウェアとは?

gorilla/csrfを使ってCSRF対策をしてみる

func main() {
r := mux.NewRouter()
csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key"))
r.Use(csrfMiddleware)
c := &controllers.UserController{}
r.HandleFunc("/", c.Get).Methods("GET")
http.ListenAndServe(":3001", r)
}
type UserController struct {}func (c *UserController) Get(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-CSRF-Token", csrf.Token(r))
w.WriteHeader(200)
}
type MiddlewareFunc func(http.Handler) http.Handlerfunc (r *Router) Use(mwf ...MiddlewareFunc) {
for _, fn := range mwf {
r.middlewares = append(r.middlewares, fn)
}
}

自作ミドルウェアを作ってみる

type MiddlewareFunc func(http.Handler) http.Handler
func CORSMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := "localhost:3001"
w.Header().Set("Access-Control-Allow-Origin", origin)
next.ServeHTTP(w, r)
})
}
func main() {
r := mux.NewRouter()
r.Use(CORSMiddleware)
csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key"))
r.Use(csrfMiddleware)
c := &controllers.UserController{}
r.HandleFunc("/", c.Get).Methods("GET")
http.ListenAndServe(":3001", r)
}
1. CORSMiddleware
2. csrfMiddleware
func CORSMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := "localhost:3001"
w.Header().Set("Access-Control-Allow-Origin", origin)
next.ServeHTTP(w, r)
})
}
r.Use(CORSMiddleware)
csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key"))
r.Use(csrfMiddleware)
next.ServeHTTP(w, r)

まとめ

Eureka Engineering

Learn about Eureka’s engineering efforts, product developments and more.

riki(Rikitake)

Written by

API Team at eureka, inc.

Eureka Engineering

Learn about Eureka’s engineering efforts, product developments and more.