-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.go
154 lines (118 loc) · 4.12 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
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
150
151
152
153
154
package main
import (
"net/http"
"database/sql"
"github.com/coopernurse/gorp"
"github.com/codegangsta/martini"
"github.com/codegangsta/martini-contrib/render"
"github.com/codegangsta/martini-contrib/binding"
_ "github.com/go-sql-driver/mysql"
"html/template"
"log"
"time"
)
type Post struct {
Id int64 `db:"post_id"`
Created int64
Title string `form:"Title"`
Body string `form:"Body" binding:"required"`
}
func (bp Post) Validate(errors *binding.Errors, req *http.Request) {
//custom validation
if len(bp.Title) == 0 {
errors.Fields["title"] = "Title cannot be empty"
}
}
func main() {
// initialize the DbMap
dbmap := initDb()
defer dbmap.Db.Close()
// setup some of the database
// delete any existing rows
err := dbmap.TruncateTables()
checkErr(err, "TruncateTables failed")
// create two posts
p1 := newPost("Post 1", "Lorem ipsum lorem ipsum")
p2 := newPost("Post 2", "This is my second post")
// insert rows
err = dbmap.Insert(&p1, &p2)
checkErr(err, "Insert failed")
// lets start martini and the real code
m := martini.Classic()
m.Use(render.Renderer(render.Options{
Directory: "templates",
Layout: "layout",
Funcs: []template.FuncMap{
{
"formatTime": func(args ...interface{}) string {
t1 := time.Unix(args[0].(int64), 0)
return t1.Format(time.Stamp)
},
"unescaped": func(args ...interface{}) template.HTML {
return template.HTML(args[0].(string))
},
},
},
}))
m.Get("/", func(r render.Render) {
//fetch all rows
var posts []Post
_, err = dbmap.Select(&posts, "select * from posts order by post_id")
checkErr(err, "Select failed")
newmap := map[string]interface{}{"metatitle": "this is my custom title", "posts": posts}
r.HTML(200, "posts", newmap)
})
m.Get("/:id", func(args martini.Params, r render.Render) {
var post Post
err = dbmap.SelectOne(&post, "select * from posts where post_id=?", args["id"])
//simple error check
if err != nil {
newmap := map[string]interface{}{"metatitle":"404 Error", "message":"This is not found"}
r.HTML(404, "error", newmap)
} else {
newmap := map[string]interface{}{"metatitle": post.Title+" more custom", "post": post}
r.HTML(200, "post", newmap)
}
})
//shows how to create with binding params
m.Post("/", binding.Bind(Post{}), func(post Post, r render.Render) {
p1 := newPost(post.Title, post.Body)
log.Println(p1)
err = dbmap.Insert(&p1)
checkErr(err, "Insert failed")
newmap := map[string]interface{}{"metatitle": "created post", "post": p1}
r.HTML(200, "post", newmap)
})
m.Run()
}
func newPost(title, body string) Post {
return Post{
//Created: time.Now().UnixNano(),
Created: time.Now().Unix(),
Title: title,
Body: body,
}
}
func initDb() *gorp.DbMap {
// connect to db using standard Go database/sql API
// use whatever database/sql driver you wish
//db, err := sql.Open("sqlite3", "/tmp/post_db.bin")
db, err := sql.Open("mysql", "USERNAME:PASSWORD@unix(/var/run/mysqld/mysqld.sock)/sample")
checkErr(err, "sql.Open failed")
// construct a gorp DbMap
// dbmap := &gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}
dbmap := &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8"}}
// add a table, setting the table name to 'posts' and
// specifying that the Id property is an auto incrementing PK
dbmap.AddTableWithName(Post{}, "posts").SetKeys(true, "Id")
// create the table. in a production system you'd generally
// use a migration tool, or create the tables via scripts
err = dbmap.CreateTablesIfNotExists()
checkErr(err, "Create tables failed")
return dbmap
}
func checkErr(err error, msg string) {
if err != nil {
log.Fatalln(msg, err)
}
}