You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.7 KiB
68 lines
1.7 KiB
package logic |
|
|
|
import ( |
|
"context" |
|
"github.com/gin-gonic/gin" |
|
"net/http" |
|
"sonet/internal/gateway_http/config" |
|
"sonet/pkg/grpc/generic" |
|
"sonet/pkg/protocol/session" |
|
"sonet/pkg/utils/resp" |
|
"sonet/pkg/utils/strs" |
|
"time" |
|
) |
|
|
|
type GrpcGenericHandler struct { |
|
grpcFactory *generic.GrpcGenericClientFactory |
|
} |
|
|
|
func NewGrpcGenericHandler(grpcFactory *generic.GrpcGenericClientFactory) *GrpcGenericHandler { |
|
return &GrpcGenericHandler{ |
|
grpcFactory: grpcFactory, |
|
} |
|
} |
|
|
|
func (h *GrpcGenericHandler) Route(route gin.IRoutes) { |
|
route.POST("/:svc/:method", h.handler) |
|
} |
|
|
|
func (h *GrpcGenericHandler) handler(c *gin.Context) { |
|
ctx := context.Background() |
|
subject, err := config.GetSubject(c) |
|
if err == nil { |
|
ctx = session.PutSubject(ctx, session.NewRpcSubject(subject.Uid)) |
|
} |
|
|
|
svc := strs.UpperInitialLetter(c.Param("svc")) |
|
method := strs.UpperInitialLetter(c.Param("method")) |
|
if svc == "" || method == "" { |
|
c.JSON(http.StatusBadRequest, resp.Error("svc not found")) |
|
return |
|
} |
|
|
|
ctx2, cancel := context.WithTimeout(ctx, time.Second*3) |
|
defer cancel() |
|
grpcClient, err := h.grpcFactory.GetClient(ctx2, svc) |
|
if err != nil { |
|
c.JSON(http.StatusForbidden, resp.Error(err.Error())) |
|
return |
|
} |
|
|
|
body := make(map[string]interface{}) |
|
err = c.BindJSON(&body) |
|
if err != nil { |
|
c.JSON(http.StatusBadRequest, resp.Error("parse request body error: "+err.Error())) |
|
return |
|
} |
|
|
|
ctx3, cancel := context.WithTimeout(ctx, time.Second*10) |
|
defer cancel() |
|
res, err := grpcClient.InvokeUnaryJson(ctx3, method, body) |
|
if err != nil { |
|
c.JSON(http.StatusInternalServerError, resp.Error(err.Error())) |
|
return |
|
} |
|
// j, err := res.MarshalJSON() |
|
// c.Render(http.StatusOK, RenderMarshaledJson{j}) |
|
c.JSON(http.StatusOK, resp.Success(res)) |
|
}
|
|
|