-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
95 lines (77 loc) · 2.48 KB
/
server.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
// http://jsonapi.org
// TODO: Schema valiadation ?
// TODO: Pagination - http://jsonapi.org/format/#fetching-pagination
// TODO: Filtering - http://jsonapi.org/recommendations/#filtering
// TODO: Implement fields type, links and etc.- http://jsonapi.org/format/#document-structure
// TODO: Disable LoggingHandler if nto DEBUG
import (
"github.com/ConsumerAffairs/mailer-log/handlers"
"github.com/ConsumerAffairs/mailer-log/middleware"
"github.com/ConsumerAffairs/mailer-log/models"
"github.com/ConsumerAffairs/mailer-log/router"
"github.com/gorilla/context"
"github.com/justinas/alice"
"gopkg.in/mgo.v2"
"net/http"
"os"
"stathat.com/c/jconfig"
)
var (
session *mgo.Session
collection *mgo.Collection
)
func main() {
var config *jconfig.Config
if _, err := os.Stat("config.local.json"); os.IsNotExist(err) {
config = jconfig.LoadConfig("config.json")
} else {
config = jconfig.LoadConfig("config.local.json")
}
mc := handlers.NewMailController(getSession(config.GetString("mongodb")))
middleware := middleware.Middleware{}
commonHandlers := alice.New(context.ClearHandler)
if config.GetBool("debug") {
commonHandlers = commonHandlers.Append(middleware.LoggingHandler)
}
commonHandlers = commonHandlers.Append(
middleware.RecoverHandler,
middleware.AcceptHandler)
router := router.NewRouter()
router.Get("/mails", commonHandlers.ThenFunc(mc.ListMail))
router.Post("/mails", commonHandlers.Append(middleware.ContentTypeHandler,
middleware.BodyHandler(models.Mail{})).ThenFunc(mc.CreateMail))
router.Put("/mails/:id", commonHandlers.Append(middleware.ContentTypeHandler,
middleware.BodyHandler(models.Mail{})).ThenFunc(mc.UpdateMail))
router.Get("/mails/:id", commonHandlers.ThenFunc(mc.RetrieveMail))
router.Delete("/mails/:id", commonHandlers.ThenFunc(mc.DeleteMail))
router.Router.NotFound = http.FileServer(http.Dir(config.GetString("servePath"))).ServeHTTP
http.ListenAndServe(config.GetString("host"), router)
}
// Get mongodb session
func getSession(url string) *mgo.Session {
s, err := mgo.Dial("")
if err != nil {
panic(err)
}
s.SetSafe(&mgo.Safe{})
// Ensure indexes
index := mgo.Index{
Key: []string{"sent_at"},
Background: true,
}
err = s.DB("mailer").C("mails").EnsureIndex(index)
if err != nil {
panic(err)
}
// Ensure full text index
textindex := mgo.Index{
Key: []string{"$text:$**"},
Background: true,
}
err = s.DB("mailer").C("mails").EnsureIndex(textindex)
if err != nil {
panic(err)
}
return s
}