forked from s32x/ipdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
70 lines (60 loc) · 1.64 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"log"
"net/http"
"os"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/s32x/ipdata/ipdata"
)
var (
port = getenv("PORT", "8080")
cityPath = getenv("CITY_PATH", "./db/city.tar.gz")
asnPath = getenv("ASN_PATH", "./db/asn.tar.gz")
)
func main() {
// Create the ipdata client
ic, err := ipdata.NewClient(cityPath, asnPath)
if err != nil {
log.Fatal(err)
}
defer ic.Close()
// Create a new echo Echo and bind all middleware
e := echo.New()
e.HideBanner = true
// Bind middleware
e.Pre(middleware.RemoveTrailingSlashWithConfig(
middleware.TrailingSlashConfig{
RedirectCode: http.StatusPermanentRedirect,
}))
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Pre(middleware.Secure())
e.Use(middleware.Gzip())
e.Use(middleware.CORS())
// Serve the static web content on the base echo instance
e.Static("*", "./static")
// Bind all API endpoint handlers
e.GET("/lookup", func(c echo.Context) error {
return c.JSON(http.StatusOK, ic.Lookup(c.RealIP()))
})
e.GET("/lookup/:ip", func(c echo.Context) error {
return c.JSON(http.StatusOK, ic.Lookup(c.Param("ip")))
})
e.GET("/healthcheck", func(c echo.Context) error {
return c.NoContent(http.StatusOK)
})
// Listen on the passed port
e.Logger.Fatal(e.Start(":" + port))
}
// getenv attempts to retrieve and return a variable from the environment. If it
// fails it will either crash or failover to a passed default value
func getenv(key string, def ...string) string {
if v, ok := os.LookupEnv(key); ok {
return v
}
if len(def) == 0 {
log.Fatalf("%s not defined in environment", key)
}
return def[0]
}