@@ -2,6 +2,7 @@ package http
22
33import (
44 "bufio"
5+ "bytes"
56 "context"
67 "fmt"
78 "io"
@@ -119,6 +120,7 @@ func NewHttpServer(p HttpServerParams, opts ...ServerOption) Server {
119120 },
120121 []string {"method" , "path" , "status" },
121122 ),
123+ config : p .Config ,
122124 }
123125
124126 server .mux .Use (server .requestMiddleware )
@@ -162,6 +164,7 @@ type httpServer struct {
162164 mux * mux.Router
163165 requestCounter * prometheus.CounterVec
164166 requestLatency * prometheus.HistogramVec
167+ config config.AgentConfig
165168}
166169
167170func (h * httpServer ) RegisterHandler (handler RegisterableHandler ) {
@@ -195,11 +198,34 @@ func (h *httpServer) requestMiddleware(next http.Handler) http.Handler {
195198 return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
196199 start := time .Now ()
197200 rec := & responseRecorder {ResponseWriter : w , statusCode : http .StatusOK }
201+
202+ fields := []zap.Field {
203+ zap .String ("method" , r .Method ),
204+ zap .String ("path" , r .URL .Path ),
205+ zap .Int ("content-length" , int (r .ContentLength )),
206+ }
207+
208+ if h .config .VerboseOutput && r .ContentLength > 0 && r .Body != nil {
209+
210+ br := bufio .NewReader (r .Body )
211+ bodyBytes , err := io .ReadAll (br )
212+ if err != nil {
213+
214+ h .logger .Error ("Failed to read request body" , zap .Error (err ))
215+ return
216+ }
217+ body := string (bodyBytes )
218+ r .Body = io .NopCloser (bytes .NewBuffer (bodyBytes ))
219+ fields = append (fields , zap .String ("body" , body ))
220+ }
221+ h .logger .Debug ("HTTP request ==>" ,
222+ fields ... ,
223+ )
198224 next .ServeHTTP (rec , r )
199225 duration := time .Since (start )
200226 h .requestCounter .WithLabelValues (r .Method , r .URL .Path , fmt .Sprintf ("%d" , rec .statusCode )).Inc ()
201227 h .requestLatency .WithLabelValues (r .Method , r .URL .Path , fmt .Sprintf ("%d" , rec .statusCode )).Observe (duration .Seconds ())
202- h .logger .Info ("HTTP incoming request" ,
228+ h .logger .Info ("<== HTTP request" ,
203229 zap .String ("method" , r .Method ),
204230 zap .String ("path" , r .URL .Path ),
205231 zap .Int ("status" , rec .statusCode ),
@@ -209,6 +235,9 @@ func (h *httpServer) requestMiddleware(next http.Handler) http.Handler {
209235 )
210236 })
211237}
238+
239+ var defaultReadTimeout = time .Second
240+
212241func (h * httpServer ) Start () (int , error ) {
213242
214243 if h .server != nil {
@@ -222,7 +251,8 @@ func (h *httpServer) Start() (int, error) {
222251 go func () {
223252
224253 h .server = & http.Server {
225- Handler : h .mux ,
254+ Handler : h .mux ,
255+ ReadTimeout : defaultReadTimeout ,
226256 }
227257
228258 err := h .server .Serve (ln )
0 commit comments