gitee.com/woood2/luca@v1.0.4/cmd/micro/pkg/check_perm.go (about) 1 package pkg 2 3 import ( 4 "context" 5 "fmt" 6 "gitee.com/woood2/luca/cmd/micro/internal/grpc/pb" 7 "gitee.com/woood2/luca/cmd/micro/internal/middleware/auth" 8 "gitee.com/woood2/luca/cmd/micro/internal/param" 9 "gitee.com/woood2/luca/internal/errcode" 10 "github.com/afex/hystrix-go/hystrix" 11 "github.com/go-kit/kit/circuitbreaker" 12 "github.com/go-kit/kit/endpoint" 13 grpctransport "github.com/go-kit/kit/transport/grpc" 14 "github.com/pkg/errors" 15 gr "google.golang.org/grpc" 16 "time" 17 ) 18 19 /** 20 [common errors] 21 micro errors 22 Non-enumerated errors: validate|network|server|hystrix|unknown 23 */ 24 func (c *LucaClient) CheckPerm(ctx context.Context, uid int, perm string) (ok bool, error error) { 25 req := ¶m.CheckPermRequest{Uid: uid, Perm: perm} 26 //log 27 defer func(begin time.Time) { 28 c.log(ctx, begin, req, error, ok) 29 }(time.Now()) 30 //validate 31 if err := c.validate.Struct(req); err != nil { 32 return false, errors.Wrapf(err, "luca:CheckPerm(%d, %s) validate failed", uid, perm) 33 } 34 //auth 35 ctx = auth.NewContext(ctx, auth.MakeToken(c.clientAppkey, c.clientAppSecret, 5*time.Minute, req)) 36 //send request 37 resp, err := c.checkPermEndpoint(ctx, req) 38 if err != nil { 39 return false, errors.Wrapf(err, "luca:CheckPerm(%d, %s) call endpoint failed", uid, perm) 40 } 41 r := resp.(*errcode.Resp) 42 if r.ErrCode != "" { 43 return false, code2Err(r.ErrCode) 44 } else { 45 return r.Data.(bool), nil 46 } 47 } 48 49 func encodeCheckPermRequest(_ context.Context, r interface{}) (interface{}, error) { 50 return &pb.CheckPermRequest{ 51 Uid: int64(r.(*param.CheckPermRequest).Uid), 52 Perm: r.(*param.CheckPermRequest).Perm, 53 }, nil 54 } 55 56 func decodeCheckPermResponse(_ context.Context, r interface{}) (interface{}, error) { 57 resp := r.(*pb.CheckPermResponse) 58 return &errcode.Resp{ 59 ErrCode: resp.ErrCode, 60 ErrMsg: resp.ErrMsg, 61 Data: resp.Data, 62 }, nil 63 } 64 65 func makeCheckPermClientEndpoint(conn *gr.ClientConn, instance string, options ...grpctransport.ClientOption) endpoint.Endpoint { 66 serviceName := "luca.Default" 67 method := "CheckPerm" 68 var e endpoint.Endpoint 69 { 70 e = grpctransport.NewClient( 71 conn, 72 serviceName, 73 method, 74 encodeCheckPermRequest, 75 decodeCheckPermResponse, 76 pb.CheckPermResponse{}, 77 options..., 78 ).Endpoint() 79 } 80 81 command := fmt.Sprintf("%s:%s_%s_%s", serviceName, method, instance, time.Now().Format("2006-01-02 15:04:05")) 82 hystrix.ConfigureCommand(command, hystrix.CommandConfig{ 83 Timeout: 5000, 84 MaxConcurrentRequests: 1000, 85 SleepWindow: 5000, 86 RequestVolumeThreshold: 10, 87 ErrorPercentThreshold: 50, 88 }) 89 return circuitbreaker.Hystrix(command)(e) 90 }