Skip to content

Instantly share code, notes, and snippets.

@arush-sal
Created February 28, 2020 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arush-sal/88e4e4ab5d9d72840cc99a357d95cbaa to your computer and use it in GitHub Desktop.
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
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))
}
@arush-sal
Copy link
Author

Replace

    router := mux.NewRouter()
    router.HandleFunc("/", logHandler(messageHandler))

with

    http.HandleFunc("/", logHandler(messageHandler))

and

	log.Fatal(http.ListenAndServe(port, nil))

can be used to start the server if using plain net/http package instead of gorilla/mux.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment