在谷歌應用程序引擎一起去,我想帶一個URL是這樣的:Golang的Google App Engine:如何將URL路徑段作爲變量進行分析?
http://www.example.com/api/account/123456/product/573832
並把它像這樣:
http://www.example.com/api/account/{acctId}/product/{prodId}
然後在我的處理函數訪問acctId
和prodId
。
我該怎麼做?
在谷歌應用程序引擎一起去,我想帶一個URL是這樣的:Golang的Google App Engine:如何將URL路徑段作爲變量進行分析?
http://www.example.com/api/account/123456/product/573832
並把它像這樣:
http://www.example.com/api/account/{acctId}/product/{prodId}
然後在我的處理函數訪問acctId
和prodId
。
我該怎麼做?
你在這裏:
func httpHandle(httpResponse http.ResponseWriter, httpRequest *http.Request) {
urlPart := strings.Split(httpRequest.URL.Path, "/")
// urlPart[3] is the acctId, urlPart[5] is the prodId
}
你可能要考慮使用一個庫,如 「httprouter」 這一點。這guide可能會幫助您選擇一個。
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
在答案中包含一段代碼示例,可以幫助OP更好地理解您的答案。 「僅鏈接」答案通常不是最好的答案。 – milo526 2015-04-27 19:19:03