-
Notifications
You must be signed in to change notification settings - Fork 4
/
api.go
71 lines (55 loc) · 1.6 KB
/
api.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 (
"context"
"log"
"net/http"
"os"
"reflect"
"github.com/gorilla/mux"
"github.com/sikozonpc/notebase/book"
"github.com/sikozonpc/notebase/config"
"github.com/sikozonpc/notebase/highlight"
"github.com/sikozonpc/notebase/medium"
"github.com/sikozonpc/notebase/storage"
"github.com/sikozonpc/notebase/user"
"go.mongodb.org/mongo-driver/mongo"
)
type APIServer struct {
addr string
db *mongo.Client
}
func NewAPIServer(addr string, db *mongo.Client) *APIServer {
return &APIServer{
addr: addr,
db: db,
}
}
func (s *APIServer) Run() error {
router := mux.NewRouter()
subrouter := router.PathPrefix("/api/v1").Subrouter()
ctx := context.Background()
gcpStorage, err := storage.NewGCPStorage(ctx)
if err != nil {
log.Fatal(err)
}
mailer := medium.NewMailer(config.Envs.SendGridAPIKey, config.Envs.SendGridFromEmail)
bookStore := book.NewStore(s.db)
userStore := user.NewStore(s.db)
userHandler := user.NewHandler(userStore)
userHandler.RegisterRoutes(subrouter)
highlightStore := highlight.NewStore(s.db)
highlightHandler := highlight.NewHandler(highlightStore, userStore, gcpStorage, bookStore, mailer)
highlightHandler.RegisterRoutes(subrouter)
// Serve static files
router.PathPrefix("/").Handler(http.FileServer(http.Dir("./static")))
log.Println("Listening on", s.addr)
log.Println("Process PID", os.Getpid())
env := config.Envs.Env
if env == "development" {
v := reflect.ValueOf(config.Envs)
for i := 0; i < v.NumField(); i++ {
log.Println(v.Type().Field(i).Name, "=", v.Field(i).Interface())
}
}
return http.ListenAndServe(s.addr, router)
}