-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
67 lines (51 loc) · 1.49 KB
/
app.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
package main
import (
"database/sql"
"flag"
"fmt"
"github.com/fernandochristyanto/devcamp-backend/internal"
"github.com/fernandochristyanto/devcamp-backend/internal/handler"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
_ "github.com/lib/pq"
)
const (
booksTTL = 10
)
func initFlags(args *internal.Args) {
port := flag.Int("port", 8000, "port number for your apps")
args.Port = *port
}
func initHandler(handler *handler.Handler) error {
// Initialize SQL DB
db, err := sql.Open("postgres", "postgres://devcamp:[email protected]:5432/?sslmode=disable")
if err != nil {
return err
}
handler.DB = db
return nil
}
func initRouter(router *httprouter.Router, handler *handler.Handler) {
router.GET("/", handler.Index)
// Single user API
router.POST("/users/shopregistration", handler.SellerRegistration)
router.GET("/users/:id/products", handler.GetProductsByUser)
router.GET("/products/garagesale", handler.GetGarageSales)
router.GET("/products/detail/:id", handler.GetProductDetail)
router.POST("/products/garagesale", handler.NewGarageSaleProduct)
// `httprouter` library uses `ServeHTTP` method for it's 404 pages
router.NotFound = handler
}
func main() {
args := new(internal.Args)
initFlags(args)
handler := new(handler.Handler)
if err := initHandler(handler); err != nil {
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))
}