Created
February 28, 2020 10:06
-
-
Save arush-sal/88e4e4ab5d9d72840cc99a357d95cbaa to your computer and use it in GitHub Desktop.
Simple Gorilla Mux HTTP server with each request logged in Go lang
This file contains 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" | |
"log" | |
"net/http" | |
"net/http/httptest" | |
"net/http/httputil" | |
"github.com/gorilla/mux" | |
) | |
const port = ":8080" | |
func logHandler(fn http.HandlerFunc) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
x, err := httputil.DumpRequest(r, true) | |
if err != nil { | |
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError) | |
return | |
} | |
log.Println(fmt.Sprintf("%q", x)) | |
rec := httptest.NewRecorder() | |
fn(rec, r) | |
if _, err = w.Write(rec.Body.Bytes()); err != nil { | |
http.Error(w, fmt.Sprint(err), | |
http.StatusInternalServerError) | |
return | |
} | |
log.Println(fmt.Sprintf("%q", rec.Body)) | |
} | |
} | |
func messageHandler(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintln(w, "Hello, World!") | |
} | |
func main() { | |
router := mux.NewRouter() | |
router.HandleFunc("/", logHandler(messageHandler)) | |
log.Println("Starting server on", port) | |
log.Fatal(http.ListenAndServe(port, router)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Replace
with
and
can be used to start the server if using plain
net/http
package instead ofgorilla/mux
.