新增用户
接口代码:
package router
import (
"github.com/zhangdapeng520/zdpgo_gin"
"gorm_api_user/g"
"gorm_api_user/model"
)
func userAdd(c *zdpgo_gin.Context) {
var user model.User
c.ShouldBindJSON(&user)
// 创建数据
g.GDB.Create(&user)
// 返回
c.JSON(200, user)
}
测试代码:
package router
import (
"github.com/zhangdapeng520/zdpgo_httprouter"
"io"
"os"
"testing"
)
func TestUserAdd(t *testing.T) {
targetUrl := "http://127.0.0.1:8888/user"
data := map[string]interface{}{
"name": "张三",
"age": 30,
}
resp, err := zdpgo_httprouter.SendJson("POST", targetUrl, data)
if err != nil {
t.Error(err)
}
io.Copy(os.Stdout, resp.Body)
}
删除用户
接口代码:
package router
import (
"github.com/zhangdapeng520/zdpgo_gin"
"gorm_api_user/g"
"gorm_api_user/model"
"strconv"
)
func userDelete(c *zdpgo_gin.Context) {
idStr := c.Param("id")
id, _ := strconv.Atoi(idStr)
g.GDB.Delete(&model.User{Id: id})
c.JSON(200, nil)
}
测试代码:
package router
import (
"github.com/zhangdapeng520/zdpgo_httprouter"
"io"
"os"
"testing"
)
func TestUserDelete(t *testing.T) {
targetUrl := "http://127.0.0.1:8888/user/3"
data := map[string]interface{}{}
resp, err := zdpgo_httprouter.SendJson("DELETE", targetUrl, data)
if err != nil {
t.Error(err)
}
io.Copy(os.Stdout, resp.Body)
}
修改用户
接口代码:
package router
import (
"github.com/zhangdapeng520/zdpgo_gin"
"gorm_api_user/g"
"gorm_api_user/model"
"strconv"
)
func userUpdate(c *zdpgo_gin.Context) {
var user model.User
c.ShouldBindJSON(&user)
idStr := c.Param("id")
id, _ := strconv.Atoi(idStr)
user.Id = id
g.GDB.Model(model.User{Id: id}).Update("name", user.Name, "age", user.Age)
c.JSON(200, nil)
}
测试代码:
package router
import (
"github.com/zhangdapeng520/zdpgo_httprouter"
"io"
"os"
"testing"
)
func TestUserUpdate(t *testing.T) {
targetUrl := "http://127.0.0.1:8888/user/7"
data := map[string]interface{}{
"name": "李四",
"age": 30,
}
resp, err := zdpgo_httprouter.SendJson("PUT", targetUrl, data)
if err != nil {
t.Error(err)
}
io.Copy(os.Stdout, resp.Body)
}
查询用户
接口代码:
package router
import (
"github.com/zhangdapeng520/zdpgo_gin"
"gorm_api_user/g"
"gorm_api_user/model"
"strconv"
)
func userGetAll(c *zdpgo_gin.Context) {
var users []model.User
g.GDB.Find(&users)
c.JSON(200, users)
}
func userGet(c *zdpgo_gin.Context) {
idStr := c.Param("id")
id, _ := strconv.Atoi(idStr)
var user model.User
g.GDB.Find(&user, "id=?", id)
c.JSON(200, user)
}
测试代码:
package router
import (
"io"
"net/http"
"os"
"testing"
)
func TestUserGetAll(t *testing.T) {
targetUrl := "http://127.0.0.1:8888/user"
resp, err := http.Get(targetUrl)
if err != nil {
t.Error(err)
}
io.Copy(os.Stdout, resp.Body)
}
func TestUserGet(t *testing.T) {
targetUrl := "http://127.0.0.1:8888/user/7"
resp, err := http.Get(targetUrl)
if err != nil {
t.Error(err)
}
io.Copy(os.Stdout, resp.Body)
}