package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
var db *gorm.DB
var err error
type User struct {
ID int `json:id`
Name string `json:"name"`
Age int `json:"age"`
Sex int `json:"sex"`
}
func main() {
db,_ = gorm.Open("mysql","root:root@tcp(192.168.40.10:3306)/wang?charset=utf8&parseTime=True&loc=Local")
if err != nil{
fmt.Println(err)
return
} else {
fmt.Println("connect success")
}
defer db.Close()
db.AutoMigrate(&User{})
r := gin.Default()
// 用户管理
r.GET("/",getUserList)
r.GET("/user/:id",getUserInfo)
r.GET("/users",getUserList)
r.POST("/user",addUser)
r.PUT("/user/:id",editUser)
r.DELETE("/user/:id",deleteUser)
r.Run(":8080")
}
// 用户信息
func getUserInfo(c *gin.Context) {
var user User
id := c.Params.ByName("id")
if err := db.Where("id = ?",id).First(&user).Error; err != nil{
c.AbortWithStatus(404)
fmt.Println(err)
} else {
c.JSON(200,user)
}
}
// 用户列表
func getUserList(c *gin.Context) {
var users []User
if err := db.Find(&users).Error;err!=nil{
c.AbortWithStatus(404)
fmt.Println(err)
} else {
c.JSON(200,users)
}
}
// 用户新增
func addUser(c *gin.Context) {
var user User
c.BindJSON(&user)
db.Create(&user)
c.JSON(200,user)
}
// 用户编辑
func editUser(c *gin.Context) {
var user User
id := c.Params.ByName("id")
if err := db.Where("id = ?",id).First(&user).Error;err !=nil{
c.AbortWithStatus(404)
fmt.Println(err)
}
c.BindJSON(&user)
db.Save(&user)
c.JSON(200,user)
}
// 用户删除
func deleteUser(c *gin.Context) {
var user User
id := c.Params.ByName("id")
d := db.Where("id = ?",id).Delete(&user)
fmt.Println(d)
c.JSON(200,gin.H{"id #" + id: "deleted"})
}
来源:oschina
链接:https://my.oschina.net/u/4406698/blog/4306271