Created
August 1, 2021 03:42
-
-
Save madflojo/7dcaea715523dc661edc70a1ce06dd58 to your computer and use it in GitHub Desktop.
httprouter Article - Hello World with Middleware
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" | |
"github.com/julienschmidt/httprouter" | |
"log" | |
"net/http" | |
) | |
// handler is a basic HTTP handler that prints hello world. | |
func handler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { | |
fmt.Fprintf(w, "Hello %s", ps.ByName("name")) | |
} | |
// middleware is used to intercept incoming HTTP calls and apply general functions upon them. | |
func middleware(n httprouter.Handle) httprouter.Handle { | |
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { | |
log.Printf("HTTP request sent to %s from %s", r.URL.Path, r.RemoteAddr) | |
// call registered handler | |
n(w, r, ps) | |
} | |
} | |
func main() { | |
// Create Router | |
router := httprouter.New() | |
router.GET("/hello/:name", middleware(handler)) | |
// Start HTTP Listener | |
err := http.ListenAndServe(":8080", router) | |
if err != nil { | |
log.Printf("HTTP Server stopped - %s", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment