简易反向代理
Posted hualou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简易反向代理相关的知识,希望对你有一定的参考价值。
package main
import (
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
)
type ProxyHandler struct {
}
func (*ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
w.WriteHeader(500)
log.Println(err)
}
}()
if r.URL.Path == "/a" { //当访问localhost:8080/a就会转发到http://localhost:9091
newr, _ := http.NewRequest(r.Method, "http://localhost:9091", r.Body)
newResponse, _ := http.DefaultClient.Do(newr)
defer newResponse.Body.Close()
res_cont, _ := ioutil.ReadAll(newResponse.Body)
w.Write(res_cont)
return
}
w.Write([]byte("default index"))
}
func main() {
http.ListenAndServe(":8080", &ProxyHandler{})
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt)
s := <-c
log.Println(s)
}
以上是关于简易反向代理的主要内容,如果未能解决你的问题,请参考以下文章