func database(w http.ResponseWriter, r *http.Request) {
// tried playing all sort of cat_and_mouse opts here with r
// r.Method is POST but can’t retrieve info sent
}
I have no clue how to proceed with this, can’t retrieve any info its all empty and I am pretty sure this is the right approximation to getting the data.
As @calmh said, on the Go side you need to read the request body.
You also need to send something useful, like JSON. I modified script.js to do that. The JSON can then be unmarshaled on the server side.
Assuming I understand what you are trying to do, I got something working. Put the files in their correct places, then compile and run main.go. Directing your web browser to http://127.0.0.1:8080/public/ will first get public/index.html and then public/script.js. The script will run, sending an XHR request to func database, which will print out the resulting data to the terminal.
main.go
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
func main() {
log.SetFlags(log.Lshortfile | log.Ltime)
http.HandleFunc("/db", database)
http.Handle("/public/", http.StripPrefix("/public", http.FileServer(http.Dir("public"))))
log.Println("starting")
http.ListenAndServe("127.0.0.1:8080", nil)
}
type Data struct {
Foo string `json:"foo"`
}
func database(w http.ResponseWriter, r *http.Request) {
log.Println("database")
b, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var data Data
err = json.Unmarshal(b, &data)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Printf("%#v", data)
}
Guys it did work thanks Followed the pattern showed by @nathankerr and tailored to my app and is working nice. Took me a while to come back because wanted to make sure everything was alright in my end.