duanfuxing2212 2019-04-14 23:57
浏览 34
已采纳

如何制作反向代理?

I have a server written in Go. I want to write for it a reverse proxy server. The server is compiled into one binary file. When I try to access it through a proxy server, it returns only the HTML page without bindings to CSS and JS scripts. How can I organize the transfer of static files?

package main

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

func main() {
    mux := http.NewServeMux()
    u1, _ := url.Parse("http://localhost:8080/")
    proxy := httputil.NewSingleHostReverseProxy(u1)
    mux.Handle("/app1", proxy)

    serv := &http.Server{
        Addr:           ":9090",
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        Handler:        mux,
    }

    err := serv.ListenAndServe()
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }

}

展开全部

  • 写回答

1条回答 默认 最新

  • dtqie02844 2019-04-15 00:08
    关注

    Writing a reverse proxy is a complex task. If you plan to expose it on the public internet, I suggest to use an existing one, e.g. Caddyserver, which is written in Go and still free if you compile it yourself instead of using the pre-compiled binaries. The source code of Caddyserver can also give you ideas how to implement it on your own, if you still want to pursue that idea.

    To your more specific question about serving files: This can be done with the http.ServeFile method or easier with httprouter's ServeFiles or FileServer methods. See https://github.com/julienschmidt/httprouter#static-files.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部