Skip to content

Commit

Permalink
Add logging middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
th0th committed Nov 8, 2020
1 parent bbf31d1 commit 3470d35
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
17 changes: 15 additions & 2 deletions http/middleware.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
package http

import "net/http"
import (
"log"
"net/http"
"os"
)

func middlewareJson(next http.Handler) http.Handler {
func middlewareJsonHeader(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")

next.ServeHTTP(w, r)
})
}

func middlewareIndexLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.SetOutput(os.Stdout)
log.Println(r.Method, r.URL)

next.ServeHTTP(w, r)
})
}
2 changes: 1 addition & 1 deletion http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func (s *Server) index(w http.ResponseWriter, r *http.Request) {
func (s *Server) Run() {
mux := http.NewServeMux()

mux.Handle("/", middlewareJson(http.HandlerFunc(s.index)))
mux.Handle("/", middlewareIndexLogger(middlewareJsonHeader(http.HandlerFunc(s.index))))

log.Println("Starting to listen on 0.0.0.0:80...")
log.Fatal(http.ListenAndServe(":80", mux))
Expand Down

0 comments on commit 3470d35

Please sign in to comment.