-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
83 lines (65 loc) · 1.99 KB
/
server.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"
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type Server struct {
db *gorm.DB
}
var server = &Server{}
func reportHttpError(w http.ResponseWriter, err error) {
http.Error(w, "", http.StatusInternalServerError)
log.Println(err)
}
func writeJsonResponse(w http.ResponseWriter, obj interface{}) {
w.Header().Set("content-type", "application/json")
err := json.NewEncoder(w).Encode(obj)
if err != nil {
log.Println(fmt.Errorf("Error http writing response: %v", err))
}
}
func SetupDB(driver, conn string) (*gorm.DB, error) {
db, err := gorm.Open(driver, conn)
if err != nil {
return nil, err
}
db.AutoMigrate(&User{})
db.AutoMigrate(&Transfer{})
return db, nil
}
func InitTestData(w http.ResponseWriter, r *http.Request) {
server.db.Delete(&User{})
user1 := &User{FirstName: "Jean", LastName: "Carter", Email: "[email protected]", Points: 500}
user2 := &User{FirstName: "Bill", LastName: "Jones", Email: "[email protected]", Points: 600}
server.db.Create(user1)
server.db.Create(user2)
server.db.Delete(&Transfer{})
transfer1 := &Transfer{ UserID: user1.ID, Amount: 1000 }
transfer2 := &Transfer{ UserID: user1.ID, Amount: -500 }
transfer3 := &Transfer{ UserID: user2.ID, Amount: 600 }
server.db.Create(transfer1)
server.db.Create(transfer2)
server.db.Create(transfer3)
ListUsers(w, r)
}
func main() {
db, err := SetupDB("sqlite3", "/tmp/button.db")
if err != nil {
panic(err)
}
server.db = db
defer db.Close()
r := mux.NewRouter()
r.HandleFunc("/init-test-data", InitTestData)
r.HandleFunc("/users/{id}/transfers", ListTransfers).Methods("GET")
r.HandleFunc("/users/{id}/transfers", CreateTransfer).Methods("POST")
r.HandleFunc("/users/{id}", GetUser).Methods("GET")
r.HandleFunc("/users", ListUsers).Methods("GET")
r.HandleFunc("/users", CreateUser).Methods("POST")
log.Fatal(http.ListenAndServe(":8080", r))
}