I can successfully send an XMLHttpRequest without parameters using this code:
template file:
xhr.open('POST', '/mytemplate');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status == 200) {
alert('success');
}
else {
alert('failed:' + xhr.status);
}
}
xhr.send();
router:
r.HandleFunc("/mytemplate", MyHandler).Methods("POST")
But as soon as I try to add parameters I get a 405 error. I only change 2 lines, not sure what I am doing wrong:
template file:
xhr.open('POST', '/mytemplate?param1='+var1+'¶m2='+var2+'¶m3='+var3);
router:
r.HandleFunc("/mytemplate/{param1}/{param2}/{param2}", MyHandler).Methods("POST")
Your parameters in the open command are defined as URL query parameters (everything after the ?
).
But you added them as URL path parameters in the call to r.HandleFunc
.
Try handling the base path of /mytemplate
with r.HandleFunc
and then parsing the query parameters in your MyHandler
function with r.URL.Query()
. That should return a map of the query parameters, which you should be able to reference by key (param1
, param2
...).
Stubbed out example below:
func myHandler(w http.ResponseWriter, r *http.Request) {
//get the query vals
values := r.URL.Query()
//parse specific params
param1 := values["param1"]
//do other stuff
}
func main() {
//define the handler
http.HandleFunc("/myHandlerPath", myHandler)
// do some other stuff?
// ...
// serve up the endpoint
log.Fatal(http.ListenAndServe(":8081", nil))
}