http.go 1.52 KB
package main

import (
	"fmt"
	"os"
	"os/signal"
	"pro2d/common"
	"pro2d/common/components"
	"pro2d/common/db/mongoproxy"
	"pro2d/common/etcd"
	"pro2d/common/logger"
	"syscall"
)

type AccountServer struct {
	components.IHttp
	EtcdClient *etcd.EtcdClient
}

func NewAccountServer(version string, port ...string) *AccountServer {
	return &AccountServer{IHttp: components.NewHttpServer(version, port...)}
}

func (s *AccountServer) Init() error {
	//mgo init
	err := mongoproxy.ConnectMongo(common.GlobalConf.AccountConf.MongoConf)

	//Etcd 初始化
	s.EtcdClient, err = etcd.NewEtcdClient(common.GlobalConf.Etcd)
	if err != nil {
		return err
	}

	//Etcd 初始化
	s.EtcdClient, err = etcd.NewEtcdClient(common.GlobalConf.Etcd)
	if err != nil {
		return err
	}
	s.EtcdClient.PutWithLeasePrefix(common.GlobalConf.AccountConf.Name, common.GlobalConf.AccountConf.ID, fmt.Sprintf("%s:%d", common.GlobalConf.AccountConf.IP, common.GlobalConf.AccountConf.Port), 5)
	return nil
}

func (s *AccountServer) Start() error {
	if err := s.Init(); err != nil {
		return err
	}

	return s.IHttp.Start()
}

func main() {
	err := make(chan error)
	stopChan := make(chan os.Signal)
	signal.Notify(stopChan, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)

	web := NewAccountServer("v1", fmt.Sprintf(":%d", common.GlobalConf.AccountConf.Port))
	web.BindHandler(&AccountAction{HttpServer: web})
	go func() {
		err <- web.Start()
	}()

	select {
	case e := <-err:
		logger.Error("http server error: %v", e)
	case <-stopChan:
		logger.Debug("http stop")
		web.Stop()
	}
}