使用go的gin和gorm框架实现切换身份的接口,接收前端发送的JSON对象,查询数据库并更新,返回前端信息
接收前端发来的JSON对象,包含由openid和登陆状态组成的一个string和要切换的身份码int型
后端接收后判断要切换的身份是否低于该用户身份,是则更新数据库的登录状态为要切换的身份码,返回由openid和新的登录状态组成的string,否则返回错误码和权限不足的错误信息
测试代码
创建两个结构体,一个用来查询数据库,一个用来接收前端发送的JSON对象
连接数据库,接收前端POST请求,提取数据,查库,处理,返回信息
package main
import (
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"log"
"net/http"
"strconv"
)
type User struct {
Openid string `json:"openid" gorm:"primaryKey"`
IdCode int `json:"idcode"`
LoginState int `json:"login_state"`
}
type RequestData struct {
OpenidAndLoginStatus string `json:"openidAndLoginState"`
IdCodeToChange int `json:"idcodeToChange"`
}
func main() {
dsn := "username:password@tcp(host:port)/database?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
err = db.AutoMigrate(&User{})
if err != nil {
log.Fatal(err)
}
router := gin.Default()
// 接口测试地址 192.168.160.128:8080/update
router.POST("/update", func(c *gin.Context) {
var requestData RequestData
if err := c.ShouldBindJSON(&requestData); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON data"})
return
}
openidAndLoginState := requestData.OpenidAndLoginStatus
openID := openidAndLoginState[:len(openidAndLoginState)-1]
loginStatus, _ := strconv.Atoi(openidAndLoginState[len(openidAndLoginState)-1:])
idCode := requestData.IdCodeToChange
var user User
result := db.Where("openid = ?", openID).First(&user)
if result.Error != nil {
c.JSON(http.StatusOK, gin.H{"error": "Invalid openid"})
return
}
if user.IdCode >= idCode {
user.LoginState = loginStatus
result = db.Save(&user)
if result.Error != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Database save error"})
return
}
} else {
c.JSON(http.StatusOK, gin.H{"error": "Insufficient privileges"})
return
}
response := openID + strconv.Itoa(idCode)
c.JSON(http.StatusOK, gin.H{"response": response})
})
err = router.Run(":8080")
if err != nil {
return
}
}