开发者社区 > 云原生 > 正文

请问,http 转发请求至 dubbo-go,有什么办法拿到header中的字段吗?

问题1:请问,http 转发请求至 dubbo-go,有什么办法拿到header中的字段吗? 问题2:attachment := ctx.Value(constant.AttachmentKey) 这样可以拿到吗?

展开
收起
真的很搞笑 2023-06-18 18:37:51 50 0
2 条回答
写回答
取消 提交回答
  • CSDN博客专家,51CTO博主专家,多知名企业认证讲师&签约作者&培训讲师,特邀作者等,华为云专家,资深测试开发专家,金牌面试官,职场面试培训及规划师。

    【回答】

    问题1: 可以使用 go-common/library/ecode.go 包中的 HandleHTTPError 和 WrapJSON 方法,从 http.Response 中获取 header 中的字段。

    具体操作如下:

    type Handler func(ctx *Context)
    
    func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        ctx := newContext(r, w)
        defer ctx.Body.Close()
    
        // 获取 header 中的字段
        var (
            code int
            message string
        )
        if err := h(ctx); err != nil {
            if ecode, ok := err.(*ecode.Error); ok {
                code = ecode.Code()
                message = ecode.Message()
            } else {
                code = http.StatusInternalServerError
                message = err.Error()
            }
        }
    
        // 返回响应
        ctx.RespAutoSetContentLength()
        ctx.String(http.StatusText(code), code)
        if message != "" {
            ctx.String(message, code)
        }
    }
    

    问题2: attachment := ctx.Value(constant.AttachmentKey) 可以获取到 attachment 对应的值。其中,constant.AttachmentKey 是一个常量,表示 attachment 的键。具体实现方式可以参考 context.Context.Value() 方法的实现。

    2023-06-19 18:19:33
    赞同 展开评论 打赏
  • 回答1:metadata应该可以拿得到 ,此回答整理自钉群“dubbogo社区1”

    2023-06-18 18:45:51
    赞同 展开评论 打赏

阿里云拥有国内全面的云原生产品技术以及大规模的云原生应用实践,通过全面容器化、核心技术互联网化、应用 Serverless 化三大范式,助力制造业企业高效上云,实现系统稳定、应用敏捷智能。拥抱云原生,让创新无处不在。

相关电子书

更多
Dubbo开源现状与2.7规划 立即下载
Dubbo分布式服务治理实战 立即下载
《Dubbo 3.0 前瞻》 立即下载