-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
60 lines (49 loc) · 1.17 KB
/
router.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
package main
import (
"database/sql"
"sync"
"github.com/go-chi/chi"
"github.com/jon-whit/go-contacts/controllers"
"github.com/jon-whit/go-contacts/datastores"
"github.com/jon-whit/go-contacts/services"
)
type ChiRouter interface {
InitRouter() *chi.Mux
}
type router struct{}
func (router *router) InitRouter() *chi.Mux {
// Create the SQLite DB Handler
sqlConn, err := sql.Open("sqlite3", "/var/tmp/go-contacts.db")
if err != nil {
// handle error
}
sqliteHandler := &datastores.SQLiteHandler{
Conn: sqlConn,
}
// Inject all implementations of the interfaces.
controller := controllers.ContactsController{
&services.ContactsService{
DataAccessor: &datastores.ContactsDatastore{
sqliteHandler,
},
},
}
// Define and bind the API routes for the Contacts API
r := chi.NewRouter()
r.Get("/users/{userid}/contacts", controller.ListUserContacts)
r.Post("/users/{userid}/contacts", controller.CreateContact)
return r
}
var (
m *router
routerOnce sync.Once
)
// NewChiRouter defines a Singleton, ensuring only a single ChiRouter is created
func NewChiRouter() ChiRouter {
if m == nil {
routerOnce.Do(func() {
m = &router{}
})
}
return m
}