シンプルなリバースプロキシ

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)

}




おすすめ

転載: www.cnblogs.com/hualou/p/12070698.html