-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
90 lines (70 loc) · 1.97 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
package main
import (
"github.com/go-martini/martini"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"github.com/martini-contrib/binding"
"github.com/martini-contrib/render"
"net/http"
"github.com/martini-contrib/cors"
//"fmt"
)
var (
sqlConnection string
)
type User struct {
User_id int64 `form:"user_id"`
Username string `form:"username"`
Password string `form:"password"`
}
func main() {
sqlConnection = "root:NexeR2995!!@/ad1_t1"
db, err := gorm.Open("mysql", sqlConnection)
if err != nil {
panic(err)
return
}
m := martini.Classic()
allowCORSHandler := (cors.Allow(&cors.Options{
AllowOrigins: []string{"*"},
AllowMethods: []string{"PUT", "PATCH", "GET", "POST"},
AllowHeaders: []string{"Origin"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
}))
m.Use(render.Renderer())
m.Get("/", allowCORSHandler, func(r render.Render) {
r.HTML(http.StatusOK, "index", nil)
})
m.Get("/users", allowCORSHandler, func(r render.Render) {
var retData struct {
Users []User
}
db.Find(&retData.Users)
r.JSON(200, retData.Users)
})
m.Get("/user/:id", allowCORSHandler, func(r render.Render, p martini.Params) {
var retData struct {
user User
}
db.Where("user_id = ?", p["id"]).Find(&retData.user)
r.JSON(http.StatusOK, retData.user)
})
m.Get("/user/remove/:id", allowCORSHandler, func(r render.Render, p martini.Params) {
var user User
db.Where("user_id = ?", p["id"]).Delete(&user)
r.JSON(http.StatusOK, "User deleted")
})
m.Post("/user/save", allowCORSHandler, binding.Bind(User{}), func(r render.Render, u User) {
db.Save(&u)
r.JSON(http.StatusOK, "User created")
})
m.Get("/**", func(r render.Render) {
r.Redirect("/")
})
m.Post("/user/edit", allowCORSHandler, binding.Bind(User{}), func(r render.Render, u User){
db.Where("user_id = ?", u.User_id).Model(&u).Updates(User{Username: u.Username, Password: u.Password})
r.JSON(http.StatusOK, "User edited")
})
m.Run()
}