/
server_http.go
70 lines (59 loc) · 1.52 KB
/
server_http.go
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
package microgo
import (
"context"
"fmt"
"github.com/YCloud160/microgo/config"
"github.com/YCloud160/microgo/meta"
"github.com/YCloud160/microgo/utils/xlog"
"go.uber.org/zap"
"net"
"net/http"
)
type ServerHTTP struct {
name string
conf *config.ServerConfig
httpServer *http.Server
mux http.Handler
}
func NewHttpServer(name string, mux http.Handler) Server {
srv := &ServerHTTP{
name: name,
mux: mux,
conf: config.GetServerConfig(name),
}
srv.httpServer = &http.Server{
Handler: srv,
}
return srv
}
func (srv *ServerHTTP) Start() error {
listenAddr := ":" + srv.conf.Port
listen, err := net.Listen("tcp", listenAddr)
if err != nil {
return err
}
startWaitGroup.Done()
xlog.Info(context.TODO(), "start http server", zap.String("server", srv.Name()), zap.String("listen", srv.conf.Port))
return srv.httpServer.Serve(listen)
}
func (srv *ServerHTTP) Stop() error {
err := srv.httpServer.Close()
xlog.Info(context.TODO(), "stop http server", zap.String("server", srv.Name()))
return err
}
func (srv *ServerHTTP) Name() string {
return srv.name
}
func (srv *ServerHTTP) Addr() string {
conf := config.GetConfig()
return fmt.Sprintf("%s:%s", conf.LocalIP, srv.conf.Port)
}
func (srv *ServerHTTP) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
ctx := context.TODO()
ctxData := make(map[string]string)
ctx, ctxData = setTrace(ctx, ctxData, "http request")
ctx = meta.NewOutRequestContext(ctx, ctxData)
req = req.WithContext(ctx)
defer xlog.Recover(ctx)
srv.mux.ServeHTTP(rw, req)
}