-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
68 lines (58 loc) · 1.51 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
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/pucsd2020-pp/rest-api/config"
"github.com/pucsd2020-pp/rest-api/driver"
"github.com/pucsd2020-pp/rest-api/handler"
httpHandler "github.com/pucsd2020-pp/rest-api/handler/http"
)
var (
handlers = []handler.IHTTPHandler{}
)
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.SetFlags(log.LstdFlags | log.Lshortfile)
dbConn, err := driver.NewMysqlConnection(config.Config().Database)
if nil != err {
log.Printf("Error while creating db connectiion:%s", err.Error())
os.Exit(1)
}
handlers = []handler.IHTTPHandler{
httpHandler.NewUserHandler(dbConn),
}
}
func createRouterGroup(router *chi.Mux) {
router.Group(func(r chi.Router) {
for _, hdlr := range handlers { // register all handlers
for _, hlr := range hdlr.GetHTTPHandler() {
path := fmt.Sprintf("/webapi/v1/%s", hlr.Path)
switch hlr.Method {
case http.MethodGet:
r.Get(path, hlr.Func)
case http.MethodPost:
r.Post(path, hlr.Func)
case http.MethodPut:
r.Put(path, hlr.Func)
case http.MethodDelete:
r.Delete(path, hlr.Func)
default:
log.Println("Invalid method")
}
}
}
})
}
func main() {
router := chi.NewRouter()
router.Use(middleware.Recoverer)
router.Use(middleware.Logger)
createRouterGroup(router)
log.Println(config.Config().Host, config.Config().Port)
http.ListenAndServe(fmt.Sprintf("%s:%d",
config.Config().Host, config.Config().Port), router)
}