golang http proxy反向代理

本文介绍golang中如何进行反向代理。

下面例子中,
proxy server接收client 的 http request,转发给true server,并把 true server的返回结果再发送给client。

1.proxy server

proxyServer.go代码如下所示。

// proxyServer.go

package main

import (
    "log"
    "net/http"
    "net/http/httputil"
    "net/url"
)

//将request转发给 http://127.0.0.1:2003
func helloHandler(w http.ResponseWriter, r *http.Request) {
    
    trueServer := "http://127.0.0.1:2003"

    url, err := url.Parse(trueServer)
    if err != nil {
        log.Println(err)
        return
    }

    proxy := httputil.NewSingleHostReverseProxy(url)
    proxy.ServeHTTP(w, r)

}


func main() {
    http.HandleFunc("/hello", helloHandler)
    log.Fatal(http.ListenAndServe(":2002", nil))
}

proxyServer监听端口2002,提供HTTP request "/hello" 的转发服务。

其中,

func NewSingleHostReverseProxy

func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy

NewSingleHostReverseProxy 返回一个新的 ReverseProxy, 将URLs 请求路由到targe的指定的scheme, host, base path 。

如果target的path是"/base" ,client请求的URL是 "/dir", 则target 最后转发的请求就是 /base/dir。

2.true server

trueServer.go代码如下所示。

// trueServer.go

package main

import (
    "io"
    "net/http"
    "log"
)

func helloHandler(w http.ResponseWriter, req *http.Request) {
        io.WriteString(w, "hello, world!\n")
}

func main() {
        http.HandleFunc("/hello", helloHandler)
        log.Fatal(http.ListenAndServe(":2003", nil))
}

trueServer 作为一个HTTP server,监听端口2003,提供"/hello"的实际处理。

3.client

client代码如下

$ curl http://127.0.0.1:2002/hello
hello, world!

参考

ReverseProxy

猜你喜欢

转载自www.cnblogs.com/lanyangsh/p/10293051.html