go - route a PUT request without a third party routing library -
in this youtube video (at around 15:29) of golang talk blake mizerany, talks how build router without using third party package, covering in detail how construct route has variable component, such id. handler uses, first line showing how variable component of route (i.e. key)
func producthandler(w http.responsewriter, r *http.request){ key := r.url.path[len("/products/":] switch r.method{ case "get": //do stuff case "post" //do stuff default: http.error(w, "method not allowed", 405) } }
it's not clear presentation though actual route looks like.
i'm trying build route handles put request id. when click element on page, sends put request route
http://localhost:8080/products/1433255183951
i have route this
http.handlefunc("/products/{id}", dosomethingwithproduct){ }
and of course have func
func dosomethingwithproduct(res http.responsewriter, req *http.request{ key := req.url.path[len("/products/"):] log.println(key, "is logging?? nope") }
problem. though have route set up, , handler, when click element got 404 not found, , there's no indication function called (i.e. it's not logging)
question: how create custom route/func handles put request
http://localhost:8080/products/1433255183951
http.handlefunc
not handle "capture groups" you're trying {id}
.
http.handlefunc("/products/", handler)
match routes begin pattern. have parse rest of yourself.
see servemux.
servemux http request multiplexer. matches url of each incoming request against list of registered patterns , calls handler pattern closely matches url.
patterns name fixed, rooted paths, "/favicon.ico", or rooted subtrees, "/images/" (note trailing slash). longer patterns take precedence on shorter ones, if there handlers registered both "/images/" , "/images/thumbnails/", latter handler called paths beginning "/images/thumbnails/" , former receive requests other paths in "/images/" subtree.
note since pattern ending in slash names rooted subtree, pattern "/" matches paths not matched other registered patterns, not url path == "/".
patterns may optionally begin host name, restricting matches urls on host only. host-specific patterns take precedence on general patterns, handler might register 2 patterns "/codesearch" , "codesearch.google.com/" without taking on requests "http://www.google.com/".
servemux takes care of sanitizing url request path, redirecting request containing . or .. elements equivalent .- , ..-free url.
Comments
Post a Comment