mirror of
https://github.com/mpolden/echoip.git
synced 2025-01-13 03:37:21 +01:00
Refactor
This commit is contained in:
parent
b156182a80
commit
f4420781a2
207
api/api.go
207
api/api.go
@ -3,81 +3,58 @@ package api
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"html/template"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"html/template"
|
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
geoip2 "github.com/oschwald/geoip2-golang"
|
geoip2 "github.com/oschwald/geoip2-golang"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const APPLICATION_JSON = "application/json"
|
||||||
IP_HEADER = "x-ifconfig-ip"
|
|
||||||
COUNTRY_HEADER = "x-ifconfig-country"
|
|
||||||
HOSTNAME_HEADER = "x-ifconfig-hostname"
|
|
||||||
TEXT_PLAIN = "text/plain; charset=utf-8"
|
|
||||||
APPLICATION_JSON = "application/json"
|
|
||||||
)
|
|
||||||
|
|
||||||
var cliUserAgentExp = regexp.MustCompile(`^(?i)((curl|wget|fetch\slibfetch|Go-http-client)\/.*|Go\s1\.1\spackage\shttp)$`)
|
var cliUserAgentExp = regexp.MustCompile(`^(?i)((curl|wget|fetch\slibfetch|Go-http-client)\/.*|Go\s1\.1\spackage\shttp)$`)
|
||||||
|
|
||||||
type API struct {
|
type API struct {
|
||||||
CORS bool
|
CORS bool
|
||||||
ReverseLookup bool
|
|
||||||
Template string
|
Template string
|
||||||
lookupAddr func(string) ([]string, error)
|
lookupAddr func(string) ([]string, error)
|
||||||
lookupCountry func(net.IP) (string, error)
|
lookupCountry func(net.IP) (string, error)
|
||||||
ipFromRequest func(*http.Request) (net.IP, error)
|
ipFromRequest func(*http.Request) (net.IP, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Response struct {
|
||||||
|
IP net.IP `json:"ip"`
|
||||||
|
Country string `json:"country,omitempty"`
|
||||||
|
Hostname string `json:"hostname,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
func New() *API {
|
func New() *API {
|
||||||
return &API{
|
return &API{
|
||||||
lookupAddr: net.LookupAddr,
|
lookupAddr: func(addr string) (names []string, err error) { return nil, nil },
|
||||||
lookupCountry: func(ip net.IP) (string, error) { return "", nil },
|
lookupCountry: func(ip net.IP) (string, error) { return "", nil },
|
||||||
ipFromRequest: ipFromRequest,
|
ipFromRequest: ipFromRequest,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewWithGeoIP(filepath string) (*API, error) {
|
func (a *API) EnableCountryLookup(filepath string) error {
|
||||||
db, err := geoip2.Open(filepath)
|
db, err := geoip2.Open(filepath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return err
|
||||||
}
|
}
|
||||||
api := New()
|
a.lookupCountry = func(ip net.IP) (string, error) {
|
||||||
api.lookupCountry = func(ip net.IP) (string, error) {
|
|
||||||
return lookupCountry(db, ip)
|
return lookupCountry(db, ip)
|
||||||
}
|
}
|
||||||
return api, nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type Cmd struct {
|
func (a *API) EnableReverseLookup() {
|
||||||
Name string
|
a.lookupAddr = net.LookupAddr
|
||||||
Args string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Cmd) String() string {
|
|
||||||
return c.Name + " " + c.Args
|
|
||||||
}
|
|
||||||
|
|
||||||
func cmdFromQueryParams(values url.Values) Cmd {
|
|
||||||
cmd, exists := values["cmd"]
|
|
||||||
if !exists || len(cmd) == 0 {
|
|
||||||
return Cmd{Name: "curl"}
|
|
||||||
}
|
|
||||||
switch cmd[0] {
|
|
||||||
case "fetch":
|
|
||||||
return Cmd{Name: "fetch", Args: "-qo -"}
|
|
||||||
case "wget":
|
|
||||||
return Cmd{Name: "wget", Args: "-qO -"}
|
|
||||||
}
|
|
||||||
return Cmd{Name: "curl"}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ipFromRequest(r *http.Request) (net.IP, error) {
|
func ipFromRequest(r *http.Request) (net.IP, error) {
|
||||||
@ -99,19 +76,6 @@ func ipFromRequest(r *http.Request) (net.IP, error) {
|
|||||||
return ip, nil
|
return ip, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func headerPairFromRequest(r *http.Request) (string, string, error) {
|
|
||||||
vars := mux.Vars(r)
|
|
||||||
header, ok := vars["header"]
|
|
||||||
if !ok {
|
|
||||||
header = IP_HEADER
|
|
||||||
}
|
|
||||||
value := r.Header.Get(header)
|
|
||||||
if value == "" {
|
|
||||||
return "", "", fmt.Errorf("no value found for: %s", header)
|
|
||||||
}
|
|
||||||
return header, value, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func lookupCountry(db *geoip2.Reader, ip net.IP) (string, error) {
|
func lookupCountry(db *geoip2.Reader, ip net.IP) (string, error) {
|
||||||
if db == nil {
|
if db == nil {
|
||||||
return "", nil
|
return "", nil
|
||||||
@ -126,71 +90,77 @@ func lookupCountry(db *geoip2.Reader, ip net.IP) (string, error) {
|
|||||||
if country, exists := record.RegisteredCountry.Names["en"]; exists {
|
if country, exists := record.RegisteredCountry.Names["en"]; exists {
|
||||||
return country, nil
|
return country, nil
|
||||||
}
|
}
|
||||||
return "", fmt.Errorf("could not determine country for IP: %s", ip)
|
return "Unknown", fmt.Errorf("could not determine country for IP: %s", ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *API) DefaultHandler(w http.ResponseWriter, r *http.Request) *appError {
|
func (a *API) newResponse(r *http.Request) (Response, error) {
|
||||||
cmd := cmdFromQueryParams(r.URL.Query())
|
ip, err := a.ipFromRequest(r)
|
||||||
funcMap := template.FuncMap{"ToLower": strings.ToLower}
|
if err != nil {
|
||||||
t, err := template.New(filepath.Base(a.Template)).Funcs(funcMap).ParseFiles(a.Template)
|
return Response{}, err
|
||||||
|
}
|
||||||
|
country, err := a.lookupCountry(ip)
|
||||||
|
if err != nil {
|
||||||
|
log.Print(err)
|
||||||
|
}
|
||||||
|
hostnames, err := a.lookupAddr(ip.String())
|
||||||
|
if err != nil {
|
||||||
|
log.Print(err)
|
||||||
|
}
|
||||||
|
return Response{
|
||||||
|
IP: ip,
|
||||||
|
Country: country,
|
||||||
|
Hostname: strings.Join(hostnames, " "),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *API) CLIHandler(w http.ResponseWriter, r *http.Request) *appError {
|
||||||
|
response, err := a.newResponse(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return internalServerError(err)
|
return internalServerError(err)
|
||||||
}
|
}
|
||||||
b, err := json.MarshalIndent(r.Header, "", " ")
|
if r.URL.Path == "/country" {
|
||||||
if err != nil {
|
io.WriteString(w, response.Country+"\n")
|
||||||
return internalServerError(err)
|
} else {
|
||||||
}
|
io.WriteString(w, response.IP.String()+"\n")
|
||||||
|
|
||||||
var data = struct {
|
|
||||||
IP string
|
|
||||||
JSON string
|
|
||||||
Header http.Header
|
|
||||||
Cmd
|
|
||||||
}{r.Header.Get(IP_HEADER), string(b), r.Header, cmd}
|
|
||||||
|
|
||||||
if err := t.Execute(w, &data); err != nil {
|
|
||||||
return internalServerError(err)
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *API) JSONHandler(w http.ResponseWriter, r *http.Request) *appError {
|
func (a *API) JSONHandler(w http.ResponseWriter, r *http.Request) *appError {
|
||||||
k, v, err := headerPairFromRequest(r)
|
response, err := a.newResponse(r)
|
||||||
contentType := APPLICATION_JSON
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return notFound(err).WithContentType(contentType)
|
return internalServerError(err).AsJSON()
|
||||||
}
|
}
|
||||||
value := map[string]string{k: v}
|
b, err := json.Marshal(response)
|
||||||
b, err := json.MarshalIndent(value, "", " ")
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return internalServerError(err).WithContentType(contentType)
|
return internalServerError(err).AsJSON()
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", contentType)
|
w.Header().Set("Content-Type", APPLICATION_JSON)
|
||||||
w.Write(b)
|
w.Write(b)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *API) JSONAllHandler(w http.ResponseWriter, r *http.Request) *appError {
|
func (a *API) DefaultHandler(w http.ResponseWriter, r *http.Request) *appError {
|
||||||
contentType := APPLICATION_JSON
|
response, err := a.newResponse(r)
|
||||||
b, err := json.MarshalIndent(r.Header, "", " ")
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return internalServerError(err).WithContentType(contentType)
|
return internalServerError(err)
|
||||||
|
}
|
||||||
|
t, err := template.New(filepath.Base(a.Template)).ParseFiles(a.Template)
|
||||||
|
if err != nil {
|
||||||
|
return internalServerError(err)
|
||||||
|
}
|
||||||
|
if err := t.Execute(w, &response); err != nil {
|
||||||
|
return internalServerError(err)
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", contentType)
|
|
||||||
w.Write(b)
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *API) CLIHandler(w http.ResponseWriter, r *http.Request) *appError {
|
func (a *API) NotFoundHandler(w http.ResponseWriter, r *http.Request) *appError {
|
||||||
_, v, err := headerPairFromRequest(r)
|
err := notFound(nil).WithMessage("404 page not found")
|
||||||
if err != nil {
|
if r.Header.Get("accept") == APPLICATION_JSON {
|
||||||
return notFound(err)
|
err = err.AsJSON()
|
||||||
}
|
}
|
||||||
if !strings.HasSuffix(v, "\n") {
|
return err
|
||||||
v += "\n"
|
|
||||||
}
|
|
||||||
io.WriteString(w, v)
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func cliMatcher(r *http.Request, rm *mux.RouteMatch) bool {
|
func cliMatcher(r *http.Request, rm *mux.RouteMatch) bool {
|
||||||
@ -199,25 +169,6 @@ func cliMatcher(r *http.Request, rm *mux.RouteMatch) bool {
|
|||||||
|
|
||||||
func (a *API) requestFilter(next http.Handler) http.Handler {
|
func (a *API) requestFilter(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
ip, err := a.ipFromRequest(r)
|
|
||||||
if err != nil {
|
|
||||||
log.Print(err)
|
|
||||||
r.Header.Set(IP_HEADER, "")
|
|
||||||
} else {
|
|
||||||
r.Header.Set(IP_HEADER, ip.String())
|
|
||||||
country, err := a.lookupCountry(ip)
|
|
||||||
if err != nil {
|
|
||||||
log.Print(err)
|
|
||||||
}
|
|
||||||
r.Header.Set(COUNTRY_HEADER, country)
|
|
||||||
}
|
|
||||||
if a.ReverseLookup {
|
|
||||||
hostname, err := a.lookupAddr(ip.String())
|
|
||||||
if err != nil {
|
|
||||||
log.Print(err)
|
|
||||||
}
|
|
||||||
r.Header.Set(HOSTNAME_HEADER, strings.Join(hostname, ", "))
|
|
||||||
}
|
|
||||||
if a.CORS {
|
if a.CORS {
|
||||||
w.Header().Set("Access-Control-Allow-Methods", "GET")
|
w.Header().Set("Access-Control-Allow-Methods", "GET")
|
||||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
@ -233,27 +184,23 @@ func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
if e.Error != nil {
|
if e.Error != nil {
|
||||||
log.Print(e.Error)
|
log.Print(e.Error)
|
||||||
}
|
}
|
||||||
contentType := e.ContentType
|
// When Content-Type for error is JSON, we need to marshal the response into JSON
|
||||||
if contentType == "" {
|
|
||||||
contentType = TEXT_PLAIN
|
|
||||||
}
|
|
||||||
response := e.Response
|
|
||||||
if response == "" {
|
|
||||||
response = e.Error.Error()
|
|
||||||
}
|
|
||||||
if e.IsJSON() {
|
if e.IsJSON() {
|
||||||
var data = struct {
|
var data = struct {
|
||||||
Error string `json:"error"`
|
Error string `json:"error"`
|
||||||
}{response}
|
}{e.Message}
|
||||||
b, err := json.MarshalIndent(data, "", " ")
|
b, err := json.Marshal(data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
response = string(b)
|
e.Message = string(b)
|
||||||
|
}
|
||||||
|
// Set Content-Type of response if set in error
|
||||||
|
if e.ContentType != "" {
|
||||||
|
w.Header().Set("Content-Type", e.ContentType)
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", contentType)
|
|
||||||
w.WriteHeader(e.Code)
|
w.WriteHeader(e.Code)
|
||||||
io.WriteString(w, response)
|
io.WriteString(w, e.Message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -262,18 +209,18 @@ func (a *API) Handlers() http.Handler {
|
|||||||
|
|
||||||
// JSON
|
// JSON
|
||||||
r.Handle("/", appHandler(a.JSONHandler)).Methods("GET").Headers("Accept", APPLICATION_JSON)
|
r.Handle("/", appHandler(a.JSONHandler)).Methods("GET").Headers("Accept", APPLICATION_JSON)
|
||||||
r.Handle("/all", appHandler(a.JSONAllHandler)).Methods("GET").Headers("Accept", APPLICATION_JSON)
|
|
||||||
r.Handle("/all.json", appHandler(a.JSONAllHandler)).Methods("GET")
|
|
||||||
r.Handle("/{header}", appHandler(a.JSONHandler)).Methods("GET").Headers("Accept", APPLICATION_JSON)
|
|
||||||
r.Handle("/{header}.json", appHandler(a.JSONHandler)).Methods("GET")
|
|
||||||
|
|
||||||
// CLI
|
// CLI
|
||||||
r.Handle("/", appHandler(a.CLIHandler)).Methods("GET").MatcherFunc(cliMatcher)
|
r.Handle("/", appHandler(a.CLIHandler)).Methods("GET").MatcherFunc(cliMatcher)
|
||||||
r.Handle("/{header}", 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)
|
||||||
|
|
||||||
// Default
|
// Browser
|
||||||
r.Handle("/", appHandler(a.DefaultHandler)).Methods("GET")
|
r.Handle("/", appHandler(a.DefaultHandler)).Methods("GET")
|
||||||
|
|
||||||
|
// Not found handler which returns JSON when appropriate
|
||||||
|
r.NotFoundHandler = appHandler(a.NotFoundHandler)
|
||||||
|
|
||||||
// Pass all requests through the request filter
|
// Pass all requests through the request filter
|
||||||
return a.requestFilter(r)
|
return a.requestFilter(r)
|
||||||
}
|
}
|
||||||
|
@ -1,14 +1,12 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"encoding/json"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"net/url"
|
|
||||||
"reflect"
|
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
@ -24,7 +22,6 @@ func newTestAPI() *API {
|
|||||||
ipFromRequest: func(*http.Request) (net.IP, error) {
|
ipFromRequest: func(*http.Request) (net.IP, error) {
|
||||||
return net.ParseIP("127.0.0.1"), nil
|
return net.ParseIP("127.0.0.1"), nil
|
||||||
},
|
},
|
||||||
ReverseLookup: true,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -50,16 +47,15 @@ func httpGet(url string, json bool, userAgent string) (string, int, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestGetIP(t *testing.T) {
|
func TestGetIP(t *testing.T) {
|
||||||
log.SetOutput(ioutil.Discard)
|
//log.SetOutput(ioutil.Discard)
|
||||||
toJSON := func(k string, v string) string {
|
toJSON := func(r Response) string {
|
||||||
return fmt.Sprintf("{\n \"%s\": \"%s\"\n}", k, v)
|
b, err := json.Marshal(r)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
}
|
}
|
||||||
s := httptest.NewServer(newTestAPI().Handlers())
|
s := httptest.NewServer(newTestAPI().Handlers())
|
||||||
jsonAll := "{\n \"Accept-Encoding\": [\n \"gzip\"\n ]," +
|
|
||||||
"\n \"X-Ifconfig-Country\": [\n \"Elbonia\"\n ]," +
|
|
||||||
"\n \"X-Ifconfig-Hostname\": [\n \"localhost\"\n ]," +
|
|
||||||
"\n \"X-Ifconfig-Ip\": [\n \"127.0.0.1\"\n ]\n}"
|
|
||||||
|
|
||||||
var tests = []struct {
|
var tests = []struct {
|
||||||
url string
|
url string
|
||||||
json bool
|
json bool
|
||||||
@ -73,11 +69,9 @@ 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 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/1.1", 200},
|
||||||
{s.URL, false, "127.0.0.1\n", "Go-http-client/2.0", 200},
|
{s.URL, false, "127.0.0.1\n", "Go-http-client/2.0", 200},
|
||||||
{s.URL + "/x-ifconfig-ip.json", false, toJSON("x-ifconfig-ip", "127.0.0.1"), "", 200},
|
{s.URL, true, toJSON(Response{IP: net.ParseIP("127.0.0.1"), Country: "Elbonia", Hostname: "localhost"}), "", 200},
|
||||||
{s.URL, true, toJSON("x-ifconfig-ip", "127.0.0.1"), "", 200},
|
{s.URL + "/foo", false, "404 page not found", "curl/7.26.0", 404},
|
||||||
{s.URL + "/foo", false, "no value found for: foo", "curl/7.26.0", 404},
|
{s.URL + "/foo", true, "{\"error\":\"404 page not found\"}", "curl/7.26.0", 404},
|
||||||
{s.URL + "/foo", true, "{\n \"error\": \"no value found for: foo\"\n}", "curl/7.26.0", 404},
|
|
||||||
{s.URL + "/all.json", false, jsonAll, "", 200},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
@ -97,7 +91,6 @@ func TestGetIP(t *testing.T) {
|
|||||||
func TestGetIPWithoutReverse(t *testing.T) {
|
func TestGetIPWithoutReverse(t *testing.T) {
|
||||||
log.SetOutput(ioutil.Discard)
|
log.SetOutput(ioutil.Discard)
|
||||||
api := newTestAPI()
|
api := newTestAPI()
|
||||||
api.ReverseLookup = false
|
|
||||||
s := httptest.NewServer(api.Handlers())
|
s := httptest.NewServer(api.Handlers())
|
||||||
|
|
||||||
out, _, err := httpGet(s.URL, false, "curl/7.26.0")
|
out, _, err := httpGet(s.URL, false, "curl/7.26.0")
|
||||||
@ -128,25 +121,6 @@ func TestIPFromRequest(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCmdFromParameters(t *testing.T) {
|
|
||||||
var tests = []struct {
|
|
||||||
in url.Values
|
|
||||||
out Cmd
|
|
||||||
}{
|
|
||||||
{url.Values{}, Cmd{Name: "curl"}},
|
|
||||||
{url.Values{"cmd": []string{"foo"}}, Cmd{Name: "curl"}},
|
|
||||||
{url.Values{"cmd": []string{"curl"}}, Cmd{Name: "curl"}},
|
|
||||||
{url.Values{"cmd": []string{"fetch"}}, Cmd{Name: "fetch", Args: "-qo -"}},
|
|
||||||
{url.Values{"cmd": []string{"wget"}}, Cmd{Name: "wget", Args: "-qO -"}},
|
|
||||||
}
|
|
||||||
for _, tt := range tests {
|
|
||||||
cmd := cmdFromQueryParams(tt.in)
|
|
||||||
if !reflect.DeepEqual(cmd, tt.out) {
|
|
||||||
t.Errorf("Expected %+v, got %+v", tt.out, cmd)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCLIMatcher(t *testing.T) {
|
func TestCLIMatcher(t *testing.T) {
|
||||||
browserUserAgent := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) " +
|
browserUserAgent := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) " +
|
||||||
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.28 " +
|
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.28 " +
|
||||||
|
16
api/error.go
16
api/error.go
@ -4,21 +4,25 @@ import "net/http"
|
|||||||
|
|
||||||
type appError struct {
|
type appError struct {
|
||||||
Error error
|
Error error
|
||||||
Response string
|
Message string
|
||||||
Code int
|
Code int
|
||||||
ContentType string
|
ContentType string
|
||||||
}
|
}
|
||||||
|
|
||||||
func internalServerError(err error) *appError {
|
func internalServerError(err error) *appError {
|
||||||
return &appError{Error: err, Response: "Internal server error", Code: http.StatusInternalServerError}
|
return &appError{
|
||||||
|
Error: err,
|
||||||
|
Message: "Internal server error",
|
||||||
|
Code: http.StatusInternalServerError,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func notFound(err error) *appError {
|
func notFound(err error) *appError {
|
||||||
return &appError{Error: err, Code: http.StatusNotFound}
|
return &appError{Error: err, Code: http.StatusNotFound}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *appError) WithContentType(contentType string) *appError {
|
func (e *appError) AsJSON() *appError {
|
||||||
e.ContentType = contentType
|
e.ContentType = APPLICATION_JSON
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -27,8 +31,8 @@ func (e *appError) WithCode(code int) *appError {
|
|||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *appError) WithResponse(response string) *appError {
|
func (e *appError) WithMessage(message string) *appError {
|
||||||
e.Response = response
|
e.Message = message
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
|
|
||||||
|
105
index.html
105
index.html
@ -8,75 +8,80 @@
|
|||||||
<link href="//fonts.googleapis.com/css?family=Oswald" rel="stylesheet">
|
<link href="//fonts.googleapis.com/css?family=Oswald" rel="stylesheet">
|
||||||
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/pure/0.6.0/pure-min.css">
|
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/pure/0.6.0/pure-min.css">
|
||||||
<style>
|
<style>
|
||||||
body {
|
html, .pure-g [class *= "pure-u"] {
|
||||||
font-family: "Oswald", sans-serif;
|
font-family: "Oswald", sans-serif;
|
||||||
font-size: 12px;
|
font-size: 15pt;
|
||||||
}
|
}
|
||||||
.response {
|
pre {
|
||||||
font-family: "Monaco", "Menlo", "Consolas", "Courier New", monospace;
|
font-family: "Monaco", "Menlo", "Consolas", "Courier New", monospace;
|
||||||
|
font-size: 12pt;
|
||||||
}
|
}
|
||||||
.content {
|
body {
|
||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
margin-right: auto;
|
margin-right: auto;
|
||||||
max-width: 1024px;
|
max-width: 80%;
|
||||||
}
|
|
||||||
#wrapper {
|
|
||||||
margin-bottom: 10px;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
#footer {
|
|
||||||
margin-top: 10px;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
#footer a {
|
|
||||||
margin: 0 10px;
|
|
||||||
}
|
}
|
||||||
.ip {
|
.ip {
|
||||||
border: 1px solid #cbcbcb;
|
border: 1px solid #cbcbcb;
|
||||||
background: #f2f2f2;
|
background: #f2f2f2;
|
||||||
font-size: 36px;
|
font-size: 36px;
|
||||||
}
|
}
|
||||||
|
#footer {
|
||||||
|
font-size: 12pt;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="content">
|
<div class="pure-g">
|
||||||
<div id="wrapper">
|
<div class="pure-u-1-1">
|
||||||
<h1>What is my IP address?</h1>
|
<h1>What is my IP address?</h1>
|
||||||
<h2>Your IP:</h2>
|
|
||||||
<p><code class="ip">{{ .IP }}</code></p>
|
<p><code class="ip">{{ .IP }}</code></p>
|
||||||
<a href="?cmd=curl" class="pure-button{{ if eq .Cmd.Name "curl" }} pure-button-active pure-button-primary{{end}}">curl</a>
|
<p>Multiple command line HTTP clients are supported,
|
||||||
<a href="?cmd=wget" class="pure-button{{ if eq .Cmd.Name "wget" }} pure-button-active pure-button-primary{{end}}">wget</a>
|
including <a href="https://curl.haxx.se/">curl</a>, <a href="https://www.gnu.org/software/wget/">GNU
|
||||||
<a href="?cmd=fetch" class="pure-button{{ if eq .Cmd.Name "fetch" }} pure-button-active pure-button-primary{{end}}">fetch</a>
|
Wget</a>
|
||||||
|
and <a href="https://www.freebsd.org/cgi/man.cgi?fetch(1)">fetch</a>.</p>
|
||||||
</div>
|
</div>
|
||||||
<table class="pure-table pure-table-bordered pure-table-striped">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th style="width: 350px">Command</th>
|
|
||||||
<th>Response</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<tr>
|
|
||||||
<td><code><span class="command">{{ .Cmd.String }}</span> ifconfig.co</code></td>
|
|
||||||
<td class="response">{{ .IP }}</td>
|
|
||||||
</tr>
|
|
||||||
{{ if $self := . }}
|
|
||||||
{{ range $key, $value := .Header }}
|
|
||||||
<tr>
|
|
||||||
<td><code><span class="command">{{ $self.Cmd.String }}</span> ifconfig.co/{{ ToLower $key }}</code></td>
|
|
||||||
<td class="response">{{ index $self.Header $key 0 }}</td>
|
|
||||||
</tr>
|
|
||||||
{{end}}
|
|
||||||
{{end}}
|
|
||||||
<td><code><span class="command">{{ .Cmd.String }}</span> ifconfig.co/all.json</code></td>
|
|
||||||
<td><pre class="response">{{ .JSON }}</pre></td>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
</div>
|
||||||
<div id="footer">
|
<div class="pure-g">
|
||||||
<a href="http://v4.ifconfig.co">IPv4 page</a>
|
<div class="pure-u-1-2">
|
||||||
<a href="http://v6.ifconfig.co">IPv6 page</a>
|
<p>CLI examples:</p>
|
||||||
|
<pre>
|
||||||
|
$ curl ifconfig.co
|
||||||
|
{{ .IP }}
|
||||||
|
|
||||||
|
$ wget -qO- ifconfig.co
|
||||||
|
{{ .IP }}
|
||||||
|
|
||||||
|
$ fetch -qo- http://ifconfig.co
|
||||||
|
{{ .IP }}
|
||||||
|
</pre>
|
||||||
|
<p>Country lookup:</p>
|
||||||
|
<pre>
|
||||||
|
$ http ifconfig.co/country
|
||||||
|
{{ .Country }}
|
||||||
|
</pre>
|
||||||
</div>
|
</div>
|
||||||
<a href="https://github.com/martinp/ifconfigd"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub"></a>
|
<div class="pure-u-1-2">
|
||||||
|
<p>JSON output:</p>
|
||||||
|
<pre>
|
||||||
|
$ http --json ifconfig.co
|
||||||
|
HTTP/1.1 200 OK
|
||||||
|
Content-Length: 61
|
||||||
|
Content-Type: application/json
|
||||||
|
Date: Fri, 15 Apr 2016 17:26:53 GMT
|
||||||
|
|
||||||
|
{
|
||||||
|
"country": "{{ .Country }}",
|
||||||
|
"ip": "{{ .IP }}"
|
||||||
|
}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="pure-g">
|
||||||
|
<div class="pure-u-1-1" id="footer">
|
||||||
|
<p>To force IPv4 lookup you can use the <a href="http://v4.ifconfig.co">v4 subdomain</a> (<a href="http://v6.ifconfig.co">or v6 for IPv6</a>).</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<a href="https://github.com/martinp/ipd"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub"></a>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
26
main.go
26
main.go
@ -14,30 +14,30 @@ func main() {
|
|||||||
DBPath string `short:"f" long:"file" description:"Path to GeoIP database" value-name:"FILE" default:""`
|
DBPath string `short:"f" long:"file" description:"Path to GeoIP database" value-name:"FILE" default:""`
|
||||||
Listen string `short:"l" long:"listen" description:"Listening address" value-name:"ADDR" default:":8080"`
|
Listen string `short:"l" long:"listen" description:"Listening address" value-name:"ADDR" default:":8080"`
|
||||||
CORS bool `short:"x" long:"cors" description:"Allow requests from other domains"`
|
CORS bool `short:"x" long:"cors" description:"Allow requests from other domains"`
|
||||||
ReverseLookup bool `short:"r" long:"reverselookup" description:"Perform reverse hostname lookups"`
|
ReverseLookup bool `short:"r" long:"reverse-lookup" description:"Perform reverse hostname lookups"`
|
||||||
Template string `short:"t" long:"template" description:"Path to template" default:"index.html"`
|
Template string `short:"t" long:"template" description:"Path to template" default:"index.html"`
|
||||||
}
|
}
|
||||||
_, err := flags.ParseArgs(&opts, os.Args)
|
_, err := flags.ParseArgs(&opts, os.Args)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
var a *api.API
|
api := api.New()
|
||||||
if opts.DBPath == "" {
|
api.CORS = opts.CORS
|
||||||
a = api.New()
|
if opts.ReverseLookup {
|
||||||
} else {
|
log.Println("Enabling reverse lookup")
|
||||||
a, err = api.NewWithGeoIP(opts.DBPath)
|
api.EnableReverseLookup()
|
||||||
if err != nil {
|
}
|
||||||
|
if opts.DBPath != "" {
|
||||||
|
log.Printf("Enabling country lookup (using database: %s)\n", opts.DBPath)
|
||||||
|
if err := api.EnableCountryLookup(opts.DBPath); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
api.Template = opts.Template
|
||||||
a.CORS = opts.CORS
|
|
||||||
a.ReverseLookup = opts.ReverseLookup
|
|
||||||
a.Template = opts.Template
|
|
||||||
|
|
||||||
log.Printf("Listening on %s", opts.Listen)
|
log.Printf("Listening on %s", opts.Listen)
|
||||||
if err := a.ListenAndServe(opts.Listen); err != nil {
|
if err := api.ListenAndServe(opts.Listen); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user