码迷,mamicode.com
首页 > 其他好文 > 详细

简易反向代理

时间:2019-12-19 23:31:45      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:main   local   pac   div   lis   new   笔记   make   imp   

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)

}




简易反向代理

标签:main   local   pac   div   lis   new   笔记   make   imp   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!