background/main.go

95 lines
2.4 KiB
Go

package main
import (
"github.com/gin-gonic/gin"
"github.com/tommy351/gin-sessions"
"log"
"strconv"
"user/config"
"user/controller"
"user/db"
"user/logs"
)
var (
userController = controller.UserController{}
mailContoller = controller.MailController{}
)
func InitConfig() {
e := config.Init("user.yaml")
if nil != e {
log.Println(e.Error())
}
}
func InitMysql() {
c := config.GetMysqlConfig()
if c == nil {
logs.Error("cannnot connect mysql server")
} else {
db.Init()
}
}
func InitRedis() {
e := config.InitRedis()
if nil != e {
logs.Error(e.Error())
return
}
}
func InitLogs() {
logs.Init(config.GetLogConfig().Dir, config.GetLogConfig().File, config.GetLogConfig().Level, config.GetLogConfig().SaveFile)
}
func CORSMiddleware(c *gin.Context) {
ori := c.Request.Header.Get("Origin")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Writer.Header().Set("Access-Control-Allow-Origin", ori)
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
c.Writer.Header().Set("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, x-access-token")
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
if c.Request.Method == "OPTIONS" {
log.Println("OPTIONS")
c.AbortWithStatus(200)
} else {
c.Next()
}
}
func main() {
InitConfig()
InitLogs()
InitRedis()
InitMysql()
r := gin.Default()
store := sessions.NewCookieStore([]byte("secret123"))
r.Use(sessions.Middleware("sess_store", store))
r.Use(CORSMiddleware)
api := r.Group("/api")
{
/** 添加或修改用户 **/
api.POST("/api/user", userController.SetUser)
/** 删除用户 **/
api.DELETE("/api/user", userController.DelUser)
/** 获取单独用户详情信息 methods(id) **/
api.GET("/api/user", userController.GetUser)
/** 获取所有用户 **/
api.GET("/api/users", userController.Users)
api.POST("/api/search_users", userController.SerarchUsers)
/** 用户登录 **/
api.POST("/api/login", userController.Login)
/** 用户注册 **/
api.POST("/api/register", userController.Register)
/** 用户退出登陆 **/
api.GET("/api/logout", userController.Logout)
api.POST("/api/verify", mailContoller.OnSendEmailCode)
}
e := r.Run(":" + strconv.Itoa(config.GetPort()))
if nil != e {
log.Print(e.Error())
}
}