Blame view

src/components/net/http.go 1.86 KB
252ca9a0   zhangqijia   解释目录结构
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
  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")
  }