In Google App Engine with Go, I would like to take a URL like this:
http://www.example.com/api/account/123456/product/573832
and treat it like this:
http://www.example.com/api/account/{acctId}/product/{prodId}
Then access acctId
and prodId
in my handler function.
How do I do this?
There you are:
func httpHandle(httpResponse http.ResponseWriter, httpRequest *http.Request) {
urlPart := strings.Split(httpRequest.URL.Path, "/")
// urlPart[3] is the acctId, urlPart[5] is the prodId
}
You might want to consider using a library, like "httprouter" for this. This guide might help you choose one.
httprouter seems to be fast and simplistic. If you need a more advanced sophisticated routing framework then look elsewhere?
go get github.com/julienschmidt/httprouter
then:
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!")
}
example matches:
Pattern: /user/:user
/user/gordon match
/user/you match
/user/gordon/profile no match
/user/ no match
further examples:
https://github.com/julienschmidt/httprouter
Further, I have an 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