echoip/api/api.go

285 lines
6.8 KiB
Go
Raw Normal View History

2015-09-17 20:57:27 +02:00
package api
import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"path/filepath"
"regexp"
"strings"
"html/template"
"github.com/gorilla/mux"
geoip2 "github.com/oschwald/geoip2-golang"
)
const (
2015-09-18 17:13:14 +02:00
IP_HEADER = "x-ifconfig-ip"
COUNTRY_HEADER = "x-ifconfig-country"
2015-09-21 18:03:52 +02:00
HOSTNAME_HEADER = "x-ifconfig-hostname"
2015-09-18 17:13:14 +02:00
TEXT_PLAIN = "text/plain; charset=utf-8"
APPLICATION_JSON = "application/json"
2015-09-17 20:57:27 +02:00
)
2016-02-23 00:02:03 +01:00
var cliUserAgentExp = regexp.MustCompile(`^(?i)((curl|wget|fetch\slibfetch|Go-http-client)\/.*|Go\s1\.1\spackage\shttp)$`)
2015-09-17 20:57:27 +02:00
type API struct {
2015-09-21 18:03:52 +02:00
CORS bool
ReverseLookup bool
Template string
2015-09-29 20:39:21 +02:00
lookupAddr func(string) ([]string, error)
lookupCountry func(net.IP) (string, error)
ipFromRequest func(*http.Request) (net.IP, error)
2015-09-17 20:57:27 +02:00
}
2015-09-29 20:39:21 +02:00
func New() *API {
return &API{
lookupAddr: net.LookupAddr,
lookupCountry: func(ip net.IP) (string, error) { return "", nil },
ipFromRequest: ipFromRequest,
}
}
2015-09-17 20:57:27 +02:00
func NewWithGeoIP(filepath string) (*API, error) {
db, err := geoip2.Open(filepath)
if err != nil {
return nil, err
}
2015-09-29 20:39:21 +02:00
api := New()
api.lookupCountry = func(ip net.IP) (string, error) {
return lookupCountry(db, ip)
}
return api, nil
2015-09-17 20:57:27 +02:00
}
type Cmd struct {
Name string
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) {
var host string
realIP := r.Header.Get("X-Real-IP")
var err error
if realIP != "" {
host = realIP
} else {
host, _, err = net.SplitHostPort(r.RemoteAddr)
if err != nil {
return nil, err
}
}
ip := net.ParseIP(host)
if ip == nil {
return nil, fmt.Errorf("could not parse IP: %s", host)
}
return ip, nil
}
2015-09-18 17:13:14 +02:00
func headerPairFromRequest(r *http.Request) (string, string, error) {
2015-09-17 20:57:27 +02:00
vars := mux.Vars(r)
2015-09-18 17:13:14 +02:00
header, ok := vars["header"]
2015-09-17 20:57:27 +02:00
if !ok {
2015-09-18 17:13:14 +02:00
header = IP_HEADER
2015-09-17 20:57:27 +02:00
}
2015-09-18 17:13:14 +02:00
value := r.Header.Get(header)
if value == "" {
return "", "", fmt.Errorf("no value found for: %s", header)
}
return header, value, nil
2015-09-17 20:57:27 +02:00
}
2015-09-29 20:39:21 +02:00
func lookupCountry(db *geoip2.Reader, ip net.IP) (string, error) {
if db == nil {
2015-09-17 20:57:27 +02:00
return "", nil
}
2015-09-29 20:39:21 +02:00
record, err := db.Country(ip)
2015-09-17 20:57:27 +02:00
if err != nil {
return "", err
}
if country, exists := record.Country.Names["en"]; exists {
return country, nil
}
if country, exists := record.RegisteredCountry.Names["en"]; exists {
return country, nil
}
return "", fmt.Errorf("could not determine country for IP: %s", ip)
}
2015-09-18 17:13:14 +02:00
func (a *API) DefaultHandler(w http.ResponseWriter, r *http.Request) *appError {
2015-09-17 20:57:27 +02:00
cmd := cmdFromQueryParams(r.URL.Query())
funcMap := template.FuncMap{"ToLower": strings.ToLower}
t, err := template.New(filepath.Base(a.Template)).Funcs(funcMap).ParseFiles(a.Template)
if err != nil {
2015-09-18 17:13:14 +02:00
return internalServerError(err)
2015-09-17 20:57:27 +02:00
}
b, err := json.MarshalIndent(r.Header, "", " ")
if err != nil {
2015-09-18 17:13:14 +02:00
return internalServerError(err)
2015-09-17 20:57:27 +02:00
}
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 {
2015-09-18 17:13:14 +02:00
return internalServerError(err)
2015-09-17 20:57:27 +02:00
}
2015-09-18 17:13:14 +02:00
return nil
2015-09-17 20:57:27 +02:00
}
2015-09-18 17:13:14 +02:00
func (a *API) JSONHandler(w http.ResponseWriter, r *http.Request) *appError {
k, v, err := headerPairFromRequest(r)
contentType := APPLICATION_JSON
if err != nil {
return notFound(err).WithContentType(contentType)
2015-09-17 22:39:12 +02:00
}
2015-09-18 17:13:14 +02:00
value := map[string]string{k: v}
2015-09-17 20:57:27 +02:00
b, err := json.MarshalIndent(value, "", " ")
if err != nil {
2015-09-18 17:13:14 +02:00
return internalServerError(err).WithContentType(contentType)
2015-09-17 20:57:27 +02:00
}
2015-09-18 17:13:14 +02:00
w.Header().Set("Content-Type", contentType)
2015-09-17 20:57:27 +02:00
w.Write(b)
2015-09-18 17:13:14 +02:00
return nil
2015-09-17 20:57:27 +02:00
}
2015-09-18 17:42:43 +02:00
func (a *API) JSONAllHandler(w http.ResponseWriter, r *http.Request) *appError {
contentType := APPLICATION_JSON
b, err := json.MarshalIndent(r.Header, "", " ")
if err != nil {
return internalServerError(err).WithContentType(contentType)
}
w.Header().Set("Content-Type", contentType)
w.Write(b)
return nil
}
2015-09-18 17:13:14 +02:00
func (a *API) CLIHandler(w http.ResponseWriter, r *http.Request) *appError {
_, v, err := headerPairFromRequest(r)
if err != nil {
return notFound(err)
2015-09-17 22:39:12 +02:00
}
2015-09-18 17:13:14 +02:00
if !strings.HasSuffix(v, "\n") {
v += "\n"
2015-09-17 20:57:27 +02:00
}
2015-09-18 17:13:14 +02:00
io.WriteString(w, v)
return nil
2015-09-17 20:57:27 +02:00
}
func cliMatcher(r *http.Request, rm *mux.RouteMatch) bool {
return cliUserAgentExp.MatchString(r.UserAgent())
}
func (a *API) requestFilter(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2015-09-29 20:39:21 +02:00
ip, err := a.ipFromRequest(r)
2015-09-17 20:57:27 +02:00
if err != nil {
2015-09-29 20:39:21 +02:00
log.Print(err)
r.Header.Set(IP_HEADER, "")
2015-09-17 20:57:27 +02:00
} else {
r.Header.Set(IP_HEADER, ip.String())
2015-09-17 22:16:33 +02:00
country, err := a.lookupCountry(ip)
2015-09-17 20:57:27 +02:00
if err != nil {
2015-09-29 20:39:21 +02:00
log.Print(err)
2015-09-17 20:57:27 +02:00
}
2015-09-29 20:39:21 +02:00
r.Header.Set(COUNTRY_HEADER, country)
2015-09-17 20:57:27 +02:00
}
2015-09-21 18:03:52 +02:00
if a.ReverseLookup {
2015-09-29 20:39:21 +02:00
hostname, err := a.lookupAddr(ip.String())
2015-09-21 18:03:52 +02:00
if err != nil {
2015-09-29 20:39:21 +02:00
log.Print(err)
2015-09-21 18:03:52 +02:00
}
2015-09-29 20:39:21 +02:00
r.Header.Set(HOSTNAME_HEADER, strings.Join(hostname, ", "))
2015-09-21 18:03:52 +02:00
}
2015-09-17 20:57:27 +02:00
if a.CORS {
w.Header().Set("Access-Control-Allow-Methods", "GET")
w.Header().Set("Access-Control-Allow-Origin", "*")
}
next.ServeHTTP(w, r)
})
}
2015-09-18 17:13:14 +02:00
type appHandler func(http.ResponseWriter, *http.Request) *appError
func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if e := fn(w, r); e != nil { // e is *appError
if e.Error != nil {
log.Print(e.Error)
}
contentType := e.ContentType
if contentType == "" {
contentType = TEXT_PLAIN
}
response := e.Response
if response == "" {
response = e.Error.Error()
}
if e.IsJSON() {
var data = struct {
Error string `json:"error"`
}{response}
b, err := json.MarshalIndent(data, "", " ")
if err != nil {
panic(err)
}
response = string(b)
}
w.Header().Set("Content-Type", contentType)
w.WriteHeader(e.Code)
io.WriteString(w, response)
}
}
2015-09-17 20:57:27 +02:00
func (a *API) Handlers() http.Handler {
r := mux.NewRouter()
// JSON
2015-09-18 17:13:14 +02:00
r.Handle("/", appHandler(a.JSONHandler)).Methods("GET").Headers("Accept", APPLICATION_JSON)
2015-09-18 17:42:43 +02:00
r.Handle("/all", appHandler(a.JSONAllHandler)).Methods("GET").Headers("Accept", APPLICATION_JSON)
r.Handle("/all.json", appHandler(a.JSONAllHandler)).Methods("GET")
2015-09-18 17:13:14 +02:00
r.Handle("/{header}", appHandler(a.JSONHandler)).Methods("GET").Headers("Accept", APPLICATION_JSON)
r.Handle("/{header}.json", appHandler(a.JSONHandler)).Methods("GET")
2015-09-17 20:57:27 +02:00
// CLI
2015-09-18 17:13:14 +02:00
r.Handle("/", appHandler(a.CLIHandler)).Methods("GET").MatcherFunc(cliMatcher)
r.Handle("/{header}", appHandler(a.CLIHandler)).Methods("GET").MatcherFunc(cliMatcher)
2015-09-17 20:57:27 +02:00
// Default
2015-09-18 17:13:14 +02:00
r.Handle("/", appHandler(a.DefaultHandler)).Methods("GET")
2015-09-17 20:57:27 +02:00
// Pass all requests through the request filter
return a.requestFilter(r)
}
func (a *API) ListenAndServe(addr string) error {
http.Handle("/", a.Handlers())
return http.ListenAndServe(addr, nil)
}