-
Notifications
You must be signed in to change notification settings - Fork 0
/
shoeshop.go
129 lines (109 loc) · 2.91 KB
/
shoeshop.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"sync"
log "github.com/sirupsen/logrus"
mux "github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mssql"
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/postgres"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
var db *gorm.DB
var idCounter int
type MyHandler struct {
mutex sync.Mutex
}
type Shoe struct {
ID string
Model string
Brand string
Price float32
}
type ShoeServer interface {
Create(resp http.ResponseWriter, r *http.Request)
Get(resp http.ResponseWriter, r *http.Request)
Remove(resp http.ResponseWriter, r *http.Request)
}
func handlerWrapper(h http.HandlerFunc) http.HandlerFunc {
return basicAuth(h)
}
func (m *MyHandler) StatusHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("200 HTTP status code returned!"))
}
func GenerateID(shoe Shoe) string {
idCounter++
var str []string
str = append(str, strings.ToLower(shoe.Brand[:3]))
str = append(str, strconv.Itoa(idCounter))
return strings.Join(str, "-")
}
func (m *MyHandler) Create(w http.ResponseWriter, r *http.Request) {
shoe := Shoe{}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&shoe); err != nil {
log.Info(err)
fmt.Errorf("Error json decode %v", err)
return
}
defer r.Body.Close()
shoe.ID = GenerateID(shoe)
if err := db.Save(&shoe).Error; err != nil {
log.Info("Error save")
fmt.Errorf("Error save ind db %v", err)
return
}
log.Info("Added shoe")
fmt.Fprintln(w, "Succesfully added!")
}
func (m *MyHandler) Remove(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
shoe := Shoe{ID: id}
db.Delete(&shoe)
fmt.Fprintln(w, "Succesfully deleted!")
}
func (m *MyHandler) Get(w http.ResponseWriter, r *http.Request) {
var shoe Shoe
vars := mux.Vars(r)
db.Where("id = ?", vars["id"]).First(&shoe)
log.Info("here it is:", vars["id"], shoe)
}
func (m *MyHandler) List(w http.ResponseWriter, r *http.Request) {
var list []Shoe
db.Find(&list)
listJson, err := json.Marshal(list)
if err != nil {
log.Info(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(listJson)
}
func main() {
var err error
dbUrl := os.Getenv("DB_URL")
dbDialect := os.Getenv("DB_DIALECT")
db, err = gorm.Open(dbDialect, dbUrl)
if err != nil {
panic("Failed to connect DB")
}
defer db.Close()
db.AutoMigrate(&Shoe{})
h := MyHandler{}
r := mux.NewRouter()
r.HandleFunc("/", handlerWrapper(h.StatusHandler))
r.HandleFunc("/shoe", handlerWrapper(h.Create)).Methods("POST")
r.HandleFunc("/shoe/{id:[a-z]+-[0-9]+}", handlerWrapper(h.Remove)).Methods("DELETE")
r.HandleFunc("/shoe/{id:[a-z]+-[0-9]+}", handlerWrapper(h.Get)).Methods("GET")
r.HandleFunc("/shoe", handlerWrapper(h.List)).Methods("GET")
port := os.Getenv("SHOE_PORT")
log.Fatal(http.ListenAndServe(port, r))
}