HttpAction.go 2.74 KB
package actions

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

type HttpAction struct {
	version string
	port []string
}

func NewHttpAction(version string, port ...string) *HttpAction {
	return &HttpAction{version: version, port: port}
}

func Pong (c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "pong",
	})
}

func HandlerFuncObj(tvl, obj reflect.Value) gin.HandlerFunc {
	apiFun := func(c *gin.Context) interface{} { return c }
	return func(c *gin.Context) {
		tvl.Call([]reflect.Value{obj, reflect.ValueOf(apiFun(c))})
	}
}

func GetRoutePath(objName, objFunc string) string  {
	return strings.ToLower(objName + "/" + objFunc)
}

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
	}

	PubRsp(c, 0, account.Account)
}

func (h *HttpAction) Start() error {
	//mongo 初始化
	db.MongoDatabase = db.MongoClient.Database(conf.GlobalConf.AccountConf.DBName)
	models.InitAccountServerModels()

	//Etcd 初始化
	conf.EtcdClient.PutWithLeasePrefix(conf.GlobalConf.AccountConf.Name, conf.GlobalConf.AccountConf.ID, fmt.Sprintf("%s:%d", conf.GlobalConf.AccountConf.IP, conf.GlobalConf.AccountConf.Port), 5)

	//gin初始化
	r := gin.Default()
	r.GET("/ping", Pong)
	typ := reflect.TypeOf(h)
	val := reflect.ValueOf(h)
	//t := reflect.Indirect(val).Type()
	//objectName := t.Name()

	numOfMethod := val.NumMethod()
	for i := 0; i < numOfMethod; i++ {
		method := typ.Method(i)
		r.GET(GetRoutePath(h.version, method.Name), HandlerFuncObj(method.Func, val))
		r.POST(GetRoutePath(h.version, method.Name), HandlerFuncObj(method.Func, val))
	}
	return r.Run(h.port...) // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}