用 golang 实现两个服务:反向代理服务和静态文件服务。
我用的是goji 框架,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
package main
import (
"net/http"
"net/http/httputil"
"net/url"
"github.com/golang/glog"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
)
type handle struct {
host string
port string
}
func (this *handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
remote, err := url.Parse("http://" + this.host + ":" + this.port)
if err != nil {
panic(err)
}
proxy := httputil.NewSingleHostReverseProxy(remote)
proxy.ServeHTTP(w, r)
}
func main() {
defer glog.Flush()
// proxy
h := &handle{host: "www.baidu.com", port: "8080"}
http.Handle("/proxy/", http.StripPrefix("/proxy/", h))
// Setup static files
static := web.New()
publicPath := "static"
static.Get("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir(publicPath))))
http.Handle("/static/", static)
goji.Serve()
}
/proxy
/static
本文网址: https://golangnote.com/topic/132.html 转摘请注明来源