向XMLHttpRequests添加参数会导致405错误

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+'&param2='+var2+'&param3='+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))
}

You're handling a route that looks like this:

/mytemplate/some/variables/here

But you're sending the request to /mytemplate with query parameters, like this:

/mytemplate?param1=some&param2=variables&param3=here

Gorilla Mux won't match on these. If you want to match query parameters, and not URL parameters, see the .Queries method in the Gorilla Mux documentation.