From 55d72fd05378b55c7d574e8094a62e045d924552 Mon Sep 17 00:00:00 2001 From: Martin Polden Date: Sat, 16 Apr 2016 09:18:21 +0200 Subject: [PATCH] Add country lookup as separate handler --- api/api.go | 17 +++++++++++------ api/api_test.go | 3 ++- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/api/api.go b/api/api.go index 40fbbd6..56f1df4 100644 --- a/api/api.go +++ b/api/api.go @@ -142,15 +142,20 @@ func (a *API) newResponse(r *http.Request) (Response, error) { } func (a *API) CLIHandler(w http.ResponseWriter, r *http.Request) *appError { + ip, err := a.ipFromRequest(r) + if err != nil { + return internalServerError(err) + } + io.WriteString(w, ip.String()+"\n") + return nil +} + +func (a *API) CLICountryHandler(w http.ResponseWriter, r *http.Request) *appError { response, err := a.newResponse(r) if err != nil { return internalServerError(err) } - if r.URL.Path == "/country" { - io.WriteString(w, response.Country+"\n") - } else { - io.WriteString(w, response.IP.String()+"\n") - } + io.WriteString(w, response.Country+"\n") return nil } @@ -275,7 +280,7 @@ func (a *API) Handlers() http.Handler { // CLI r.Handle("/", appHandler(a.CLIHandler)).Methods("GET").MatcherFunc(cliMatcher) r.Handle("/ip", appHandler(a.CLIHandler)).Methods("GET").MatcherFunc(cliMatcher) - r.Handle("/country", appHandler(a.CLIHandler)).Methods("GET").MatcherFunc(cliMatcher) + r.Handle("/country", appHandler(a.CLICountryHandler)).Methods("GET").MatcherFunc(cliMatcher) // Browser r.Handle("/", appHandler(a.DefaultHandler)).Methods("GET") diff --git a/api/api_test.go b/api/api_test.go index 68554dc..9e67d26 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -50,7 +50,7 @@ func httpGet(url string, json bool, userAgent string) (string, int, error) { } func TestGetIP(t *testing.T) { - //log.SetOutput(ioutil.Discard) + log.SetOutput(ioutil.Discard) toJSON := func(r Response) string { b, err := json.Marshal(r) if err != nil { @@ -72,6 +72,7 @@ func TestGetIP(t *testing.T) { {s.URL, false, "127.0.0.1\n", "Go 1.1 package http", 200}, {s.URL, false, "127.0.0.1\n", "Go-http-client/1.1", 200}, {s.URL, false, "127.0.0.1\n", "Go-http-client/2.0", 200}, + {s.URL + "/country", false, "Elbonia\n", "curl/7.26.0", 200}, {s.URL, true, toJSON(Response{IP: net.ParseIP("127.0.0.1"), Country: "Elbonia", Hostname: "localhost"}), "", 200}, {s.URL + "/foo", false, "404 page not found", "curl/7.26.0", 404}, {s.URL + "/foo", true, "{\"error\":\"404 page not found\"}", "curl/7.26.0", 404},