In go, how to check the HTTP response that is written in http.ResponseWriter?

There is probably something obvious that I am missing, but I am trying to debug the HTTP response written by my go server.

I see that there is httputil.DumpResponse , but this requires an http.Response object, and the one I access is http.ResponseWriter

Is there a way to extract http.Response from http.ResponseWriter so that I can check the contents of the response in the console or log?

Context:

I am writing simple server-side authentication using https://github.com/RangelReale/osin , and this is the default example, but could not understand why front-end (using http://ember-simple-auth.com ) interprets failed authentication (wrong password) as success.

Here's a snippet:

r = mux.NewRouter() r.HandleFunc("/token", func (w http.ResponseWriter, r *http.Request) { fmt.Printf("r.HandleFunc /token\n") resp := server.NewResponse() defer resp.Close() r.ParseForm() grantType := r.FormValue("grant_type") username := r.FormValue("username") password := r.FormValue("password") fmt.Printf("/token : grantType=%s username=%s password=%s\n", grantType, username, password) if ar := server.HandleAccessRequest(resp, r); ar != nil { if username == "user" && password == "correct-password" { ar.Authorized = true } else { ar.Authorized = false } server.FinishAccessRequest(resp, r, ar) } osin.OutputJSON(resp, w, r) // Debug - doesn't work yet dump, err := httputil.DumpResponse(w, true) if err != nil { fmt.Printf("%s\n", dump) } }); http.Handle("/token", r) 
+5
source share
1 answer

Write *httptest.ResponseRecorder (which implements http.ResponseWriter ) and check it out.

Example from the package:

 package main import ( "fmt" "log" "net/http" "net/http/httptest" ) func main() { handler := func(w http.ResponseWriter, r *http.Request) { http.Error(w, "something failed", http.StatusInternalServerError) } req, err := http.NewRequest("GET", "http://example.com/foo", nil) if err != nil { log.Fatal(err) } w := httptest.NewRecorder() handler(w, req) fmt.Printf("%d - %s", w.Code, w.Body.String()) } 

Change the answer to the question in the comments:

If I understand your question correctly, then yes, you can use closure for this.

As a handler, consider the following:

 func MyHandler(w http.ResponseWriter, r *http.Request) { // do useful stuff... } 

You can then register the following closure with servemux to achieve the desired effect:

 http.HandleFunc("/my/url", func(w http.ResponseWriter, r *http.Request) { // first call MyHandler MyHandler(w, r) // then log whatever you need log.Printf("%#v\n", w) }) 

If this model is useful to you, you can write a higher order method that wraps any func(http.ResponseWriter, *http.Request) in such a closure. This is a topic for myself, though.

+5
source

Source: https://habr.com/ru/post/1211245/


All Articles