聊聊dubbo-go的TokenFilter

本文主要研究一下dubbo-go的TokenFilter

TokenFilter

dubbo-go-v1.4.2/filter/filter_impl/token_filter.go

const (
    // TOKEN ...
    TOKEN = "token"
)

func init() {
    extension.SetFilter(TOKEN, GetTokenFilter)
}

// TokenFilter ...
type TokenFilter struct{}
  • TokenFilter的init方法设置了GetTokenFilter

GetTokenFilter

dubbo-go-v1.4.2/filter/filter_impl/token_filter.go

// GetTokenFilter ...
func GetTokenFilter() filter.Filter {
    return &TokenFilter{}
}
  • GetTokenFilter创建了TokenFilter

Invoke

dubbo-go-v1.4.2/filter/filter_impl/token_filter.go

// Invoke ...
func (tf *TokenFilter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
    invokerTkn := invoker.GetUrl().GetParam(constant.TOKEN_KEY, "")
    if len(invokerTkn) > 0 {
        attachs := invocation.Attachments()
        remoteTkn, exist := attachs[constant.TOKEN_KEY]
        if exist && strings.EqualFold(invokerTkn, remoteTkn) {
            return invoker.Invoke(ctx, invocation)
        }
        return &protocol.RPCResult{Err: perrors.Errorf("Invalid token! Forbid invoke remote service %v method %s ",
            invoker, invocation.MethodName())}
    }

    return invoker.Invoke(ctx, invocation)
}
  • Invoke方法读取constant.TOKEN_KEY的值invokerTkn,在该值有配置的前提下,从invocation.Attachments()获取对应的remoteTkn,之后对比invokerTkn与remoteTkn,相等则执行invoker.Invoke(ctx, invocation),否则返回错误结果

OnResponse

dubbo-go-v1.4.2/filter/filter_impl/token_filter.go

// OnResponse ...
func (tf *TokenFilter) OnResponse(ctx context.Context, result protocol.Result, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
    return result
}
  • OnResponse方法这里直接返回result

小结

TokenFilter的Invoke方法读取constant.TOKEN_KEY的值invokerTkn,在该值有配置的前提下,从invocation.Attachments()获取对应的remoteTkn,之后对比invokerTkn与remoteTkn,相等则执行invoker.Invoke(ctx, invocation),否则返回错误结果

doc

你可能感兴趣的:(dubbo)