dongtu9823 2018-06-21 09:17 采纳率: 0%
浏览 190
已采纳

使用自定义ServeHTTP实现的HTTP处理程序的golang单元测试

I am trying to write unit test for my http file server. I have implemented the ServeHTTP function so that it'd replace "//" with "/" in the URL:

type slashFix struct {
    mux http.Handler
}

func (h *slashFix) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    r.URL.Path = strings.Replace(r.URL.Path, "//", "/", -1)
    h.mux.ServeHTTP(w, r)
}

The bare-minimum code would look like this:

func StartFileServer() {
    httpMux := http.NewServeMux()
    httpMux.HandleFunc("/abc/", basicAuth(handle))
    http.ListenAndServe(":8000", &slashFix{httpMux})
}

func handle(writer http.ResponseWriter, r *http.Request) {
    dirName := "C:\\Users\\gayr\\GolandProjects\\src\\NDAC\\download\\"    
    http.StripPrefix("/abc",
        http.FileServer(http.Dir(dirName))).ServeHTTP(writer, r)
}

func basicAuth(handler http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        user, pass, ok := r.BasicAuth()
        if user != "UserName" || pass != "Password" {
            w.WriteHeader(401)
            w.Write([]byte("Unauthorised.
"))
            return
        }
        handler(w, r)
    }
}

I came across instances like the following to test http handlers:

req, err := http.NewRequest("GET", "/abc/testfile.txt", nil)
if err != nil {
    t.Fatal(err)
}
req.SetBasicAuth("UserName", "Password")
rr := httptest.NewRecorder()
handler := http.HandlerFunc(basicAuth(handle))
handler.ServeHTTP(rr, req)

Doing so would invoke the ServeHTTP function implemented using http.HandleFunc, but I want ServeHTTP implemented in my code to be invoked. How can this be achieved? Also, is there a way for me to directly test StartFileServer()?

Edit: I checked the link provided in the comments; my question does not appear to be a duplicate. I have a specific question: instead of invoking the ServeHTTP function implemented using http.HandleFunc, I want ServeHTTP implemented in my code to be invoked. I do not see this addressed in the provided link.

  • 写回答

1条回答 默认 最新

  • dongmou3615 2018-06-21 10:37
    关注

    http.HandlerFunc implements http.Handler. As Flimzy pointed out in the comments, there is no need for basicAuth to require a HandlerFunc; any http.Handler will do. Sticking to the http.Handler interface instead of the concrete HandlerFunc type will make everything easily composable:

    func basicAuth(handler http.Handler) http.Handler { // Note: http.Handler, not http.HandlerFunc
            return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                    user, pass, ok := r.BasicAuth()
                    if !ok {
                            // TODO
                    }
                    if user != "UserName" || pass != "Password" {
                            w.WriteHeader(401)
                            w.Write([]byte("Unauthorised.
    "))
                            return
                    }
    
                    handler.ServeHTTP(w, r)
            })
    }
    
    func TestFoo(t *testing.T) {
            req, err := http.NewRequest("GET", "/abc/testfile.txt", nil)
            if err != nil {
                    t.Fatal(err)
            }
            req.SetBasicAuth("UserName", "Password")
            rr := httptest.NewRecorder()
    
            // composition is trivial now
            sf := &slashFix{
                    mux: http.HandlerFunc(handle),
            }
            handler := basicAuth(sf)
            handler.ServeHTTP(rr, req)
    
            // assert correct rr
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看