Passing text to golang

I am trying to send a text string to golang. I can’t find a way to get it to work.

This is what I have :

var j = `{"var":"test","id":10,"quant":1,"uid":1}`;

                        

              $.ajax({

              url: "http://localhost:8080/display",

              type: 'POST',

              dataType: 'json',

              contentType: "application/json; charset=utf-8",

              //crossDomain: true,

              data:  "mydata=" + j,

              success: function (result) {
func display1(w http.ResponseWriter, r *http.Request) {

    err5 := r.ParseForm()

    if err5 != nil {

        fmt.Println(err5)

    }

    username := r.Form["var"][0]

    fmt.Println(username)

I’ve tried for hours, will you show me a solution, please?

Do you make an AJAX call from a web page and try to send the result to Go? If this is the matter you can “write” to the body and read from the body.

In the browser you write to the body like goForm

htmltag.innerHTML = "text"

And in Go you read this body in some way https://goapi.go4webdev.org/client

json.NewDecoder(resp.Body).Decode(&result)

If you try to “read” a web form you can use the “form keys” to fetch the values:

r.ParseForm()
mailfrom := r.FormValue("mail")
mailtype := r.FormValue("type")
1 Like

This didn’t work, I am just looking for a simple POST that sends the JSON to the golang and it recieves it. I can get it working with url parameters and GET, but I just want to send it over. This is because the data is longer than 2000 characters. It looks like the two options are decode and parseform(), it isn’t a form though. All the web examples don’t work and rarely show both the ajax call and the golang code. They also mostly contain the json in the golang code not sent from ajax/javacsript.

I have used a struct too…

I found this on SO. I interpret this method to pretend to be a web form and you pull the data as it was a form…

1 Like

Thanks, however this would defualt the contenttype to be form instead of json in the Jquery AJAX call…

This is what I have now (which is a JSON GET that works). I am trying to do a JSON POST. I am using JQuery.

var members='{"var" : 10}';

            var membersJSONString=JSON.stringify(members);

              $.ajax({

              url: "http://localhost:8080/display",

              type: 'GET',

              dataType: 'json',

              contentType: "application/json; charset=utf-8",

              crossDomain: true,

              data:  members,

              processData: true,

              success: function (result) {
func display1(w http.ResponseWriter, r *http.Request) {

    r.ParseForm()

    var body1 []byte

    for key, _ := range r.Form {

    body1 = []byte(key)

    fmt.Println(body1)

    fmt.Println(string(body1))

    break

}

This code implies that there is an html form involved. That the key and value are submitted by using a form. Otherwise you have to write to the body and read the body. AFAIK.

In your example you do either use a html form or write to the body, but the Go code assume there is an html form involved.

Here is how you could send a form without a form (Vanilla Javascript - sorry)

1 Like

So, I am trying to see it your way, and I think I am understanding. The contenttype is multipart/form-data and I am decoding r.Body. Everything is working now but I am wondering, is this JSON as the data transfer?

Thanks so much,
Joshua

(“key”, “value”) is quite similar to JSON, but {“key”:“value”} is JSON format. Many records should start and end with square brackets an separated by comma. [{“key”:“value”},{“key”:“value”}]

Reading and saving as JSON is another story :slight_smile:

1 Like

Oh, I thought this was saving and reading with JSON! Does the process become a JSON save when just your format is used and the contenttype is changed? And, in my example, what is the point of sending over using JSON instead of an HTML? :slight_smile: Actually, I am thinking that save/read is a way of passing large amounts of data to golang, is this what you mean?

I do this in javascript:

  fetch("model", {
    credentials: "include",
    method: "POST",
    headers:{
        "Content-Type": "application/json"
      },
    body: JSON.stringify(payload)})
    .then(response=>response.json())
    .then(data => displayResponse(data));

The Go service endpoint defines a struct matching the expected structure of the payload and decodes the body like this:

var postParameters struct {...}
if err := json.NewDecoder(req.Body).Decode(&postParameters); err != nil {
2 Likes

Came here to make sure somebody mentioned Fetch. With one minor caveat that it’s not supported by IE. But most people don’t have to worry about IE anymore (thank goodness).

@JoshuaE your example is close. As Jeff mentioned, you need to properly decode your JSON. Take, for example, the data you’re posting (I renamed var to something that’s not a keyword, so var is now myNumber):

{"myNumber" : 10}

… and you want to decode it using json.NewDecoder as in Jeff’s example. You would need a struct to decode it into. You might be getting hung up on a few things. First, let’s say you have a struct that looks like this:

// Struct to decode JSON in to that mirrors javascript code
type postPayload struct {
    myNumber int
}

At first glance, it might look OK. But what would happen if try to decode your json using json.NewDecoder? It wouldn’t produce your desired result because myNumber is a private field. I’ve seen many a new go developer get hung up on this. If you haven’t yet, check out gobyexample.com/json.

Here’s a contrived working example that you can run on the go playground:

package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

type postPayload struct {
	MyNumber int
}

func main() {
	// Simulate request body by making a reader from string containing JSON
	r := strings.NewReader(`{"myNumber" : 10}`)
	res := postPayload{}
	// This would be your request's body (r.Body)
	json.NewDecoder(r).Decode(&res)
	fmt.Println(res.MyNumber)
}

As long as you’re sending proper JSON in the request body, that code would work fine. However, you could have a different problem: your javascript code might not be doing exactly what you think it’s doing. So, you should use Chrome (or whatever browser you’re using) dev tools to make sure the request is sending exactly the payload you think it is. You can also use a tool like postman for testing.

1 Like

First make sure that your function is called with the JSON data when you send the POST request. To do so, we simply print out the received data to the console.

func display1(w http.ResponseWriter, r *http.Request) {
    // read all received data into s that will be of type []byte
    s, err := ioutil.ReadAll(r.Body) 
    if err != nil {
        panic(err) 
    }
    // print the content of s to the console (stdout)
    fmt.Println(string(s))
}

If you see the expected JSON text, we can proceed to the second step that is decoding the JSON data.

type myData struct {
    Var string `json:"var"` 
    ID int `json:"id"`
    Quant int `json:"quant"`
    UID int `json:"uid"`
}

func display1(w http.ResponseWriter, r *http.Request) {
    // read all received data into s that will be of type []byte
    s, err := ioutil.ReadAll(r.Body) 
    if err != nil {
        panic(err) 
    }

    // decode the received JSON data
    var data myData
    if err := json.Unmarshall(s, &data); err != nil {
        panic(err)
    }
    // print data to the console
    fmt.Printf("%+v\n", data)
}

When using POST with this ajax function, you don’t send a form. The request data is the JSON encoding. That is why we get the JSON data by simply reading all the data from r.Body.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.