-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
56 lines (47 loc) · 1.4 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
package mux
import (
"net/http"
"github.com/goriller/ginny/middleware"
"github.com/goriller/ginny/server/health"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"go.uber.org/zap"
)
// MuxServe the custom serve mux that implement grpc MuxServe to simplify the http restful.
type MuxServe struct {
serveMux *runtime.ServeMux
opts *MuxOption
handler http.Handler
}
// NewMuxServe allocates and returns a new MuxServe.
func NewMuxServe(logger *zap.Logger, opts ...Optional) *MuxServe {
o := fullOptions(logger, opts...)
mux := &MuxServe{
opts: o,
}
mux.serveMux = runtime.NewServeMux(o.runTimeOpts...)
// default middleWares
var middlewares = []middleware.MuxMiddleware{
middleware.RecoverMiddleWare(o.logger, o.bodyMarshaler, o.errorMarshaler, o.withoutHTTPStatus),
health.HealthMiddleware,
}
if len(o.middleWares) > 0 {
middlewares = append(middlewares, o.middleWares...)
}
mux.handler = handlerWithMiddleWares(mux.serveMux, middlewares...)
return mux
}
// ServeMux return grpc gateway server mux
func (srv *MuxServe) ServeMux() *runtime.ServeMux {
return srv.serveMux
}
// Handle handle http path
func (srv *MuxServe) ServeHTTP(w http.ResponseWriter, r *http.Request) {
srv.handler.ServeHTTP(w, r)
}
// Handle handle http path
func (srv *MuxServe) Handle(method, path string, h runtime.HandlerFunc) {
err := srv.serveMux.HandlePath(method, path, h)
if err != nil {
panic(err)
}
}