WebRouter
WebRouter copied to clipboard
代码不规范,亲人两行泪~
package main
import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "log" "net" "os" "regexp" "strings" )
type rule struct {
Domain string json:Domain
Address string json:Address
}
type config struct {
MainPort string json:MainPort
rules []rule json:rules
}
var myconfig config
func initconfig() { var Data, err = ioutil.ReadFile("config.json") if err != nil { log.Println("Read config File Error!") os.Exit(0) return } err = json.Unmarshal(Data, &myconfig) if err != nil { log.Println("Read config JSON Error!Please Check!") os.Exit(0) return } fmt.Println("Main Port:" + myconfig.MainPort) for i := 0; i < len(myconfig.rules); i++ { fmt.Println("Domain: " + myconfig.rules[i].Domain + " <----> " + myconfig.rules[i].Address) } } func handleClientRequest(client net.Conn) { if client == nil { return } defer client.Close() var b [1024]byte n, err := client.Read(b[:]) if err != nil { log.Println(err) return } var method, url, HTTPv, address string fmt.Sscanf(string(b[:bytes.IndexByte(b[:], '\n')]), "%s%s%s", &method, &url, &HTTPv) address = getaddress(string(b[:])) if address == "nil" { fmt.Println("Unknow Domain") return } server, err := net.Dial("tcp", address) if err != nil { log.Println(err) return } if method == "CONNECT" { fmt.Fprint(client, "HTTP/1.1 200 Connection established\r\n\r\n") } else { server.Write(b[:n]) } go io.Copy(server, client) io.Copy(client, server) } func getaddress(HTTPData string) string { Lines := strings.Split(HTTPData, "\r\n") for i := 0; i < len(Lines); i++ { line := Lines[i] temp := strings.Split(line, ": ") if strings.Compare(temp[0], "Host") == 0 { for i := 0; i < len(myconfig.rules); i++ { if strings.Compare(myconfig.rules[i].Domain, temp[1]) == 0 { return myconfig.rules[i].Address } } } } return "nil" } func compressStr(str string) string { if str == "" { return "" } reg := regexp.MustCompile("\s+") return reg.ReplaceAllString(str, "") } func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) initconfig() l, err := net.Listen("tcp", ":"+myconfig.MainPort) if err != nil { log.Panic(err) } for { client, err := l.Accept() if err != nil { log.Panic(err) } go handleClientRequest(client) } }
结构体小写开头 函数名小写开头 复制粘贴后调试时,还能丢失括号。。