go - 如何在 golang 中传递 http 请求?

标签 go proxy network-programming

我在 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/

相关文章:

struct - 有没有办法强制转换结构以通过 channel 发送

django - 重负载下的扭曲连接超时

google-app-engine - 通过Regex Google数据存储区查询实体

Go模板将数据从一个传递到另一个

proxy - 带 Spring 的 CGLIB 抛出 IllegalAccessError

amazon-web-services - 将 ECR 配置为从 Docker Hub 拉取的代理

c++ - 读取多个(所有)未决数据报

ruby - 网络 - 要发送到服务器的数据

sql-server - Golang 连接到 SQL Server 错误 - "TLS Handshake failed: Cannot read handshake packet: EOF"

android - Android 代理设置是否适用于设备上的所有应用?