聊聊dubbo-go-proxy的replacePathFilter


本文摘自网络,作者,侵删。

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

replacePathFilter

dubbo-go-proxy/pkg/filter/replacepath/replace_path.go

// replacePathFilter is a filter for host.
type replacePathFilter struct {
    path string
}

// New create replace path filter.
func New(path string) filter.Filter {
    return &replacePathFilter{path: path}
}

func (f replacePathFilter) Do() context.FilterFunc {
    return func(c context.Context) {
        f.doReplacePathFilter(c.(*http.HttpContext))
    }
}

func (f replacePathFilter) doReplacePathFilter(ctx *http.HttpContext) {
    req := ctx.Request
    if req.URL.RawPath == "" {
        req.Header.Add(ReplacedPathHeader, req.URL.Path)
    } else {
        req.Header.Add(ReplacedPathHeader, req.URL.RawPath)
    }

    req.URL.RawPath = f.path
    var err error
    req.URL.Path, err = url.PathUnescape(req.URL.RawPath)
    if err != nil {
        ctx.AddHeader(constant.HeaderKeyContextType, constant.HeaderValueTextPlain)
        ctx.WriteWithStatus(nh.StatusInternalServerError, []byte(replacePathError))
        ctx.Abort()
        return
    }

    req.RequestURI = req.URL.RequestURI()

    ctx.Next()
}
replacePathFilter定义了path属性;它实现了Filter的Do方法,该方法执行的是doReplacePathFilter方法,它会往header写入名为ReplacedPathHeader,若req.URL.RawPath为空则取req.URL.Path;之后将req.URL.RawPath更新为f.path,再通过url.PathUnescape(req.URL.RawPath)计算req.URL.Path,最后将req.URL.RequestURI()赋值给req.RequestURI

httpFilter

dubbo-go-proxy/pkg/proxy/listener.go

func httpFilter(ctx *h.HttpContext, request fc.IntegrationRequest) {
    if len(request.Host) != 0 {
        ctx.AppendFilterFunc(host.New(request.Host).Do())
    }
    if len(request.Path) != 0 {
        ctx.AppendFilterFunc(replacepath.New(request.Path).Do())
    }
}
httpFilter方法会根据request.Path通过AppendFilterFunc添加replacepath.New(request.Path)

小结

dubbo-go-proxy的httpFilter会根据request.Path通过AppendFilterFunc添加replacepath.New(request.Path);而replacePathFilter会根据path属性替换req.URL.RawPath及req.URL.Path,最后更新req.RequestURI。

doc

  • dubbo-go-proxy

本文来自:Segmentfault

感谢作者:.container .card .information strong

查看原文:聊聊dubbo-go-proxy的replacePathFilter

相关阅读 >>

10天入门Go语言教程- hello world

Golang base64字符串的编码和解码

Go mod使用

slice

linux环境Golang配置

Golang中创建错误的方法

Golang如何退出进程?

手撸Golang Go与微服务 chatserver之4 内存泄漏

Go调优神器trace介绍

Go get下载包失败问题

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...