/
main.go
54 lines (45 loc) · 1.25 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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/jingweno/conf"
"github.com/pengux/web"
)
type Context struct{}
// Unmarshal request body in JSON to a struct
func (c *Context) UnmarshalBody(rw web.ResponseWriter, req *web.Request, object interface{}) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
log.Panicln(err)
}
err = json.Unmarshal(body, object)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
log.Panicln(err)
}
}
func main() {
defaults := map[string]interface{}{
"ENV": "production",
"API_PORT": 9090,
"API_PREFIX": "",
}
config, err := conf.NewLoader().Env().Argv().File("./config.json").Defaults(defaults).Load()
if err != nil {
log.Fatalln(err)
}
rootRouter := web.NewWithPrefix(Context{}, config.Get("API_PREFIX").(string))
rootRouter.Subrouter(TodoContext{}, "/todos").
Get("/", (*TodoContext).ReadMany).
Get("/:id", (*TodoContext).Read).
Post("/", (*TodoContext).Create).
Put("/:id", (*TodoContext).Replace).
Delete("/:id", (*TodoContext).Delete).
Middleware((*TodoContext).Init)
log.Printf("Listen to port %v", config.Get("API_PORT"))
http.ListenAndServe(fmt.Sprintf(":%v", config.Get("API_PORT")), rootRouter)
}