2016-02-28 174 views
1

我在golang中有一個Request對象,我想通過net.Conn作爲代理任務的一部分來提供此對象的內容。 我想打電話給像如何在golang中傳遞http請求?

req, err := http.ReadRequest(bufio.NewReader(conn_to_client)) 
conn_to_remote_server.Write(... ? ...) 

,但我不知道我會被傳遞的參數。任何意見,將不勝感激。

+0

爲了尋找靈感:https://github.com/elazarl/goproxy – elithrar

回答

0

檢查出Negroni中間件。它讓你通過不同的中間件和自定義的HandlerFuncs傳遞你的HTTP請求。 事情是這樣的:

n := negroni.New(
     negroni.NewRecovery(), 
     negroni.HandlerFunc(myMiddleware), 
     negroni.NewLogger(), 
     negroni.NewStatic(http.Dir("public")), 
    ) 

... 
... 

func myMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { 
    log.Println("Logging on the way there...") 

    if r.URL.Query().Get("password") == "secret123" { 
     next(rw, r)  //**<--------passing the request to next middleware/func** 
    } else { 
     http.Error(rw, "Not Authorized", 401) 
    } 

    log.Println("Logging on the way back...") 
} 

注意如何next(rw,r)用於沿HTTP請求

傳遞如果你不想使用內格羅尼,您可以隨時看它的實現它如何通過了HTTP請求另一箇中間件。

它使用自定義的處理,看起來是這樣的:

handlerFunc func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) 

編號:https://gobridge.gitbooks.io/building-web-apps-with-go/content/en/middleware/index.html