Created
July 11, 2017 22:11
-
-
Save rodkranz/9c198cc1c785b1538c5b8b950253199c to your computer and use it in GitHub Desktop.
Example of middleware in GO
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" | |
"os" | |
"net/http" | |
"log" | |
"context" | |
"time" | |
) | |
type Server struct { | |
*http.ServeMux | |
} | |
func NewServer() *Server { | |
return &Server{http.NewServeMux()} | |
} | |
func (s *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) { | |
timeStart := time.Now() | |
ctx := req.Context() | |
ctx = context.WithValue(ctx, "name", "Rodrigo") | |
req = req.WithContext(ctx) | |
s.ServeMux.ServeHTTP(rw, req) | |
timeEnd := time.Now().Sub(timeStart) | |
log.Printf("Server execution time was %s.\n", timeEnd.String()) | |
} | |
func main() { | |
myServer := NewServer() | |
myServer.HandleFunc("/welcome", welcome) | |
myServer.HandleFunc("/hello", MiddlewareForRouter(hello)) | |
addr := ":8080" | |
fmt.Printf("Server listing %s\n", addr) | |
err := http.ListenAndServe(addr, myServer) | |
if err != nil { | |
log.Fatalf("Server Errror: %v", err) | |
os.Exit(1) | |
} | |
os.Exit(0) | |
} | |
// MiddlewareForRouter is an example of middleware for routers. | |
func MiddlewareForRouter(handlerFunc http.HandlerFunc) http.HandlerFunc { | |
return func(rw http.ResponseWriter, req *http.Request) { | |
timeStart := time.Now() | |
handlerFunc(rw, req) | |
timeEnd := time.Now().Sub(timeStart) | |
log.Printf("Middleware execution time was %s.\n", timeEnd.String()) | |
} | |
} | |
func welcome(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintln(w, "Welcome Rodrigo") | |
} | |
func hello(w http.ResponseWriter, r *http.Request) { | |
userName, has := r.Context().Value("name").(string) | |
if has { | |
fmt.Fprintf(w, "Welcome %v.", userName) | |
return | |
} | |
w.WriteHeader(401) | |
fmt.Fprintln(w, "User not logged") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment