middleware.go 685 Bytes
Newer Older
kzkzzzz's avatar
kzkzzzz committed
1 2 3 4 5 6
package server

import (
	"context"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/transport"
kzkzzzz's avatar
kzkzzzz committed
7 8
	"hilo/common/errm"
	"hilo/common/validate"
kzkzzzz's avatar
kzkzzzz committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
)

// ValidateParams 验证参数
func ValidateParams() middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (interface{}, error) {
			if tr, ok := transport.FromServerContext(ctx); ok {
				err := validate.Struct(req)
				if err != nil {
					logHelper.WithContext(ctx).Warnf("[%s]参数验证失败: %s", tr.Operation(), err.Error())
					return nil, errm.ParamsError(err.Error())
				}
			}
			return handler(ctx, req)
		}
	}
}