Go: IM系统基于xorm实现简单的注册和登录功能
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
type User struct {
Id int
Username string `xorm:"unique"`
Password string
Email string `xorm:"unique"`
CreatedAt time.Time
}
func Register(c *gin.Context) {
var user User
if err := c.ShouldBind(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if _, err := engine.Insert(&user); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success", "data": user})
}
func Login(c *gin.Context) {
var user User
if err := c.ShouldBind(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var result User
if err := engine.Where("username = ?", user.Username).Get(&result); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if result.Username == user.Username && result.Password == user.Password {
c.JSON(http.StatusOK, gin.H{"status": "success", "data": result})
} else {
c.JSON(http.StatusUnauthorized, gin.H{"status": "fail", "message": "Invalid username or password"})
}
}
func main() {
r := gin.Default()
r.POST("/register", Register)
r.POST("/login", Login)
r.Run(":8080")
}
这段代码实现了用户注册和登录的功能。它使用了Gin框架来简化HTTP请求的处理,并使用xorm来操作数据库。注册时,它会检查用户名和邮箱是否唯一,登录时,它会检查用户名和密码是否匹配。这个例子教会开发者如何使用Go语言和相关库来构建一个简单的IM系统的后端。
评论已关闭