dongmao9217 2015-01-16 12:23 采纳率: 100%
浏览 215
已采纳

在运行中,如何检查写入http.ResponseWriter的http响应?

There's probably something obvious that I'm missing but I'm trying to debug the HTTP response written by my go server.

I see that there's httputil.DumpResponse available but it takes a http.Response object and what I have available is http.ResponseWriter

Is there a way to extract the http.Response from http.ResponseWriter so I can inspect the content of the response to console or log?

Context:

I'm writing a simple server-side authentication using https://github.com/RangelReale/osin and it's default example, but could not understand why the front-end (using http://ember-simple-auth.com) interprets a failed authentication (incorrect password) as success.

Here's the snippet:

r = mux.NewRouter()
r.HandleFunc("/token", func (w http.ResponseWriter, r *http.Request) {

    fmt.Printf("r.HandleFunc /token
")

    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
", 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
", dump)
    }
});
http.Handle("/token", r)
  • 写回答

1条回答 默认 最新

  • doubiao1734 2015-01-16 16:06
    关注

    Write to an *httptest.ResponseRecorder (which implements http.ResponseWriter) and inspect it.

    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())
    }
    

    Edit to answer question in comments:

    If I understand your question correctly, then yes, you can make use of closures for this.

    Consider the following to be your handler:

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

    You could then register the following closure with your servemux to attain 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
    ", w)
    })
    

    If this pattern proves useful to you then you could write a higher-order method that wraps any func(http.ResponseWriter, *http.Request) in such a closure. That's a topic for itself, though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器