Skip to content

Commit

Permalink
log ip
Browse files Browse the repository at this point in the history
  • Loading branch information
lesomnus committed Oct 10, 2023
1 parent 9b45e51 commit ad7d1e1
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
22 changes: 20 additions & 2 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,22 @@ func (s *Handler) parseDescription(res http.ResponseWriter, req *http.Request) (
}, nil
}

func getRemoteAddr(req *http.Request) string {
addr := req.Header.Get("X-Real-Ip")
if addr == "" {
addr = req.Header.Get("X-Forwarded-For")
}
if addr == "" {
addr = req.RemoteAddr
}
return addr
}

func (s *Handler) ServeHTTP(r http.ResponseWriter, req *http.Request) {
remote_addr := getRemoteAddr(req)

if (req.URL.Path == "/") && (req.Method == http.MethodGet) {
s.Log.Info().Msg("probe")
s.Log.Info().Str("remote_addr", remote_addr).Msg("probe")
r.WriteHeader(http.StatusOK)
return
}
Expand All @@ -122,7 +135,12 @@ func (s *Handler) ServeHTTP(r http.ResponseWriter, req *http.Request) {

desc, err := s.parseDescription(res, req)
{
l := l.With().Str("url", req.URL.String()).Str("method", req.Method).Logger()
l := l.With().
Str("remote_addr", remote_addr).
Str("url", req.URL.String()).
Str("method", req.Method).
Logger()

if err != nil {
l.Warn().Dur("dt", time.Since(t0)).Int("status", res.status_code).Msg("REQ " + err.Error())
return
Expand Down
23 changes: 23 additions & 0 deletions server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,29 @@ func TestServerPut(t *testing.T) {
err := store.Get(context.Background(), DescriptionFoo, io.Discard)
require.ErrorIs(err, main.ErrNotExist)
}))

t.Run("409 if cache already exist", WithHandler(func(t *testing.T, store main.Store, handler *main.Handler) {
require := require.New(t)

data := randomData(t)
{
req := httptest.NewRequest(http.MethodPut, DescriptionFoo.String(), bytes.NewReader(data))
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)

res := w.Result()
require.Equal(http.StatusOK, res.StatusCode)
}

{
req := httptest.NewRequest(http.MethodPut, DescriptionFoo.String(), bytes.NewReader(data))
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)

res := w.Result()
require.Equal(http.StatusConflict, res.StatusCode)
}
}))
}

func TestServerInvalidMethod(t *testing.T) {
Expand Down

0 comments on commit ad7d1e1

Please sign in to comment.