From f3f2898e265b5aaa82e5cb08beba773df43aaea9 Mon Sep 17 00:00:00 2001 From: Yifu Yu Date: Mon, 28 Oct 2019 23:29:21 +0800 Subject: [PATCH] Add flags to specify server bind --- main.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 2ea3dff..9327b56 100644 --- a/main.go +++ b/main.go @@ -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) }