2017-03-07 5 views
2

원격 서버에 요청을 프록시하기 전에 REST API를 호출하여 사용자를 인증하려고합니다. 그러나, 나는 원격 서버에 프록시하기 전에 API를 호출 할 경우, 요청이 다음 오류와 함께 실패 할 것을 발견 : 나는 원격 서버에 프록시하기 전에 API 호출을 제거하면Golang 리버스 프록시와 사용자 정의 인증

http: proxy error: http: ContentLength=139 with Body length 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 
     } 
     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} 
} 

을 그리고이 문제와 무엇

r.Use(AuthMiddleware) 
r.Post("/", NewReverseProxy(targets).ServeHTTP) 

을 라우팅 치을 사용하고 있습니다 이 구현?

+0

가장 먼저하는 일을한다 : 당신이 읽을 할 시체와 닫아? – RickyA

+1

http://stackoverflow.com/questions/31337891/net-http-http-contentlength-222-with-body-length-0 – RickyA

+0

[net/http : http : ContentLength = 222 body length 0의 가능한 중복] (http://stackoverflow.com/questions/31337891/net-http-http-contentlength-222-with-body-length-0) – stderr

답변

0

당신이 몸에 신경 쓰지 않으면 더 이상 당신 몸의 현재 상태를 반영, 0에 대한 요청의 contentlength을 설정할 수 있습니다 마음에 오는

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) 
    }) 
} 
+0

이 작품을 했습니까 ?? – RickyA