整理配置代码

This commit is contained in:
chenlichun
2019-02-02 11:04:28 +08:00
parent 9ac1615f28
commit c6e603ca0e
2 changed files with 32 additions and 30 deletions
+1
View File
@@ -12,6 +12,7 @@
*.out
.vscode/
.idea/
Ginx
config.json
+31 -30
View File
@@ -2,54 +2,52 @@ package main
import (
"encoding/json"
"net/http"
"net/url"
"net/http/httputil"
"log"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
)
type Config struct {
Server string `json:"server"`
Server string `json:"server"`
Upstream []string `json:"upstream"`
}
var loadBalancer = NewWeightedRR(RR_NGINX)
type handle struct {
addrs []string
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)
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
//被代理的服务器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)
}
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 main() {
func readConfig() Config {
file, err := ioutil.ReadFile("./config.json")
if err != nil {
fmt.Printf("File error: %v\n", err)
@@ -60,7 +58,10 @@ func main() {
json.Unmarshal(file, &config)
fmt.Printf("%v", config.Upstream)
fmt.Printf("%v", config.Server)
return config
}
// startServer(*server, *upstream)
startServer(config.Server, config.Upstream)
}
func main() {
config := readConfig()
startServer(config.Server, config.Upstream)
}