Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse req.body in POST request

Tags:

post

go

I am using fetch API to send two values to my POST request handler...

fetch('http://localhost:8080/validation', {
        method:'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email:this.state.email,
            password:this.state.password
        })

I want to save both email and password as strings on the server side. Here is my attempt...

type credentials struct {
    Test string
}

func Validate(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {

    decoder := json.NewDecoder(req.Body)

    var creds credentials

    err := decoder.Decode(&creds)

    if err != nil {
        panic(err)
    }

    fmt.Println(creds.Test)
}

The problem is I do not know how exactly the format of the structure being sent to the POST. I am attempting to save req.Body as a string but this yields nothing.

When I print fmt.Println I get a blank space. What is the proper way of parsing it?

like image 824
buydadip Avatar asked Mar 11 '23 09:03

buydadip


1 Answers

Try with

type credentials struct {
    Email string `json:"email"`
    Password string `json:"password"`
}

You are receiving a JSON with two values. Receiving struct should have a structure matching your request. Otherwise, there are no placeholders to decode the JSON into, as in your case - email and password do not have matching struct fields. Btw. if you send "Test" in your JSON, this would work, as you have a Test field in your struct!

Regarding field names. If fields in JSON do not start with a capital letter or even have different names, then you should use so called tags. More on tags: https://golang.org/pkg/encoding/json/#Marshal

In my example I used them to match struct field names to your json fields, i.e. to make email from json match Email field of the credentials struct.

like image 130
oharlem Avatar answered Mar 15 '23 10:03

oharlem