/
main.go
122 lines (103 loc) · 2.54 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
package main
import (
"database/sql"
"fmt"
"github.com/elgs/gosqljson"
_ "github.com/go-sql-driver/mysql"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
"io"
"net/http"
"strings"
)
func main() {
/* -- Router -- */
// Top
goji.Get("/", Root)
// User list
goji.Get("/user_list/:offset/:limit", UserList)
// Comment List
goji.Get("/comment_list/:offset/:limit", CommentList)
// Comment
goji.Post("/coment", Comment)
goji.NotFound(NotFound)
goji.Serve()
}
/**
* root page
*/
func Root(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello Golang Goji.")
}
/**
* user list
*/
func UserList(c web.C, w http.ResponseWriter, r *http.Request) {
/* -- DB -- */
db, err := sql.Open("mysql", "root:@/test_bbs")
if err != nil {
panic(err.Error())
}
defer db.Close()
/* -- Params -- */
limit := c.URLParams["limit"]
offset := c.URLParams["offset"]
/* -- SQL -- */
sql := "SELECT id, name FROM user LIMIT ?, ?;"
theCase := "lower"
data, _ := gosqljson.QueryDbToMapJson(db, theCase, sql, offset, limit)
/* -- View -- */
w.Header().Set("Content-Type", "application/json; charset=utf-8")
io.WriteString(w, data)
}
/**
* comment list
*/
func CommentList(c web.C, w http.ResponseWriter, r *http.Request) {
/* -- DB -- */
db, err := sql.Open("mysql", "root:@/test_bbs")
if err != nil {
panic(err.Error())
}
defer db.Close()
/* -- Params -- */
limit := c.URLParams["limit"]
offset := c.URLParams["offset"]
/* -- SQL -- */
sql := "SELECT * FROM comment LIMIT ?, ?;"
theCase := "lower"
data, _ := gosqljson.QueryDbToMapJson(db, theCase, sql, offset, limit)
/* -- View -- */
w.Header().Set("Content-Type", "application/json; charset=utf-8")
io.WriteString(w, data)
}
/**
* post comment
*/
func Comment(w http.ResponseWriter, r *http.Request) {
/* -- DB -- */
db, err := sql.Open("mysql", "root:@/test_bbs")
if err != nil {
panic(err.Error())
}
defer db.Close()
/* -- Params -- */
r.ParseForm()
post := r.Form
var name, comment, tags, area string
name = strings.Join(post["name"], "")
comment = strings.Join(post["comment"], "")
tags = strings.Join(post["tags"], "")
area = strings.Join(post["area"], "")
/* -- SQL -- */
sql := "INSERT INTO comment (name, comment, tags, area, created, modified) VALUES (?, ?, ?, ?, NOW(), NOW());"
result, err := db.Exec(sql, name, comment, tags, area)
if err != nil {
fmt.Println(err)
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Println(result)
}
func NotFound(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Not Found...", 404)
}