GoLang Gin – Binding JSON data from POST request rewrites all Identifier Fields to 0

Issue

I am taking my first steps with GoLang, and currently setting up an API Server, which is able to read JSON file from POST Request and save that to Memory.

I have a JSON File as Following:

[
    {
        "id": 0,
        "name": "kubernetes",
        "uri": "https://github.com/kubernetes/kubernetes"
    },
    {
        "id": 1,
        "name": "jenkins",
        "uri": "https://github.com/jenkinsci/jenkins"
    }
]

Which I am POST:ing to the API Server running on local port.

Here is my setupRoutes() – function:

func setupRoutes() {

    // Initialize Router
    router := gin.Default()

    // Initialize Routes
    router.GET("/api/projects", getProjects)
    router.GET("/api/projects/:id", getProjectByIdentifier)
    router.POST("/api/projects", uploadProjects)        

    // Start the Router
    router.Run("localhost:8080")
}

and here is my uploadProjects() – function:

// Reads file from POST request, and saves that to Memory.
func uploadProjects(c *gin.Context) {

    // Initialize Object
    var obj []Project

    // Bind JSON Data to Object
    c.BindJSON(&obj)

    fmt.Println(obj) // For Testing: What is binded.

    // Save Data to Memory
    proj = obj

}

and here is the Project Struct:

type Project struct {
    Identifier int64    `json: id`
    Name string         `json: name`
    Uri string          `json: uri`
}

After executing this – I can print that data out right away, what is being binded or I can fetch that with my GET /api/projects – call, and the result is always:

[{0 kubernetes https://github.com/kubernetes/kubernetes} {0 jenkins https://github.com/jenkinsci/jenkins}]

What I’ve tried:

  • I’ve tried to swap between string, int and int64 types of Identifier Field in my struct.
  • Googled a Bunch

This is probably something very simple, but I don’t really know where to look at this point, so any help is appreciated.

Solution

The id field does not match the field name Identifier. Fix by using properly formatted JSON field tags. The field tags used in the question are not recognized by the JSON codec.

type Project struct {
    Identifier int64    `json:"id"`
    Name string         `json:"name"`
    Uri string          `json:"uri"`
}

Answered By – Eric

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.