98 lines
2.0 KiB
Go
98 lines
2.0 KiB
Go
package web
|
|
|
|
import (
|
|
"context"
|
|
"strings"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"google.golang.org/grpc/metadata"
|
|
|
|
"git.loafle.net/commons_go/logging"
|
|
backGRpc "git.loafle.net/overflow/overflow_api_server/golang"
|
|
"git.loafle.net/overflow/overflow_gateway_web/handler"
|
|
gws "git.loafle.net/overflow/overflow_gateway_websocket"
|
|
"git.loafle.net/overflow/overflow_gateway_websocket/protocol/jsonrpc"
|
|
grpcPool "git.loafle.net/overflow/overflow_grpc_pool"
|
|
)
|
|
|
|
type WebHandler interface {
|
|
handler.Handler
|
|
}
|
|
|
|
type webHandler struct {
|
|
ctx context.Context
|
|
logger *zap.Logger
|
|
so *gws.SocketOptions
|
|
ro *jsonrpc.Options
|
|
handler gws.MessageHandler
|
|
pool grpcPool.Pool
|
|
}
|
|
|
|
func New(ctx context.Context, pool grpcPool.Pool) WebHandler {
|
|
h := &webHandler{
|
|
ctx: ctx,
|
|
logger: logging.WithContext(ctx),
|
|
pool: pool,
|
|
}
|
|
|
|
h.ro = &jsonrpc.Options{
|
|
OnRequest: h.onRequest,
|
|
OnNotify: h.onNotify,
|
|
}
|
|
|
|
h.handler = jsonrpc.NewHandler(ctx, h.ro)
|
|
|
|
h.so = &gws.SocketOptions{
|
|
Handler: h.handler,
|
|
}
|
|
|
|
return h
|
|
}
|
|
|
|
func (h *webHandler) GetSocketOption() *gws.SocketOptions {
|
|
return h.so
|
|
}
|
|
|
|
func (h *webHandler) onRequest(soc gws.Socket, method string, params []string) (interface{}, error) {
|
|
h.logger.Info("OnRequest",
|
|
zap.String("path", soc.Path()),
|
|
zap.String("method", method),
|
|
zap.Any("params", params),
|
|
)
|
|
|
|
c, err := h.pool.Get()
|
|
if err != nil {
|
|
h.logger.Error("cannot retrive GRPC Client")
|
|
return nil, err
|
|
}
|
|
defer h.pool.Put(c)
|
|
|
|
sm := strings.Split(method, ".")
|
|
|
|
si := &backGRpc.ServerInput{
|
|
Target: sm[0],
|
|
Method: sm[1],
|
|
Params: params,
|
|
}
|
|
|
|
md := metadata.Pairs("email", "overflow@loafle.com")
|
|
ctx := metadata.NewOutgoingContext(context.Background(), md)
|
|
|
|
so, err := c.(backGRpc.OverflowApiServerClient).Exec(ctx, si)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return so.Result, nil
|
|
}
|
|
|
|
func (h *webHandler) onNotify(soc gws.Socket, method string, params []string) error {
|
|
h.logger.Info("OnRequest",
|
|
zap.String("path", soc.Path()),
|
|
zap.String("method", method),
|
|
zap.Any("params", params),
|
|
)
|
|
return nil
|
|
}
|