-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
72 lines (62 loc) · 1.73 KB
/
server.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
71
72
package server
import (
"context"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/GoodCodingFriends/animekai/api"
"github.com/golang/protobuf/proto" //nolint:staticcheck
"github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap"
"github.com/rs/cors"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// New returns a handler for statistics server.
func New(
logger *zap.Logger,
statisticsService api.StatisticsServer,
slackService http.Handler,
fs http.FileSystem,
enableCORS bool,
) http.Handler {
ints := interceptors(logger)
srv := newStatisticsServer(statisticsService)
mux := http.NewServeMux()
mux.Handle(endpoint(srv.GetDashboardWithName(appendGRPCStatusToHeader, ints...)))
mux.Handle(endpoint(srv.ListWorksWithName(appendGRPCStatusToHeader, ints...)))
mux.Handle("/slack", slackService)
if fs != nil {
mux.Handle("/", http.FileServer(fs))
}
if enableCORS {
logger.Info("enable CORS")
return cors.Default().Handler(mux)
}
return mux
}
func newStatisticsServer(srv api.StatisticsServer) *api.StatisticsHTTPConverter {
return api.NewStatisticsHTTPConverter(srv)
}
func endpoint(service, method string, handlerFunc http.HandlerFunc) (string, http.HandlerFunc) {
return fmt.Sprintf("/%s/%s", strings.ToLower(service), strings.ToLower(method)), handlerFunc
}
func appendGRPCStatusToHeader(
ctx context.Context,
w http.ResponseWriter,
_ *http.Request,
_, _ proto.Message,
err error,
) {
if err == nil {
// When err is nil, body is already written.
return
}
code := status.Code(err)
if code == codes.Unknown {
code = codes.Internal
ctxzap.Extract(ctx).Warn("unknown gRPC code returned", zap.Error(err))
}
w.Header().Set("grpc-status", strconv.Itoa(int(code)))
}