-
Notifications
You must be signed in to change notification settings - Fork 101
/
main.go
49 lines (40 loc) · 1.05 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
package main
import (
"fmt"
"net/http"
"os"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/s1s1ty/go-mysql-crud/driver"
ph "github.com/s1s1ty/go-mysql-crud/handler/http"
)
func main() {
dbName := os.Getenv("DB_NAME")
dbPass := os.Getenv("DB_PASS")
dbHost := os.Getenv("DB_HOST")
dbPort := os.Getenv("DB_PORT")
connection, err := driver.ConnectSQL(dbHost, dbPort, "root", dbPass, dbName)
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
r := chi.NewRouter()
r.Use(middleware.Recoverer)
r.Use(middleware.Logger)
pHandler := ph.NewPostHandler(connection)
r.Route("/", func(rt chi.Router) {
rt.Mount("/posts", postRouter(pHandler))
})
fmt.Println("Server listen at :8005")
http.ListenAndServe(":8005", r)
}
// A completely separate router for posts routes
func postRouter(pHandler *ph.Post) http.Handler {
r := chi.NewRouter()
r.Get("/", pHandler.Fetch)
r.Get("/{id:[0-9]+}", pHandler.GetByID)
r.Post("/", pHandler.Create)
r.Put("/{id:[0-9]+}", pHandler.Update)
r.Delete("/{id:[0-9]+}", pHandler.Delete)
return r
}