英文:
How to pass along an http Request in golang?
问题
我有一个在golang中的Request对象,并且我想通过net.Conn将这个对象的内容作为代理任务的一部分传递。我想要调用类似下面的代码:
req, err := http.ReadRequest(bufio.NewReader(conn_to_client))
conn_to_remote_server.Write(... ? ... )
但是我不知道应该传递什么参数。有什么建议吗?
英文:
I have a Request object in golang, and I would like to feed the contents of this object through a net.Conn as part of the task of a proxy.
I want to call something like
req, err := http.ReadRequest(bufio.NewReader(conn_to_client))
conn_to_remote_server.Write(... ? ... )
but I have no idea what I would be passing in as the arguments. Any advice would be appreciated.
答案1
得分: 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) //**<--------将请求传递给下一个中间件/函数**
} 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
英文:
Check out Negroni middleware. It let's you pass your HTTP request through different middleware and custom HandlerFuncs.
Something like this:
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...")
}
Notice how next(rw,r)
is used to pass along the HTTP request
If you don't want to use Negroni, you can always look at it's implementation on how it passes the HTTP request to another middleware.
It uses custom handler which looks something like:
handlerFunc func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)
Ref: https://gobridge.gitbooks.io/building-web-apps-with-go/content/en/middleware/index.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论