HttpAction.go 1.61 KB
package actions

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"pro2d/conf"
	"pro2d/protos/pb"
	"pro2d/src/components/net"
	"pro2d/src/models"
	"pro2d/src/utils"
)

type HttpAction struct {
	HttpServer *net.HttpServer
}


func PubRsp(c *gin.Context, code int, data interface{}) {
	c.JSON(http.StatusOK, gin.H{"code": code, "data": data})
}

func (h *HttpAction) Register(c *gin.Context) {
	var register pb.Register
	if err := c.ShouldBindJSON(&register); err != nil {
		PubRsp(c, -1, err.Error())
		return
	}

	account := models.NewAccount(register.Phone)
	if err := account.Load(); err == nil {
		PubRsp(c, -2, "account exist: " + register.Phone)
		return
	}

	account.Uid = conf.SnowFlack.NextValStr()
	account.Password = utils.Md5V(register.Password)
	if _, err := account.Create(); err != nil{
		PubRsp(c, -3, "account register err: " + err.Error())
		return
	}
	account.Password = register.Password
	PubRsp(c, 0, account.Account)
}

func (h *HttpAction) Login(c *gin.Context) {
	var login pb.Account
	if err := c.ShouldBindJSON(&login); err != nil {
		PubRsp(c, -1, err.Error())
		return
	}
	account := models.NewAccount(login.Phone)
	if err := account.Load(); err != nil {
		PubRsp(c, -2, err.Error())
		return
	}

	if utils.Md5V(login.Password) != account.Password {
		PubRsp(c, -3, "password error")
		return
	}

	var gs []*pb.ServiceInfo
	for k, v := range h.HttpServer.EtcdClient.GetByPrefix(conf.GlobalConf.GameConf.Name) {
		gs = append(gs, &pb.ServiceInfo{
			Id:      k,
			Name:    conf.GlobalConf.GameConf.Name,
			Address: v,
		})
	}
	rsp := &pb.LoginRsp{
		Uid:         account.Uid,
		GameService: gs,
	}
	PubRsp(c, 0, rsp)
}