使用Golang的Google App Engine:如何将URL路径段解析为变量?

时间:2014-10-10 03:07:16

标签: google-app-engine go url-routing

在使用Go的Google App Engine中,我想采用这样的网址:

http://www.example.com/api/account/123456/product/573832

并像这样对待:

http://www.example.com/api/account/{acctId}/product/{prodId}

然后在我的处理函数中访问acctIdprodId

我该怎么做?

3 个答案:

答案 0 :(得分:5)

你有:

func httpHandle(httpResponse http.ResponseWriter, httpRequest *http.Request) {
    urlPart := strings.Split(httpRequest.URL.Path, "/")
    // urlPart[3] is the acctId, urlPart[5] is the prodId
}

答案 1 :(得分:0)

您可能需要考虑使用库,例如​​" httprouter"为了这。这个guide可能会帮助您选择一个。

答案 2 :(得分:0)

httprouter似乎快速而简单。如果您需要更先进的复杂路由框架,那么请查看其他地方?

go get github.com/julienschmidt/httprouter

然后:

package goseo

import (
    "fmt"
    "net/http"
    "github.com/julienschmidt/httprouter"
)

func init() {
    router := httprouter.New()
    router.GET("/", index)
    http.Handle("/", router)
}

func index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    fmt.Fprint(w, "Hello, world!")
}

示例匹配:

Pattern: /user/:user

 /user/gordon              match
 /user/you                 match
 /user/gordon/profile      no match
 /user/                    no match

进一步的例子:

https://github.com/julienschmidt/httprouter

此外,我有一个app.yaml:

application: student-course-review
module: goseo
version: goseo1
runtime: go
api_version: go1

handlers:
- url: /static/(.+)
  static_files: static/\1
  upload: static/(.*)

- url: /.*
  script: _go_app