-
Notifications
You must be signed in to change notification settings - Fork 13
/
server.go
110 lines (90 loc) · 2.46 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package http
import (
"encoding/json"
"net/http"
"github.com/asim/go-micro/v3"
"github.com/asim/go-micro/v3/metadata"
"github.com/go-chi/chi"
chimiddleware "github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
"github.com/owncloud/ocis-hello/pkg/assets"
"github.com/owncloud/ocis-hello/pkg/proto/v0"
"github.com/owncloud/ocis-hello/pkg/version"
"github.com/owncloud/ocis/ocis-pkg/account"
"github.com/owncloud/ocis/ocis-pkg/middleware"
ohttp "github.com/owncloud/ocis/ocis-pkg/service/http"
)
type greetRequest struct {
Name string `json:"name"`
}
// Server initializes the http service and server.
func Server(opts ...Option) ohttp.Service {
options := newOptions(opts...)
handler := options.Handler
svc := ohttp.NewService(
ohttp.Logger(options.Logger),
ohttp.Name(options.Name),
ohttp.Version(options.Config.Server.Version),
ohttp.Address(options.Config.HTTP.Addr),
ohttp.Namespace(options.Config.HTTP.Namespace),
ohttp.Context(options.Context),
ohttp.Flags(options.Flags...),
)
mux := chi.NewMux()
mux.Use(chimiddleware.RealIP)
mux.Use(chimiddleware.RequestID)
mux.Use(middleware.NoCache)
mux.Use(middleware.Cors)
mux.Use(middleware.Secure)
mux.Use(middleware.ExtractAccountUUID(
account.Logger(options.Logger),
account.JWTSecret(options.Config.TokenManager.JWTSecret)),
)
mux.Use(middleware.Version(
options.Name,
version.String,
))
mux.Use(middleware.Logger(
options.Logger,
))
mux.Use(middleware.Static(
options.Config.HTTP.Root,
assets.New(
assets.Logger(options.Logger),
assets.Config(options.Config),
),
options.Config.HTTP.CacheTTL,
))
mux.Route(options.Config.HTTP.Root, func(r chi.Router) {
r.Post("/api/v0/greet", func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var req greetRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if req.Name == "" {
render.Status(r, http.StatusBadRequest)
render.PlainText(w, r, "missing a name")
return
}
accountID, ok := metadata.Get(ctx, middleware.AccountID)
if !ok {
return
}
greeting := handler.Greet(accountID, req.Name)
rsp := &proto.GreetResponse{
Message: greeting,
}
render.Status(r, http.StatusCreated)
render.JSON(w, r, rsp)
})
})
err := micro.RegisterHandler(svc.Server(), mux)
if err != nil {
options.Logger.Fatal().Err(err).Msg("failed to register the handler")
}
svc.Init()
return svc
}