1

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:

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);
        });
      }

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I tried capitalizing it to TxData, it is still giving a null output : response Body: &{0xc00008a300 [] {[] 0 0 {<nil> false [] <nil> 0} {<nil> []} <nil> false false 0} 0 0 {<nil> false [] <nil> 0} <nil> 0 []} {to: from: value:0 key:}
Not capitalize txData capitalize it's a field like to -> To

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.