猿问

如何在golang中传递http请求?

我在 golang 中有一个 Request 对象,我想通过 net.Conn 作为代理任务的一部分提供这个对象的内容。我想打电话给类似的东西


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

conn_to_remote_server.Write(... ? ... )

但我不知道我会传入什么作为参数。任何意见,将不胜感激。


拉丁的传说
浏览 147回答 1
1回答

慕雪6442864

查看 Negroni 中间件。它让您通过不同的中间件和自定义 HandlerFuncs 传递您的 HTTP 请求。像这样的东西:&nbsp; &nbsp;n := negroni.New(&nbsp; &nbsp; &nbsp; &nbsp; negroni.NewRecovery(),&nbsp; &nbsp; &nbsp; &nbsp; negroni.HandlerFunc(myMiddleware),&nbsp; &nbsp; &nbsp; &nbsp; negroni.NewLogger(),&nbsp; &nbsp; &nbsp; &nbsp; negroni.NewStatic(http.Dir("public")),&nbsp; &nbsp; )......func myMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {&nbsp; &nbsp; log.Println("Logging on the way there...")&nbsp; &nbsp; if r.URL.Query().Get("password") == "secret123" {&nbsp; &nbsp; &nbsp; &nbsp; next(rw, r)&nbsp; &nbsp; &nbsp; //**<--------passing the request to next middleware/func**&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; http.Error(rw, "Not Authorized", 401)&nbsp; &nbsp; }&nbsp; &nbsp; 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
随时随地看视频慕课网APP

相关分类

Go
我要回答