[Go]基于Go语言的Web路由转发,多个网站共享一个端口(新版本,支持WebSocket)

之前编写过一个Web路由转发,可以参考我之前的博客

之前的版本具有很多问题,所前段时间一直很忙,在做我的新东西和实习,所以就一直没更新

今天忙里偷闲,就更新一下Web路由

主要解决的还是多语言Web开发时,整合至一个端口的问题

当然除了这个功能,还有很多有趣的用法,比如网站镜像,绕过备案等玩法

废话不说直接上代码

package main

import(
    "log"
    "strings"
    "net/http"
    "io/ioutil"
    "encoding/json"
    "github.com/vulcand/oxy/forward"
      "github.com/vulcand/oxy/testutils"
)

type Rule struct{
    Domain string `json:Domain`
    Address string `json:Address`
}
type Setting struct{
    MainPort string `json:MainPort`
    Rules []Rule `json:Rules`
}

var setting Setting
var fwd *forward.Forwarder

func redirectHandle(w http.ResponseWriter, r *http.Request){
    address := getAddress(r.Host)
    if address != "" {
        r.URL = testutils.ParseURI("http://"+address)
        log.Println("Info: "+r.Host+" => "+address)
        fwd.ServeHTTP(w, r)
    } else {
        w.WriteHeader(500)
    }
}

func getAddress(host string) string {
    for _,v := range setting.Rules {
        if strings.Compare(host,v.Domain) == 0 {
            return v.Address
        }
    }
    return ""
}

func Init(){
    var Data,err = ioutil.ReadFile("setting.json")
    if err != nil{
        log.Fatal("Read Config File Error!")
        return
    }
    err = json.Unmarshal(Data,&setting)
    if err != nil{
        log.Fatal("Read Config JSON Error!Please Check!")
        return
    }
    log.Println("Main Port: "+setting.MainPort)
    for i:=0;i<len(setting.Rules);i++{
        log.Println("Import Rule: "+setting.Rules[i].Domain+" <----> "+setting.Rules[i].Address)
    }
}

func main(){
    Init()
    fwd, _ = forward.New()
    redirect := http.HandlerFunc(redirectHandle)
    s := &http.Server{
        Addr:           ":"+setting.MainPort,
        Handler:        redirect,
    }
    log.Println("Info: Listening port "+s.Addr)
    s.ListenAndServe()
}

下面是配置文件

{
    "MainPort": "80",
    "Rules": [
        {
            "Domain":"bt.onlinecode.cn",
            "Address":"123.207.241.119:88"
        },
        {
            "Domain":"test.onlinecode.cn",
            "Address":"123.207.241.119"
        }
    ]
}

MainPort:监听的主端口

Rules:就是定义的相关规则,Domain是绑定的IP或域名,Address就是真实的地址

下面是运行输出

下面是项目地址:

https://github.com/leeli73/WebRouter

包括Windows x64和Linux x64的几个release

posted @ 2019-08-02 11:05  leeli73  阅读(1266)  评论(0编辑  收藏  举报