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)
}

猜你喜欢

转载自blog.csdn.net/robin912/article/details/80921731