jsongounmarshalling

Problem with showing JSON data of an incoming HTTP POST request


Server-Side Go Code

package main

    import (
        "encoding/json"
        "fmt"
        "net/http"
    )

    type Authentication struct {
        username string 
        password string
    }

    func main() {

        mux := http.NewServeMux()

        mux.HandleFunc("/auth", func(w http.ResponseWriter, req *http.Request) {
            decoder := json.NewDecoder(req.Body)
            var auth Authentication
            err := decoder.Decode(&auth)

            if err != nil {
                http.Error(w, "Failed to decode JSON", http.StatusBadRequest)
                return
            }

            fmt.Printf("Received authentication: %+v\n", auth)
        })
    
        mux.Handle("/",http.FileServer(http.Dir("./static")))

        fmt.Printf("Starting server at port 3000\n")

        http.ListenAndServe(":3000", mux)
    }

Client-Side Javascript Code:

   //--Variables--//
    let signin = document.getElementById("Signin");
    let username = document.getElementById("Username");
    let password = document.getElementById("Password");

    signin.onclick = () => {
      let data = {
        username: username.value,
        password: password.value,
      };
      sendData("/auth", data);
      console.log(data.username, "   ", data.password);
    };

    //--Functions--//
    const sendData = (url, data) => {
    fetch(url, {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      });
    };

The Problem im having is that yes, the POST Request does go trough and can be seen on the Server-Side but i cant actually see the contents of the POST Request. This is what is printed on the Server-Side when a request comes trough: Received authentication: {username: password:} Its empty. My question is: Why is it empty, im pretty new to Go and im not sure on how to encode Json Data. ChatGPT said the code should work fine.

I've searched for other Stackoverflow posts and tried them out, but they never seemed to work. Probably because im doing something wrong though.


Solution

  • The problem here is that the fields are not exported. Changing the Authentication to the following should help

     type Authentication struct {
            Username string `json:"username"`
            Password string `json:"password"
        }