Skip to content

Instantly share code, notes, and snippets.

@craftamap
Created June 6, 2020 20:23
Show Gist options
  • Save craftamap/781eb5e9845bfee483d3407433f1d84e to your computer and use it in GitHub Desktop.
Save craftamap/781eb5e9845bfee483d3407433f1d84e to your computer and use it in GitHub Desktop.
Golang Middleware Example
package main
import (
"fmt"
"net/http"
"net/url"
"os"
"github.com/gorilla/context"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
type wrapperMiddleware struct {
h http.Handler
}
func (h wrapperMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
xCraft := r.Header.Values("X-CRAFT")
if len(xCraft) == 0 {
return
}
contextReq := http.Request{}
contextReq.URL, _ = url.Parse(xCraft[0])
context.Set(r, "contextReq", &contextReq)
h.h.ServeHTTP(w, r)
}
func newWrapperMiddleware(h http.Handler) http.Handler {
return wrapperMiddleware{h}
}
type authenticatedMiddleware struct {
h http.Handler
}
func (h authenticatedMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
contextReq := context.Get(r, "contextReq").(*http.Request)
client := &http.Client{}
fmt.Println(contextReq)
resp, err := client.Do(contextReq)
if err != nil {
w.WriteHeader(404)
return
}
fmt.Println(resp.StatusCode)
h.h.ServeHTTP(w, r)
}
func newAuthenticatedMiddleware(h http.Handler) http.Handler {
return authenticatedMiddleware{h}
}
func simpleRequestHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World!\n"))
}
func authenticatedEndpoint(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello Authenticated User!\n"))
}
func main() {
r := mux.NewRouter()
r.Handle("/", newAuthenticatedMiddleware(http.HandlerFunc(authenticatedEndpoint)))
r.Use(func(handler http.Handler) http.Handler {
return handlers.LoggingHandler(os.Stdout, handler)
})
r.Use(handlers.CompressHandler)
r.Use(handlers.RecoveryHandler())
r.Use(newWrapperMiddleware)
http.ListenAndServe(":8080", r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment