My client code sends an AJAX request to server, containing a message
How could I read data from that request message body. In Express of NodeJS, I use this:
app.post('/api/on', auth.isLoggedIn, function(req, res){
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
var url = req.body.url;
// Later process
}
What is the url = req.body.url
equivalent in Go?
Here is a simple example of an http handler:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
http.HandleFunc("/", Handler)
http.ListenAndServe(":8080", nil)
// Running in playground will fail but this will start a server locally
}
type Payload struct {
ArbitraryValue string `json:"arbitrary"`
AnotherInt int `json:"another"`
}
func Handler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
url := r.URL
// Do something with Request URL
fmt.Fprintf(w, "The URL is %q", url)
payload := Payload{}
err = json.NewDecoder(bytes.NewReader(body)).Decode(&payload)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Do something with payload
}
If the request body is URL encoded, then use r.FormValue("url") to get the "url" value from the request.
If the request body is JSON, then use the JSON decoder to parse the request body to a value typed to match the shape of the JSON.
var data struct {
URL string
}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
// handle error
}
// data.URL is "url" member of the posted JSON object.