sending post request using fetch to Golang server

Emmanuel Thomas :

I am using a golang server using gorilla/mux and a WebSocket server from "github.com/graarh/golang-socketio", I am sending data in the form of JSON to golang server where I would like to parse it into a struct, but it isn't parsing the data, click for the output for the code

package main
import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
    gosocketio "github.com/graarh/golang-socketio"
    "github.com/graarh/golang-socketio/transport"
)
type txData struct {
    to    string
    from  string
    value int
    key   string
}
func createeWsSocketServer() *gosocketio.Server {
    return gosocketio.NewServer(transport.GetDefaultWebsocketTransport())
}
func transactionHandler(w http.ResponseWriter, r *http.Request) {

    fmt.Fprintf(w, "transactionHandler Hit")
    fmt.Println("endpoint hit")
    var t txData

    decoder := json.NewDecoder(r.Body)
    fmt.Println("response Body:", r.Body)
    err := decoder.Decode(&t)

    if err != nil {
        panic(err)
    }

    fmt.Printf("%+v", t)
}
func handleRequests() {
    wsServer := createeWsSocketServer()
    wsServer.On(gosocketio.OnConnection, func(c *gosocketio.Channel) {
        c.Join("room")
        wsServer.BroadcastToAll("serverEvent", "New Client Joined!")
    })

    wsServer.On("clientEvent", func(c *gosocketio.Channel, msg string) string {
        c.BroadcastTo("room", "roomEvent", msg)
        return "returns OK"
    })

    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.Handle("/", http.FileServer(http.Dir("./static")))
    myRouter.Handle("/socket.io/", wsServer)
    myRouter.HandleFunc("/transaction", transactionHandler)
    log.Panic(http.ListenAndServe(":8080", myRouter))
}
func main() {
    handleRequests()
}

and here is the javascript code used to call the server

document.getElementById("form").addEventListener("submit", (e) => {
        e.preventDefault();
        console.log("form submitetd");
        let file = document.getElementById("fileInput").files[0];
        let fr = new FileReader();
        fr.onload = function () {
          postData(fr.result.toString());
        };

        fr.readAsText(file);
      });

      function postData(fileString) {
        let Body = {};
        Body.key = fileString;
        Body.to = document.getElementById("to").value;
        Body.from = document.getElementById("from").value;
        Body.amount = document.getElementById("amount").value;
        console.log(Body);

        fetch("/transaction", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },

          body: JSON.stringify(Body),
        }).then((resp) => {
          console.log(resp);
        });
      }
Rono :

Your txData struct fields are not exported means they are not visible outside of your package because they start with a lowercase letter. So encoding/json package can't access them. Capitalize the first letter of the fields to make them exported.

type txData struct {
    To    string
    From  string
    Value int
    Key   string
}

Reference the Golang specification here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Sending POST request in Golang with header

Sending an image and JSON data to server using Ajax POST request?

Sending a post request behind a proxy server using idHTTP

making POST request using fetch

Post request to golang server using polymer core-ajax?

Retrofit: Sending POST request to server in android

Application freezes when sending a post request to the server

jQuery or AngularJS Ajax "POST" request to server using code below however do not sending param data to server.

Fetch is not sending secure cookie during cross domain POST request

PHP $_POST variables are null when sending FormData() in a fetch request

Sending a POST request with JSON body using Guzzlehttp

Sending a Post request using VB.Net

Volley - Sending a POST request using JSONArrayRequest

Sending a POST request with JSONArray using Volley

Sending POST request to API using Alamofire

Sending Parameters in a POST request using Volley

Sending an authorised post request using RequestBuilder and HttpUriRequest

Sending an image in a php POST request using cURL

Fetch - sending POST data

Sending empty arrays to the server using jQuery post or similar Asynchronous JavaScript request

Getting Internal Server Error when sending POST request with an image file to database using React JS and Laravel

Need an example of sending xml data from salesforce to external server/another salesforce org using http post request

Golang - Sending API POST Request - Not enough arguments error

Node Fetch Post Request using Graphql Query

POST Request Using fetch() Returns 204 No Content

Sending data weekly to the server using POST

Negotiate maximum request body size with remote server before sending a POST

sending compressed numpy array (zlib) to flask server with post request [python]

Angular post request sending empty body to node.js server