-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathapp.go
More file actions
75 lines (57 loc) · 1.72 KB
/
Copy pathapp.go
File metadata and controls
75 lines (57 loc) · 1.72 KB
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
package main
import (
"database/sql"
"flag"
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
_ "github.com/lib/pq"
"github.com/martinock/devcamp-backend/internal"
)
func initFlags(args *internal.Args) {
port := flag.Int("port", 3000, "port number for your apps")
args.Port = *port
}
func initHandler(handler *internal.Handler) error {
// Initialize SQL DB
// NOTE: change localhost:5432 to postgres:5432 if you use docker
db, err := sql.Open("postgres", "postgres://postgres:postgres@localhost:5432/?sslmode=disable")
if err != nil {
return err
}
handler.DB = db
return nil
}
func initRouter(router *httprouter.Router, handler *internal.Handler) {
router.GET("/", handler.Index)
// Single user API
router.GET("/user/:userID", handler.GetUserByID)
router.POST("/user", handler.InsertUser)
router.PUT("/user/:userID", handler.EditUserByID)
router.DELETE("/user/:userID", handler.DeleteUserByID)
// Single book API
router.GET("/book/:bookID", handler.GetBookByID)
router.POST("/book", handler.InsertBook)
router.PUT("/book/:bookID", handler.EditBook)
router.DELETE("/book/:bookID", handler.DeleteBookByID)
// Batch book API
router.POST("/books", handler.InsertMultipleBooks)
// Lending API
router.POST("/lend", handler.LendBook)
// `httprouter` library uses `ServeHTTP` method for it's 404 pages
router.NotFound = handler
}
func main() {
args := new(internal.Args)
initFlags(args)
handler := new(internal.Handler)
if err := initHandler(handler); err != nil {
log.Println("Failed to init handler", err)
panic(err)
}
router := httprouter.New()
initRouter(router, handler)
fmt.Printf("Apps served on :%d\n", args.Port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", args.Port), router))
}