2016-02-28 176 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