@@ -172,10 +172,55 @@ func TestToStringWithOptionals(t *testing.T) {
172
172
}
173
173
}
174
174
175
+ func TestToFields (t * testing.T ) {
176
+ tables := []struct {
177
+ statusCode int
178
+ method string
179
+ path string
180
+ expectedFields RequestFields
181
+ }{
182
+ {http .StatusOK , http .MethodGet , "/foo" , RequestFields {Method : http .MethodGet , Url : "/foo" , StatusCode : http .StatusOK }},
183
+ {http .StatusUnauthorized , http .MethodPost , "/bar/create" , RequestFields {Method : http .MethodPost , Url : "/bar/create" , StatusCode : http .StatusUnauthorized }},
184
+ {http .StatusNotFound , http .MethodGet , "/hello/world" , RequestFields {Method : http .MethodGet , Url : "/hello/world" , StatusCode : http .StatusNotFound }},
185
+ {http .StatusInternalServerError , http .MethodGet , "/" , RequestFields {Method : http .MethodGet , Url : "/" , StatusCode : http .StatusInternalServerError }},
186
+ {http .StatusServiceUnavailable , http .MethodPut , "/foo/update" , RequestFields {Method : http .MethodPut , Url : "/foo/update" , StatusCode : http .StatusServiceUnavailable }},
187
+ }
188
+
189
+ for _ , table := range tables {
190
+ app := & application {}
191
+
192
+ req , err := http .NewRequest (table .method , table .path , nil )
193
+ if err != nil {
194
+ t .Fatal (err )
195
+ }
196
+
197
+ testHandler := http .HandlerFunc (func (rw http.ResponseWriter , r * http.Request ) {
198
+ rw .WriteHeader (table .statusCode )
199
+ })
200
+
201
+ rr := httptest .NewRecorder ()
202
+ handler := app .logRequestToFields (testHandler )
203
+ handler .ServeHTTP (rr , req )
204
+
205
+ if app .RequestFields .StatusCode != table .expectedFields .StatusCode {
206
+ t .Errorf ("Expected field was incorrect, %d should be %d" , app .RequestFields .StatusCode , table .expectedFields .StatusCode )
207
+ }
208
+
209
+ if app .RequestFields .Method != table .expectedFields .Method {
210
+ t .Errorf ("Expected field was incorrect, %s should be %s" , app .RequestFields .Method , table .expectedFields .Method )
211
+ }
212
+
213
+ if app .RequestFields .Url != table .expectedFields .Url {
214
+ t .Errorf ("Expected field was incorrect, %s should be %s" , app .RequestFields .Url , table .expectedFields .Url )
215
+ }
216
+ }
217
+ }
218
+
175
219
// Helpers
176
220
177
221
type application struct {
178
222
infoLog * log.Logger
223
+ RequestFields
179
224
}
180
225
181
226
func (app * application ) logRequestToLogger (next http.Handler ) http.Handler {
@@ -207,3 +252,10 @@ func (app *application) logRequestToStringWithOptionals(next http.Handler) http.
207
252
app .infoLog .Println (lr .ToString ()["completed" ])
208
253
})
209
254
}
255
+
256
+ func (app * application ) logRequestToFields (next http.Handler ) http.Handler {
257
+ return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
258
+ lr := LogRequest {Request : r , Writer : w , Handler : next }
259
+ app .RequestFields = lr .ToFields ()
260
+ })
261
+ }
0 commit comments