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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line