go restful源码剖析-4

综述


调试样例为examples\restful-encoding-filter.go,在该例子中主要引入了Path、Comsumer、Produces的概念,代码如下。

func main() {
    restful.Add(NewUserService())
    log.Print("start listening on localhost:8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func NewUserService() *restful.WebService {
    ws := new(restful.WebService)
    ws.
        Path("/users").
        Consumes(restful.MIME_XML, restful.MIME_JSON).
        Produces(restful.MIME_JSON, restful.MIME_XML)

    // install a response encoding filter
    ws.Route(ws.GET("/{user-id}").Filter(encodingFilter).To(findUser))
    return ws
}

// Route Filter (defines FilterFunction)
func encodingFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
    log.Printf("[encoding-filter] %s,%s\n", req.Request.Method, req.Request.URL)
    // wrap responseWriter into a compressing one
    compress, _ := restful.NewCompressingResponseWriter(resp.ResponseWriter, restful.ENCODING_GZIP)
    resp.ResponseWriter = compress
    defer func() {
        compress.Close()
    }()
    chain.ProcessFilter(req, resp)
}

// GET http://localhost:8080/users/42
//
func findUser(request *restful.Request, response *restful.Response) {
    log.Print("findUser")
    response.WriteEntity(User{"42", "Gandalf"})
}

Path添加流程


ws.Path("/users")在之前的样例中,都没有设置过rootpath,restful中通过调用Path函数,改变web service中的root path。

func (w *WebService) Path(root string) *WebService {
    w.rootPath = root
    if len(w.rootPath) == 0 {
        w.rootPath = "/"
    }
    w.compilePathExpression()
    return w
}

在该函数中首先将web service的root path设置为传入的/user, 并且将调用compilePathExpression生成对应的的path匹配规则

func (w *WebService) compilePathExpression() {
    compiled, err := newPathExpression(w.rootPath)
    if err != nil {
        log.Printf("invalid path:%s because:%v", w.rootPath, err)
        os.Exit(1)
    }
    w.pathExpr = compiled
}
func newPathExpression(path string) (*pathExpression, error) {
    expression, literalCount, varNames, varCount, tokens := templateToRegularExpression(path)
    compiled, err := regexp.Compile(expression)
    if err != nil {
        return nil, err
    }
    return &pathExpression{literalCount, varNames, varCount, compiled, expression, tokens}, nil
}

在处理过程中,对web service的rootpath进行加工,产出expression=^/users(/.*)?$token=/hello,并创建pathExpression对象返回。

type pathExpression struct {
    LiteralCount int      // the number of literal characters (means those not resulting from template variable substitution)
    VarNames     []string // the names of parameters (enclosed by {}) in the path
    VarCount     int      // the number of named parameters (enclosed by {}) in the path
    Matcher      *regexp.Regexp
    Source       string // Path as defined by the RouteBuilder
    tokens       []string
}

[图片上传失败...(image-306dc5-1535615090387)]

consumer及producer赋值及生效


在web service中consumer及producer各是一组属性,通过对应的接口可以直接给对应的属性赋值

// Produces specifies that this WebService can produce one or more MIME types.
// Http requests must have one of these values set for the Accept header.
func (w *WebService) Produces(contentTypes ...string) *WebService {
    w.produces = contentTypes
    return w
}

// Consumes specifies that this WebService can consume one or more MIME types.
// Http requests must have one of these values set for the Content-Type header.
func (w *WebService) Consumes(accepts ...string) *WebService {
    w.consumes = accepts
    return w
}

最终consumes生效在进行route匹配过程中,当http访问中,在获取route的函数中detectRoute

    for _, each := range methodOk {
        if each.matchesContentType(contentType) {
            inputMediaOk = append(inputMediaOk, each)
        }
    }

会执行matchesContentType,在这个函数中,将会从ws中获取到consumer检查用户的http content type是否符合consumer的设置,而produces的生效是用户调用WriteEntity函数时,调用EntityWriter使用。

// WriteEntity calls WriteHeaderAndEntity with Http Status OK (200)
func (r *Response) WriteEntity(value interface{}) error {
    return r.WriteHeaderAndEntity(http.StatusOK, value)
}
func (r *Response) EntityWriter() (EntityReaderWriter, bool) {
    sorted := sortedMimes(r.requestAccept)
    for _, eachAccept := range sorted {
        for _, eachProduce := range r.routeProduces {
            if eachProduce == eachAccept.media {
                if w, ok := entityAccessRegistry.accessorAt(eachAccept.media); ok {
                    return w, true
                }
            }
        }
        if eachAccept.media == "*/*" {
            for _, each := range r.routeProduces {
                if w, ok := entityAccessRegistry.accessorAt(each); ok {
                    return w, true
                }
            }
        }
    }
    // if requestAccept is empty
    writer, ok := entityAccessRegistry.accessorAt(r.requestAccept)
    if !ok {
        // if not registered then fallback to the defaults (if set)
        if DefaultResponseMimeType == MIME_JSON {
            return entityAccessRegistry.accessorAt(MIME_JSON)
        }
        if DefaultResponseMimeType == MIME_XML {
            return entityAccessRegistry.accessorAt(MIME_XML)
        }
        // Fallback to whatever the route says it can produce.
        // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
        for _, each := range r.routeProduces {
            if w, ok := entityAccessRegistry.accessorAt(each); ok {
                return w, true
            }
        }
        if trace {
            traceLogger.Printf("no registered EntityReaderWriter found for %s", r.requestAccept)
        }
    }
    return writer, ok
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,902评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,037评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,978评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,867评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,763评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,104评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,565评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,236评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,379评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,313评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,363评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,034评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,637评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,719评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,952评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,371评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,948评论 2 341

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,566评论 18 139
  • restful hello world 首次浏览下go-restful的工程结构,从工程组织上面来看,工程包括两个...
    tcuze阅读 575评论 0 1
  • 姓名:周小蓬 16019110037 转载自:http://blog.csdn.net/YChenFeng/art...
    aeytifiw阅读 34,695评论 13 425
  • 有时候,开始比坚持更艰难,但有时候,开始了之后坚持就会变得简单。
    墨中人阅读 131评论 0 0
  • 占高姿,树正气,显德行,朔本归源,细至精妙,开格局,驻情商,逆思维,大局者明,入局者清,明懂而自开,善以身心临境,...
    夜猫二阅读 263评论 0 0