我们今天,在增加一两个小块,更加适开发
我们今天就增加一点middleware
go kit 对middleware的定义,从字面意思就能看出来,没错就是中间件,是的,没看错~~~ 哈哈
那我们今天就增加一个token中间件吧,现在所有的应用中都有token等权限的校验,好了好了,直接进入正题:
我们先看一下kit中的middleware是如何定义的:
这就是 kit中 中间件的初定义
func JwtMiddleware() endpoint.Middleware {
}
继续追踪
// Middleware is a chainable behavior modifier for endpoints.
type Middleware func(Endpoint) Endpoint
看一下他的描述:这个middlerware的类型,是一个方法,func(Endpoint) Endpoint,方法的返回值其实也就是一个endpoint,也就是说:kit中的中间件实际上也就是一个endpoint
// Endpoint is the fundamental building block of servers and clients.
// It represents a single RPC method.
type Endpoint func(ctx context.Context, request interface{}) (response interface{}, err error)
好那我们就清楚这个中间件的创建了,对吧,直接上
// 这只是简单的创建,需要完善其中的判断逻辑,
func JwtMiddleware() endpoint.Middleware {
return func(e endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
return nil, nil
}
}
}
到目前为止,我们知道了如何去创建一个middleware,下面是使用,目前我们中间件的业务逻辑没有完善,需要完善,但是现在要展示如何使用:
func ServiceForHttp(r *mux.Router) {
getCode := goKitHttp.NewServer(
JwtMiddleware()(GenVcEndpoint()),
DecodeVcRequest, EncodeVcResponse)
r.Methods("Get").Path(`/getName/{uid:\d+}`).Handler(getCode)
}
OK,到此为止,中间的声明以及使用,就ok了,下一步我们完善jwt的token校验
---------
下面是代码所在位置,有兴趣的可以拉去共同探讨一下
https://gitee.com/weishunuan_163com/go