-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
149 lines (119 loc) · 3.84 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
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package main
import (
"net/http"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
"database/sql"
"github.com/coopernurse/gorp"
_ "github.com/go-sql-driver/mysql"
"os"
"log"
"fmt"
"encoding/json"
"regexp"
)
type Book struct {
Id int64 `db:"book_id"`
Title string
Author string
Description string
}
type ClearDBInfo struct {
Credentials ClearDBCredentials `json:"credentials"`
}
type ClearDBCredentials struct {
Uri string `json:"uri"`
}
func main() {
dbmap := initDb()
defer dbmap.Db.Close()
m := martini.Classic()
m.Map(dbmap)
m.Use(render.Renderer(render.Options{
Layout: "layout",
}))
m.Get("/", ShowBooks)
m.Post("/books", CreateBook)
m.Get("/create", NewBooks)
fmt.Println("listening...")
err := http.ListenAndServe(":"+os.Getenv("PORT"), m)
PanicIf(err)
}
func NewBooks(r render.Render) {
r.HTML(200, "create", nil)
}
func CreateBook(ren render.Render, r *http.Request, dbmap *gorp.DbMap) {
new_book := Book{
Title: r.FormValue("title"),
Author: r.FormValue("author"),
Description: r.FormValue("description")}
err := dbmap.Insert(&new_book)
PanicIf(err)
ren.Redirect("/")
}
func ShowBooks(ren render.Render, r *http.Request, dbmap *gorp.DbMap) {
var books_raws []Book
_, err := dbmap.Select(&books_raws, "select * from books order by book_id")
PanicIf(err)
ren.HTML(200, "books", books_raws)
}
func dbcredentials() (DB_URI string, err error){
s := os.Getenv("VCAP_SERVICES")
services := make(map[string][]ClearDBInfo)
err = json.Unmarshal([]byte(s), &services)
if err != nil {
log.Printf("Error parsing MySQL connection information: %v\n", err.Error())
return
}
info := services["cleardb"]
if len(info) == 0 {
log.Printf("No ClearDB databases are bound to this application.\n")
return
}
// Assumes only a single ClearDB is bound to this application
creds := info[0].Credentials
DB_URI = creds.Uri
return
}
func initDb() *gorp.DbMap {
DB_URI, err := dbcredentials()
ra := regexp.MustCompile("mysql://")
rb := ra.ReplaceAllLiteralString(DB_URI, "")
rc := regexp.MustCompile("\\?reconnect=true")
rd := rc.ReplaceAllLiteralString(rb, "")
re := regexp.MustCompile(":3306")
rf := re.ReplaceAllLiteralString(rd, ":3306)")
rg := regexp.MustCompile("@")
DB_URL := rg.ReplaceAllLiteralString(rf, "@tcp(")
db, err := sql.Open("mysql", DB_URL)
PanicIf(err)
dbmap := &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8"}}
// Id property is an auto incrementing PK
dbmap.AddTableWithName(Book{}, "books").SetKeys(true, "Id")
err = dbmap.CreateTablesIfNotExists()
PanicIf(err)
dbmap.TraceOn("[gorp]", log.New(os.Stdout, "GO-sample:", log.Lmicroseconds))
populateDb(dbmap)
return dbmap
}
func populateDb(dbmap *gorp.DbMap) {
count, err := dbmap.SelectInt("select count(*) from books")
PanicIf(err)
if count == 0 {
book1 := Book{
Title: "JerBear goes to the City",
Author: "Garnee Smashington",
Description: "A young hipster bear seeks his fortune in the wild city of Irvine."}
book2 := Book{
Title: "Swarley''s Big Day",
Author: "Barney Stinson",
Description: "Putting his Playbook aside, one man seeks a lifetime of happiness."}
err = dbmap.Insert(&book1, &book2)
PanicIf(err)
}
}
func PanicIf(err error) {
if err != nil {
panic(err)
}
}