-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
87 lines (72 loc) · 1.77 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"database/sql"
"encoding/json"
"github.com/gorilla/mux"
"github.com/testingallthethings/033-go-rest/book"
"github.com/testingallthethings/033-go-rest/rest"
"log"
"net/http"
"os"
"time"
"github.com/golang-migrate/migrate"
"github.com/golang-migrate/migrate/database/postgres"
_ "github.com/golang-migrate/migrate/source/file"
_ "github.com/lib/pq"
)
type health struct {
Status string `json:"status"`
Messages []string `json:"messages"`
}
type jsonError struct {
Code string `json:"code"`
Msg string `json:"msg"`
}
type Book struct {
ISBN string `json:"isbn"`
Title string `json:"title"`
Image string `json:"image"`
Genre string `json:"genre"`
YearPublished int `json:"year_published"`
}
func main() {
db, err := sql.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatalf("Error making DB connected: %s", err.Error())
}
driver, err := postgres.WithInstance(db, &postgres.Config{})
if err != nil {
log.Fatalf("Error making DB driver: %s", err.Error())
}
migrator, err := migrate.NewWithDatabaseInstance(
"file://migrations",
"postgres",
driver,
)
if err != nil {
log.Fatalf("Error making migration engine: %s", err.Error())
}
migrator.Steps(2)
r := mux.NewRouter()
dbRetriever := book.NewDBRetriever(db)
retriever := book.NewRetriever(dbRetriever)
r.Handle("/book/{isbn}", rest.NewGetBookHandler(retriever))
r.HandleFunc(
"/healthcheck",
func(w http.ResponseWriter, r *http.Request) {
h := health{
Status: "OK",
Messages: []string{},
}
b, _ := json.Marshal(h)
w.WriteHeader(http.StatusOK)
w.Write(b)
})
s := http.Server{
Addr: ":8080",
Handler: r,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}
s.ListenAndServe()
}