Add flags to specify server bind

This commit is contained in:
Yifu Yu 2019-10-28 23:29:21 +08:00
parent 1018ff016f
commit f3f2898e26
1 changed files with 9 additions and 2 deletions

11
main.go
View File

@ -4,6 +4,7 @@ import (
"encoding/json"
"flag"
"fmt"
"log"
"net"
"net/http"
_ "net/http/pprof"
@ -23,6 +24,10 @@ type errorMessage struct {
Error string `json:error`
}
var (
listen_spec = flag.String("bind", "127.0.0.1:8086", "http server bind spec")
)
func responseWithError(resp http.ResponseWriter, statusCode int, message string) {
resp.Header().Set("Content-Type", "text/plain")
resp.WriteHeader(statusCode)
@ -34,11 +39,11 @@ func responseWithJsonError(resp http.ResponseWriter, statusCode int, message str
body, err := json.Marshal(&errorMessage{
Error: message,
})
resp.Header().Set("Content-Length", strconv.Itoa(len(body)))
if err != nil {
// This should never happen
panic("json marshal failed, check code")
}
resp.Header().Set("Content-Length", strconv.Itoa(len(body)))
resp.WriteHeader(statusCode)
resp.Write(body)
}
@ -132,8 +137,10 @@ func main() {
resp.Header().Set("Content-Type", "text/plain")
resp.WriteHeader(http.StatusOK)
server := mapping.Get(ip)
log.Printf("%s => %s\n", ip, server)
fmt.Fprint(resp, server)
})
ipgeo.Init()
http.ListenAndServe("0.0.0.0:8086", nil)
log.Println("HTTP server is running on", *listen_spec)
http.ListenAndServe(*listen_spec, nil)
}