rs / xmux

xmux is a httprouter fork on top of xhandler (net/context aware)
Other
98 stars 11 forks source link

Add TestSetParamContext to sets ParamHolder for testing #8

Closed achiku closed 8 years ago

achiku commented 8 years ago

As discussed in https://github.com/rs/xmux/issues/7, this function is purely for testing, and set ParamHolder in context.Context.

func helloWithParam(ctx context.Context, w http.ResponseWriter, r *http.Request) {
    n := xmux.Param(ctx, "name")
    fmt.Fprintf(w, "Hello, %s!", n)
    return
}

func main() {
    m := xmux.New()
    m.GET("/hello/:name", xhandler.HandlerFuncC(helloWithParam))
    if err := http.ListenAndServe(":8888", xhandler.New(context.Background(), m)); err != nil {
        log.Fatal(err)
    }
}
func TestHelloWithParam(t *testing.T) {
    n := "dummyName"
    ps := xmux.ParamHolder{xmux.Parameter{Name: "name", Value: n}}
    ctx := xmux.TestSetParamContext(context.TODO(), ps)
    req, _ := http.NewRequest("GET", "/hello/"+n, nil)
    w := httptest.NewRecorder()
    helloWithParam(ctx, w, req)
    t.Log(w.Body)
}