echoip/api/api.go

245 lines
5.8 KiB
Go
Raw Normal View History

2015-09-17 20:57:27 +02:00
package api
import (
"encoding/json"
"fmt"
2016-04-15 20:14:16 +02:00
"html/template"
2015-09-17 20:57:27 +02:00
"io"
"log"
"net"
"net/http"
"path/filepath"
"regexp"
2016-04-15 20:52:15 +02:00
"strconv"
2015-09-17 20:57:27 +02:00
"strings"
"github.com/gorilla/mux"
)
2016-04-15 20:14:16 +02:00
const APPLICATION_JSON = "application/json"
2015-09-17 20:57:27 +02:00
2016-04-16 20:18:20 +02:00
var USER_AGENT_RE = regexp.MustCompile(
`^(?:curl|Wget|fetch\slibfetch|Go-http-client|HTTPie)\/.*|Go\s1\.1\spackage\shttp$`,
)
2015-09-17 20:57:27 +02:00
type API struct {
2016-04-17 16:03:00 +02:00
Template string
IPHeader string
oracle Oracle
2015-09-17 20:57:27 +02:00
}
2016-04-15 20:14:16 +02:00
type Response struct {
IP net.IP `json:"ip"`
Country string `json:"country,omitempty"`
2016-04-17 11:28:47 +02:00
City string `json:"city,omitempty"`
2016-04-15 20:14:16 +02:00
Hostname string `json:"hostname,omitempty"`
}
2016-04-15 20:52:15 +02:00
type TestPortResponse struct {
IP net.IP `json:"ip"`
Port uint64 `json:"port"`
Reachable bool `json:"reachable"`
}
2016-04-17 11:09:56 +02:00
func New(oracle Oracle) *API {
2016-04-17 16:03:00 +02:00
return &API{oracle: oracle}
2015-09-29 20:39:21 +02:00
}
2015-09-17 20:57:27 +02:00
func ipFromRequest(header string, r *http.Request) (net.IP, error) {
remoteIP := r.Header.Get(header)
2016-04-16 10:45:43 +02:00
if remoteIP == "" {
host, _, err := net.SplitHostPort(r.RemoteAddr)
2015-09-17 20:57:27 +02:00
if err != nil {
return nil, err
}
2016-04-16 10:45:43 +02:00
remoteIP = host
2015-09-17 20:57:27 +02:00
}
2016-04-16 10:45:43 +02:00
ip := net.ParseIP(remoteIP)
2015-09-17 20:57:27 +02:00
if ip == nil {
2016-04-16 10:45:43 +02:00
return nil, fmt.Errorf("could not parse IP: %s", remoteIP)
2015-09-17 20:57:27 +02:00
}
return ip, nil
}
2016-04-15 20:14:16 +02:00
func (a *API) newResponse(r *http.Request) (Response, error) {
2016-04-17 16:03:00 +02:00
ip, err := ipFromRequest(a.IPHeader, r)
2015-09-17 20:57:27 +02:00
if err != nil {
2016-04-15 20:14:16 +02:00
return Response{}, err
2015-09-17 20:57:27 +02:00
}
2016-04-17 11:09:56 +02:00
country, err := a.oracle.LookupCountry(ip)
2015-09-17 20:57:27 +02:00
if err != nil {
2016-04-15 20:14:16 +02:00
log.Print(err)
2015-09-17 20:57:27 +02:00
}
2016-04-17 11:28:47 +02:00
city, err := a.oracle.LookupCity(ip)
if err != nil {
log.Print(err)
}
2016-04-17 11:09:56 +02:00
hostnames, err := a.oracle.LookupAddr(ip.String())
2016-04-15 20:14:16 +02:00
if err != nil {
log.Print(err)
}
return Response{
IP: ip,
Country: country,
2016-04-17 11:28:47 +02:00
City: city,
2016-04-15 20:14:16 +02:00
Hostname: strings.Join(hostnames, " "),
}, nil
}
2015-09-17 20:57:27 +02:00
2016-04-15 20:14:16 +02:00
func (a *API) CLIHandler(w http.ResponseWriter, r *http.Request) *appError {
2016-04-17 16:03:00 +02:00
ip, err := ipFromRequest(a.IPHeader, r)
2016-04-15 20:14:16 +02:00
if err != nil {
2015-09-18 17:13:14 +02:00
return internalServerError(err)
2015-09-17 20:57:27 +02:00
}
2016-04-16 09:18:21 +02:00
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)
2016-04-15 20:14:16 +02:00
}
2016-04-16 09:18:21 +02:00
io.WriteString(w, response.Country+"\n")
2015-09-18 17:13:14 +02:00
return nil
2015-09-17 20:57:27 +02:00
}
2016-04-17 11:28:47 +02:00
func (a *API) CLICityHandler(w http.ResponseWriter, r *http.Request) *appError {
response, err := a.newResponse(r)
if err != nil {
return internalServerError(err)
}
io.WriteString(w, response.City+"\n")
return nil
}
2015-09-18 17:13:14 +02:00
func (a *API) JSONHandler(w http.ResponseWriter, r *http.Request) *appError {
2016-04-15 20:14:16 +02:00
response, err := a.newResponse(r)
2015-09-18 17:13:14 +02:00
if err != nil {
2016-04-15 20:14:16 +02:00
return internalServerError(err).AsJSON()
2015-09-17 22:39:12 +02:00
}
2016-04-15 20:14:16 +02:00
b, err := json.Marshal(response)
2015-09-17 20:57:27 +02:00
if err != nil {
2016-04-15 20:14:16 +02:00
return internalServerError(err).AsJSON()
2015-09-17 20:57:27 +02:00
}
2016-04-15 20:14:16 +02:00
w.Header().Set("Content-Type", APPLICATION_JSON)
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
}
2016-04-16 09:48:39 +02:00
func (a *API) PortHandler(w http.ResponseWriter, r *http.Request) *appError {
2016-04-15 20:52:15 +02:00
vars := mux.Vars(r)
port, err := strconv.ParseUint(vars["port"], 10, 16)
if err != nil {
return badRequest(err).WithMessage("Invalid port: " + vars["port"]).AsJSON()
}
if port < 1 || port > 65355 {
return badRequest(nil).WithMessage("Invalid port: " + vars["port"]).AsJSON()
}
2016-04-17 16:03:00 +02:00
ip, err := ipFromRequest(a.IPHeader, r)
2016-04-15 20:52:15 +02:00
if err != nil {
return internalServerError(err).AsJSON()
}
2016-04-17 11:09:56 +02:00
err = a.oracle.LookupPort(ip, port)
2016-04-15 20:52:15 +02:00
response := TestPortResponse{
IP: ip,
Port: port,
Reachable: err == nil,
}
b, err := json.Marshal(response)
if err != nil {
return internalServerError(err).AsJSON()
}
w.Header().Set("Content-Type", APPLICATION_JSON)
w.Write(b)
return nil
}
2016-04-15 20:14:16 +02:00
func (a *API) DefaultHandler(w http.ResponseWriter, r *http.Request) *appError {
response, err := a.newResponse(r)
2015-09-18 17:42:43 +02:00
if err != nil {
2016-04-15 20:14:16 +02:00
return internalServerError(err)
2015-09-18 17:42:43 +02:00
}
2016-04-15 20:14:16 +02:00
t, err := template.New(filepath.Base(a.Template)).ParseFiles(a.Template)
2015-09-18 17:13:14 +02:00
if err != nil {
2016-04-15 20:14:16 +02:00
return internalServerError(err)
2015-09-17 22:39:12 +02:00
}
var data = struct {
Response
2016-04-17 11:09:56 +02:00
Oracle
}{response, a.oracle}
if err := t.Execute(w, &data); err != nil {
2016-04-15 20:14:16 +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
}
2016-04-15 20:14:16 +02:00
func (a *API) NotFoundHandler(w http.ResponseWriter, r *http.Request) *appError {
err := notFound(nil).WithMessage("404 page not found")
if r.Header.Get("accept") == APPLICATION_JSON {
err = err.AsJSON()
}
return err
}
2015-09-17 20:57:27 +02:00
func cliMatcher(r *http.Request, rm *mux.RouteMatch) bool {
2016-04-16 20:18:20 +02:00
return USER_AGENT_RE.MatchString(r.UserAgent())
2015-09-17 20:57:27 +02:00
}
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)
}
2016-04-15 20:14:16 +02:00
// When Content-Type for error is JSON, we need to marshal the response into JSON
2015-09-18 17:13:14 +02:00
if e.IsJSON() {
var data = struct {
Error string `json:"error"`
2016-04-15 20:14:16 +02:00
}{e.Message}
b, err := json.Marshal(data)
2015-09-18 17:13:14 +02:00
if err != nil {
panic(err)
}
2016-04-15 20:14:16 +02:00
e.Message = string(b)
}
// Set Content-Type of response if set in error
if e.ContentType != "" {
w.Header().Set("Content-Type", e.ContentType)
2015-09-18 17:13:14 +02:00
}
w.WriteHeader(e.Code)
2016-04-15 20:14:16 +02:00
io.WriteString(w, e.Message)
2015-09-18 17:13:14 +02:00
}
}
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)
2016-04-17 09:31:33 +02:00
r.Handle("/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)
2016-04-15 20:14:16 +02:00
r.Handle("/ip", appHandler(a.CLIHandler)).Methods("GET").MatcherFunc(cliMatcher)
2016-04-16 09:18:21 +02:00
r.Handle("/country", appHandler(a.CLICountryHandler)).Methods("GET").MatcherFunc(cliMatcher)
2016-04-17 11:28:47 +02:00
r.Handle("/city", appHandler(a.CLICityHandler)).Methods("GET").MatcherFunc(cliMatcher)
2015-09-17 20:57:27 +02:00
2016-04-15 20:14:16 +02:00
// Browser
2015-09-18 17:13:14 +02:00
r.Handle("/", appHandler(a.DefaultHandler)).Methods("GET")
2015-09-17 20:57:27 +02:00
2016-04-15 20:52:15 +02:00
// Port testing
2016-04-16 09:48:39 +02:00
r.Handle("/port/{port:[0-9]+}", appHandler(a.PortHandler)).Methods("GET")
2016-04-15 20:52:15 +02:00
2016-04-15 20:14:16 +02:00
// Not found handler which returns JSON when appropriate
r.NotFoundHandler = appHandler(a.NotFoundHandler)
2016-04-17 14:23:20 +02:00
return r
2015-09-17 20:57:27 +02:00
}
func (a *API) ListenAndServe(addr string) error {
http.Handle("/", a.Handlers())
return http.ListenAndServe(addr, nil)
}