forked from rdegges/ipify-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
48 lines (40 loc) · 1.16 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// ipify-api
//
// This is the main package which starts up and runs our REST API service.
//
// ipify is a simple API service which returns a user's public IP address (it
// supports handling both IPv4 and IPv6 addresses).
package main
import (
"github.com/julienschmidt/httprouter"
"github.com/rs/cors"
"log"
"net/http"
"os"
"github.com/nrh/ipify-appengine/api"
)
func roothandler(w http.ResponseWriter, r *http.Request) {
// Setup all routes. We only service API requests, so this is basic.
router := httprouter.New()
router.GET("/", api.GetIP)
// Setup 404 / 405 handlers.
router.NotFound = http.HandlerFunc(api.NotFound)
router.MethodNotAllowed = http.HandlerFunc(api.MethodNotAllowed)
// Setup middlewares. For this we're basically adding:
// - Support for CORS to make JSONP work.
handler := cors.Default().Handler(router)
handler.ServeHTTP(w, r)
}
// appengine entrypoint
func main() {
http.HandleFunc("/", roothandler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("Defaulting to port %s", port)
}
log.Printf("Listening on port %s", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}