http.go 1.86 KB
package net

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"pro2d/conf"
	"pro2d/src/components/db"
	"pro2d/src/components/etcd"
	"pro2d/src/models"
	"reflect"
	"strings"
)

type HttpServer struct {
	version string
	port []string
	EtcdClient *etcd.EtcdClient

	Handler interface{}
}

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

func NewHttpServer(version string, port ...string) *HttpServer {
	return &HttpServer{version: version, port: port}
}

func  (h *HttpServer)HandlerFuncObj(tvl, obj reflect.Value) gin.HandlerFunc {
	return func(c *gin.Context) {
		v := tvl.Call([]reflect.Value{obj, reflect.ValueOf(c)})
		fmt.Printf("v : %v\n", v)
	}
}

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

func (h *HttpServer) BindHandler(handler interface{})  {
	h.Handler = handler
}

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

	//Etcd 初始化
	var err error
	h.EtcdClient, err = etcd.NewEtcdClient(conf.GlobalConf.Etcd)
	if err != nil {
		return err
	}
	h.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.Handler)
	val := reflect.ValueOf(h.Handler)
	//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), h.HandlerFuncObj(method.Func, val))
		r.POST(GetRoutePath(h.version, method.Name), h.HandlerFuncObj(method.Func, val))
	}
	return r.Run(h.port...) // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}