-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
83 lines (71 loc) · 2.04 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
package main
import (
"fmt"
"log"
"net/http"
"os"
"time"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/gorilla/mux"
)
func main() {
pgHost := getEnv("MY_DATABASE_SERVICE_HOST", "localhost")
pgPort := getEnv("DB_PORT", "5432")
pgUser := getEnv("DB_USERNAME", "postgres")
pgDBname := getEnv("DB_DBNAME", "postgres")
pgPassword := getEnv("DB_PASSWORD", "mysecretpassword")
connectionString := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=disable",
pgHost,
pgPort,
pgUser,
pgDBname,
pgPassword)
db, err := NewFruitsRepository("postgres", connectionString)
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.AutoMigrate(&Fruit{})
// Delete all data in Fruit table
db.Delete(&Fruit{})
// Sample data
_, err = db.CreateFruit(Fruit{Name: "Apple", Stock: 10})
if err != nil {
log.Fatal(err)
}
_, err = db.CreateFruit(Fruit{Name:"Orange", Stock:10 })
if err != nil {
log.Fatal(err)
}
_, err = db.CreateFruit(Fruit{Name: "Pear", Stock: 10})
if err != nil {
log.Fatal(err)
}
fruitController := NewFruitController(db)
r := mux.NewRouter()
r.HandleFunc("/api/fruits", fruitController.List).Methods("GET")
r.HandleFunc("/api/fruits/{id:[0-9]+}", fruitController.Show).Methods("GET")
r.HandleFunc("/api/fruits", fruitController.Create).Methods("POST")
r.HandleFunc("/api/fruits/{id:[0-9]+}", fruitController.Update).Methods("PUT")
r.HandleFunc("/api/fruits/{id:[0-9]+}", fruitController.Delete).Methods("DELETE")
r.PathPrefix("/").Handler(http.FileServer(assetFS()))
http.Handle("/", r)
r.Use(loggingMiddleware)
fmt.Println("Server started on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("\n[%s] %q %q",
time.Now().Format("02/Jan/2006:15:04:05 -0700"),
r.Method,
r.RequestURI)
next.ServeHTTP(w, r)
})
}
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}