golang 之反向代理

golang 之反向代理

使用golang实现一个类似nginx的反向代理程序,处理react编译后的单页面部署.

func middleware1(next http.Handler, proxy http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Printf("request %v, %v, %v", r.Method, r.URL, r.Header.Get("Accept"))
        url1 := r.URL.Path
        if len(url1) == 4 && (url1 == "/401" || url1 == "/403") {
            url1 = "/"
            http.Redirect(w, r, "/", 300)
            return
        }

        re := regexp.MustCompile("(.js|.html|.css|.png|.ico|.map|.woff|.svg|.eot|.ttf|.jpg|.htm)$")
        if re.Find([]byte(url1)) != nil || url1 == "/" || strings.Contains(r.Header.Get("Accept"), "text/html") {
            next.ServeHTTP(w, r)
        } else {
            log.Println("request need redirect", r.Method, r.URL.Path, r.Host, r.PostForm)
            proxy.ServeHTTP(w, r)
        }
    })
}

func main() {
    conf, err := readConfig("config.json")
    checkErr(err, "read config file failed")
    fmt.Printf("read file %v", conf)

    fs := http.FileServer(http.Dir("public"))
    proxy := httputil.NewSingleHostReverseProxy(&url.URL{
        Scheme: "http",
        Host:   "127.0.0.1:8080",
    })
    http.Handle("/", middleware1(fs, proxy))

    log.Println("Listening...")
    http.ListenAndServe(":3000", nil)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值