-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
81 lines (63 loc) · 1.76 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
72
73
74
75
76
77
78
79
80
81
package main
import (
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/go-kit/kit/log"
"nrei.name/blogapi/post"
"nrei.name/blogapi/utils"
"nrei.name/blogapi/db"
)
const (
defaultPort = "8080"
)
func main() {
var (
addr = utils.EnvGet("PORT", defaultPort)
httpAddr = flag.String("http.addr", ":"+addr, "HTTP listen address")
)
flag.Parse()
var logger log.Logger
logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
logger = log.With(logger, "ts", log.DefaultTimestampUTC)
httpLogger := log.With(logger, "component", "http")
db := db.CreateClient(db.CreateSession())
psr := post.NewRepository(db)
// For testing purposes.
mockTestPostsData(psr)
var ps post.Service
ps = post.NewService(psr)
mux := http.NewServeMux()
mux.Handle("/posts/v1/", post.MakeHandler(ps, httpLogger))
http.Handle("/", accessControl(mux))
errs := make(chan error, 2)
go func() {
httpLogger.Log("transport", "http", "address", *httpAddr)
errs <- http.ListenAndServe(*httpAddr, nil)
}()
go func() {
c := make(chan os.Signal)
signal.Notify(c, syscall.SIGINT)
errs <- fmt.Errorf("%s", <-c)
}()
logger.Log("terminated", <-errs)
}
func accessControl(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type")
if r.Method == "OPTIONS" {
return
}
h.ServeHTTP(w, r)
})
}
func mockTestPostsData(p post.Repository) {
if err := p.Save(post.New(post.ID("123"), "my super long text of 80 chars will be here and the whole phrase should be sliced", "my awesome content")); err != nil {
panic(err)
}
}