Skip to content

Commit

Permalink
Adding a request logger. Perhaps overkill, but it`ll work for now.
Browse files Browse the repository at this point in the history
  • Loading branch information
Dynom committed Jun 16, 2018
1 parent 3b5f5d0 commit 1cf683b
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ import (

"context"

"math/rand"

"sync"

"strings"

"strconv"

"github.com/rs/cors"
"github.com/sirupsen/logrus"
"gopkg.in/tomb.v2"
Expand Down Expand Up @@ -117,8 +125,23 @@ func NewHTTP(sr ServiceRegistry, mux *http.ServeMux, options ...Option) TySugSer
}

func createRequestIDHandler(h http.Handler) http.HandlerFunc {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
instanceId := rnd.Int31()

var requestCounter int
var lock = sync.Mutex{}
var buf = strings.Builder{}
return func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "request_id", r.RemoteAddr)
lock.Lock()
requestCounter++
buf.Reset()
buf.WriteString(strconv.Itoa(int(instanceId)))
buf.WriteString("-")
buf.WriteString(strconv.Itoa(requestCounter))
reqId := buf.String()
lock.Unlock()

ctx := context.WithValue(r.Context(), "request_id", reqId)
h.ServeHTTP(w, r.WithContext(ctx))
}
}
Expand Down

0 comments on commit 1cf683b

Please sign in to comment.