使用go实现反向代理

版权声明:本文为博主原创文章,欢迎大家讨论,未经博主允许不得转载. https://blog.csdn.net/u010398771/article/details/84256796

今天让大家看看用go写了一个反向代理,真的非常的简单,比用java写的简单多了,而且非常好理解,感觉go确实非常适用写各种中间件.好了,大家看代码.


package main

import (
    _ "fmt"
    "io"
    _ "log"
    "net/http"
    "net/http/httputil"
    "net/url"
    _ "strings"
)

func main() {
    /*localHost := "127.0.0.1:9293"
    targetHost := "127.0.0.1:29383"
    httpsServer(localHost, targetHost)
    var err error = nil*/
    http.HandleFunc("/", ServeHTTP)
    //    http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    //        if req.RequestURI == "/favicon.ico" {
    //            io.WriteString(w, "Request path Error")
    //            return
    //        }
    //        fmt.Println(req.RequestURI)
    //        fmt.Fprintf(w, req.RequestURI)
    //    })
    http.ListenAndServe(":8085", nil)
}

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if r.RequestURI == "/favicon.ico" {
        io.WriteString(w, "Request path Error")
        return
    }
    remote, err := url.Parse("http://" + "127.0.0.1:80")
    if err != nil {
        panic(err)
    }
    proxy := httputil.NewSingleHostReverseProxy(remote)
    proxy.ServeHTTP(w, r)
}
 

就是这么的简单,首先监听本机的8085端口,然后分发请求到本机的80端口上面去,就完成了代理的过程,只需要启动这个go程序就够了.

这个程序的下一步优化就是怎么根据服务进行服务器的ip(127.0.0.1:80),端口号的获取了,不能这样固定的写死,就能做到灵活的进行配置了.就是相当于进行服务的注册,当然下面还有很大的优化的空间.

这是我正在学习go的同事陈磊大大写的,我写的就是一个简单的web服务器,多个请求的统一处理,以后再分享出来.

因为之前的JetBrains GoLand 过期了,就换了一个IDE,安利一下 国人做的go的编辑器把,LiteIDE,俺用了这么多年的英文的IDE,终于见到了一个汉字的,还有点不习惯,哈哈.还是很方便的.一些功能也有待加强,例如Git的集成,直接在IDE 进行代码的管理.

好了,今天就写这么多.

猜你喜欢

转载自blog.csdn.net/u010398771/article/details/84256796