mirror of
https://github.com/razertory/Ginx.git
synced 2020-01-07 15:43:17 +00:00
整理配置代码
This commit is contained in:
@@ -12,6 +12,7 @@
|
||||
*.out
|
||||
|
||||
.vscode/
|
||||
.idea/
|
||||
Ginx
|
||||
config.json
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user