-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
71 lines (58 loc) · 1.56 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
71
package main
import (
"os"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/labstack/gommon/log"
"gopkg.in/mgo.v2"
"github.com/checkaayush/sampark/handler"
)
func getEnvWithDefault(name, defaultValue string) string {
val := os.Getenv(name)
if val == "" {
val = defaultValue
}
return val
}
func main() {
e := echo.New()
e.Logger.SetLevel(log.WARN)
// Add middlewares
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Add Basic Auth
e.Use(middleware.BasicAuth(func(user, pass string, c echo.Context) (bool, error) {
authUser := getEnvWithDefault("AUTH_USERNAME", "admin")
authPass := getEnvWithDefault("AUTH_PASSWORD", "admin")
if user == authUser && pass == authPass {
return true, nil
}
return false, nil
}))
// Database connection
db, err := mgo.Dial(getEnvWithDefault("MONGO_URI", "mongodb:27017"))
if err != nil {
e.Logger.Fatal(err)
}
// Create database indices
dbname := getEnvWithDefault("MONGO_DBNAME", "sampark")
if err = db.Copy().DB(dbname).C("contacts").EnsureIndex(mgo.Index{
Key: []string{"email"},
Unique: true,
}); err != nil {
log.Fatal(err)
}
// Initialize handler
h := &handler.Handler{DB: db}
// Routes
v1 := e.Group("/v1")
v1.GET("/health", h.Health)
v1.POST("/contacts", h.CreateContact)
v1.GET("/contacts", h.FetchContacts)
v1.GET("/contacts/:id", h.GetContactByID)
v1.DELETE("/contacts/:id", h.DeleteContactByID)
v1.PATCH("/contacts/:id", h.UpdateContactByID)
// Start server
addr := ":" + getEnvWithDefault("PORT", "5000")
e.Logger.Fatal(e.Start(addr))
}