Search code examples
jsongopostgorillamux

Post request to Golang API to send JSON and stringy-fied JSON


While making a POST request to Golang API, if I send stringy-fied JSON data it returns success but when I send JSON data it returns error with status 403.

Please help me understanding this behavior and how can I send JSON data using a POST request method.

File: main.go

package main

import (
    "devmgmtv2/auth"
    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

func main() {
    router := mux.NewRouter()
    auth.AuthInit(router)
    ssid.SsidInit(router)
    headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})
    originsOk := handlers.AllowedOrigins([]string{"*"})
    methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
    router.HandleFunc("/auth/login", Login).Methods("POST", "OPTIONS")
    log.Fatal(http.ListenAndServe(":8000", handlers.CORS(headersOk, originsOk, methodsOk)(router)))
}

func Login(w http.ResponseWriter, r *http.Request) {
    //Create User Struct
    var user User
    json.NewDecoder(r.Body).Decode(&user)
    userPassword := getUserPassword(user.User)
    // call get value for that user
    // check for equality if true, return the structure
    // if false return error
    if user.Password == userPassword {
        w.Header().Set("Content-Type", "text/plain")
        w.Write([]byte("success"))
    } else {
        http.Error(w, "Forbidden", http.StatusForbidden)
    }
}

Solution

  • When sending JSON to any http server you always have to use JSON.stringify().

    Not doing so will result in sending [object Object]... There are client libraries that do this kind of heavy lifting for you, but behind the scenes the JSON is always send as a string.


    Node.JS handles it the same way... it receives the string representation and usually something like body parser is run on the incoming request to extract the JSON from the string. So it might happen here behind the scenes, but it still happens.