我在 golang 中有一个 Request 对象,我想通过 net.Conn 提供这个对象的内容作为代理任务的一部分。 我想调用类似的东西
req, err := http.ReadRequest(bufio.NewReader(conn_to_client))
conn_to_remote_server.Write(... ? ... )
但我不知道我将作为参数传递什么。任何建议将不胜感激。
最佳答案
查看 Negroni 中间件。它让您通过不同的中间件和自定义 HandlerFunc 传递 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 请求的
如果您不想使用 Negroni,您可以随时查看它的实现,了解它如何将 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
关于go - 如何在 golang 中传递 http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35677048/