新增json配置

This commit is contained in:
chenlichun
2019-02-01 18:18:33 +08:00
parent 0daffdac22
commit 07804bc714
3 changed files with 37 additions and 4 deletions
+3
View File
@@ -10,3 +10,6 @@
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
.vscode/
Ginx
+4
View File
@@ -0,0 +1,4 @@
{
"server":":9999",
"upstreams": ["127.0.0.1:3000"]
}
+30 -4
View File
@@ -1,12 +1,22 @@
package main
import (
"encoding/json"
"net/http"
"net/url"
"net/http/httputil"
"log"
"flag"
"fmt"
"io/ioutil"
"os"
)
type Config struct {
Server string `json:"server"`
Upstream []string `json:"upstream"`
}
var loadBalancer = NewWeightedRR(RR_NGINX)
@@ -24,22 +34,38 @@ func (this *handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
proxy.ServeHTTP(w, r)
}
func startServer() {
func startServer(server string, upstream []string) {
//被代理的服务器host和port
h := &handle{}
h.addrs = []string{"127.0.0.1:3000"}
h.addrs = upstream
w := 1
for _, e := range h.addrs {
loadBalancer.Add(e, w)
w++
}
err := http.ListenAndServe(":9999", h)
err := http.ListenAndServe(server, h)
if err != nil {
log.Fatalln("ListenAndServe: ", err)
}
}
func main() {
startServer()
server := flag.String("server", ":9999", "Your server")
upstream := flag.String("upstream", "127.0.0.1:3000", "upstream server")
flag.Parse()
fmt.Println(*server)
fmt.Println(*upstream)
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)
// startServer(*server, *upstream)
startServer(config.Server, config.Upstream)
}