首页 > 其他 > 详细

简易反向代理

时间:2019-12-20 02:01:24      阅读:95      评论:0      收藏:0      [点我收藏+]
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)

}




简易反向代理

原文:https://www.cnblogs.com/hualou/p/12070698.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!