Ejemplo n.º 1
0
Archivo: http.go Proyecto: d0ngw/go
// Start 启动Http服务,开始端口监听和服务处理
func (self *HttpService) Start() bool {
	self.Lock()
	defer self.Unlock()

	c.Infof("Listen at %s", self.Conf.Addr)
	ln, err := net.Listen("tcp", self.Conf.Addr)
	if err != nil {
		c.Errorf("Listen at %s fail,error:%v", self.Conf.Addr, err)
		return false
	}

	tcpListener := tcpKeepAliveListener{ln.(*net.TCPListener)}
	if self.Conf.MaxConns > 0 {
		self.listener = netutil.LimitListener(tcpListener, self.Conf.MaxConns)
	} else {
		self.listener = tcpListener
	}

	self.graceHandler.waitGroup.Add(1)

	go func() {
		defer self.graceHandler.waitGroup.Done()
		err := self.server.Serve(self.listener)
		if err != nil {
			c.Errorf("server.Serve return with error:%v", err)
		}
	}()
	return true
}
Ejemplo n.º 2
0
Archivo: http.go Proyecto: d0ngw/go
// Init 初始化Http服务
func (self *HttpService) Init() bool {
	self.Lock()
	defer self.Unlock()

	serveMux := http.NewServeMux()

	for pattern, cname := range self.Conf.Controllers {
		c.Infof("Binding %s to %s", pattern, cname)
		handler := GetController(cname)
		if handler == nil {
			c.Criticalf("Can't find the controller for name:%s", cname)
			return false
		}
		serveMux.Handle(pattern, handler)
	}

	graceHandler := &GraceableHandler{
		handler:   serveMux,
		waitGroup: &sync.WaitGroup{}}

	server := &http.Server{
		Addr:         self.Conf.Addr,
		ReadTimeout:  self.Conf.ReadTimeout * time.Second,
		WriteTimeout: self.Conf.WriteTimeout * time.Second,
		Handler:      graceHandler}

	if self.Conf.Addr == "" {
		self.Conf.Addr = ":http"
	}

	self.graceHandler = graceHandler
	self.server = server
	self.serveMux = serveMux
	return true
}
Ejemplo n.º 3
0
Archivo: http.go Proyecto: d0ngw/go
// Stop 停止Http服务,关闭端口监听和服务处理
func (self *HttpService) Stop() bool {
	self.Lock()
	defer self.Unlock()

	if self.listener != nil {
		if err := self.listener.Close(); err != nil {
			c.Errorf("Close listener error:%v", err)
		}
	}

	//等待所有的服务
	c.Infof("Waiting shutdown")
	self.graceHandler.waitGroup.Wait()
	c.Infof("Finish shutdown")

	self.listener = nil
	self.graceHandler = nil
	self.server = nil
	self.serveMux = nil
	return true
}
Ejemplo n.º 4
0
// RegController 根据名称注册一个controller
func RegController(name string, controller http.Handler) {
	if len(name) == 0 {
		panic("The controller name must not be empty")
	}
	if reflect.ValueOf(controller).Kind() != reflect.Ptr {
		panic("The controller must be a pointer")
	}

	controllerMux.Lock()
	defer controllerMux.Unlock()

	if _, ok := controllers[name]; ok {
		panic(fmt.Errorf("Duplicate controller name:%s", name))
	} else {
		controllers[name] = controller
		c.Infof("Register controller name:%s with %T", controller)
	}
}