summaryrefslogtreecommitdiff
path: root/http/service.go
blob: 7f4261d052f611792a2119ddfd93b78d3d04f22b (plain)
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
package http

import (
	"context"
	"github.com/sirupsen/logrus"
	"github.com/spiral/roadrunner/service"
	"net/http"
)

type Service struct {
	cfg  *serviceConfig
	http *http.Server
	srv  *Server
}

func (s *Service) Name() string {
	return "http"
}

func (s *Service) Configure(cfg service.Config) (bool, error) {
	config := &serviceConfig{}
	if err := cfg.Unmarshal(config); err != nil {
		return false, err
	}

	if !config.Enabled {
		return false, nil
	}

	if err := config.Valid(); err != nil {
		return false, err
	}

	s.cfg = config
	return true, nil
}

func (s *Service) RPC() interface{} {
	return &RPCServer{s}
}

func (s *Service) Serve() error {
	logrus.Debugf("http: started")
	defer logrus.Debugf("http: stopped")

	rr, term, err := s.cfg.Pool.NewServer()
	if err != nil {
		return err
	}
	defer term()

	s.srv = NewServer(s.cfg.httpConfig(), rr)
	s.http = &http.Server{
		Addr:    s.cfg.httpAddr(),
		Handler: s.srv,
	}

	if err := s.http.ListenAndServe(); err != nil {
		return err
	}

	return nil
}

func (s *Service) Stop() error {
	return s.http.Shutdown(context.Background())
}