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