mirror of
https://github.com/razertory/Ginx.git
synced 2020-01-07 15:43:17 +00:00
69 lines
1.2 KiB
Go
69 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"log"
|
|
"net/http"
|
|
"net/http/httputil"
|
|
"net/url"
|
|
"os"
|
|
)
|
|
|
|
type Config struct {
|
|
Server string `json:"server"`
|
|
Upstream []string `json:"upstream"`
|
|
}
|
|
|
|
var loadBalancer = NewWeightedRR(RR_NGINX)
|
|
|
|
type handle struct {
|
|
addrs []string
|
|
}
|
|
|
|
func (this *handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
addr := loadBalancer.Next().(string)
|
|
remote, err := url.Parse("http://" + addr)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
proxy := httputil.NewSingleHostReverseProxy(remote)
|
|
proxy.ServeHTTP(w, r)
|
|
}
|
|
|
|
func startServer(server string, upstream []string) {
|
|
//被代理的服务器host和port
|
|
h := &handle{}
|
|
h.addrs = upstream
|
|
|
|
w := 1
|
|
for _, e := range h.addrs {
|
|
loadBalancer.Add(e, w)
|
|
w++
|
|
}
|
|
err := http.ListenAndServe(server, h)
|
|
if err != nil {
|
|
log.Fatalln("ListenAndServe: ", err)
|
|
}
|
|
}
|
|
|
|
func readConfig() Config {
|
|
file, err := ioutil.ReadFile("./config.json")
|
|
if err != nil {
|
|
fmt.Printf("File error: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
var config Config
|
|
json.Unmarshal(file, &config)
|
|
fmt.Printf("%v", config.Upstream)
|
|
fmt.Printf("%v", config.Server)
|
|
return config
|
|
}
|
|
|
|
func main() {
|
|
config := readConfig()
|
|
startServer(config.Server, config.Upstream)
|
|
}
|