我在尝试将请求代理到远程服务器之前,通过调用REST api来尝试对用户进行身份验证。 但是,我发现如果我在代理到远程服务器之前进行api调用,请求将失败并出现以下错误:
http: proxy error: http: ContentLength=139 with Body length 0.
如果我在代理到远程服务器之前删除api调用,请求可以通过并返回正确的响应。
我的中间件如下:
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// the api call to external auth server
user_id, err := authenticate(r.FormValue("username"), r.FormValue("password"))
if err != nil {
http.Error(w, err.Error(), 401)
return
}
next.ServeHTTP(w, r)
})
}
我的反向代理如下:
func NewReverseProxy(target *url.URL) *httputil.ReverseProxy {
director := func(req *http.Request) {
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.URL.Path = target.Path
targetQuery := target.RawQuery
if targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
if _, ok := req.Header["User-Agent"]; !ok {
// explicitly disable User-Agent so it's not set to default value
req.Header.Set("User-Agent", "")
}
}
return &httputil.ReverseProxy{Director: director}
}
我正在使用Chi进行路由
r.Use(AuthMiddleware)
r.Post("/", NewReverseProxy(targets).ServeHTTP)
此实施有什么问题?
答案 0 :(得分:0)
如果您不再关心身体,可以将请求的内容长度设置为0,反映身体的当前状态:
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// the api call to external auth server
user_id, err := authenticate(r.FormValue("username"), r.FormValue("password"))
if err != nil {
http.Error(w, err.Error(), 401)
return
}
r.ContentLength = 0
next.ServeHTTP(w, r)
})
}