How would I read and change the values if I posted JSON data to /post route in gofiber:
{
"name" : "John Wick"
"email" : "[email protected]"
}
app.Post("/post", func(c *fiber.Ctx) error {
//read the req.body here
name := req.body.name
return c.SendString(name)
}
To retrieve the body of the POST request sent to the handler, we'll use the @RequestBody annotation, and assign its value to a String. This takes the body of the request and neatly packs it into our fullName String. We've then returned this name back, with a greeting message.
A POST request requires a body in which you define the data of the entity to be created. A successful POST request would be a 200 response code.
NSString *requestBody = [NSString stringWithFormat:@"mystring"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:[requestBody dataUsingEncoding:NSUTF8StringEncoding]];
ENTER A POST BODY As part of a POST or PUT request, a data payload can be sent to the server in the body of the request. When you select one of those methods from the method drop-down button, the API Connector form changes to display an input field for the post body. The body contents can be any valid JSON object, for example like this:
In Go, we use the http package to create GET and POST requests. The package provides HTTP client and server implementations. The following example creates a simple GET request in Go. We create a GET request to the webcode.me webpage.
A request body larger than that will now result in // Decode () returning a "http: request body too large" error. r.Body = http.MaxBytesReader (w, r.Body, 1048576 ) // Setup the decoder and call the DisallowUnknownFields () method on it. // This will cause Decode () to return a "json: unknown field ..."
API Connector defaults to the GET method. To make a POST, PUT, or PATCH request, choose that method from the drop-down menu: As part of a POST, PUT, or PATCH request, a data payload can be sent to the server in the body of the request.
You can use BodyParser
app.Post("/post", func(c *fiber.Ctx) error {
payload := struct {
Name string `json:"name"`
Email string `json:"email"`
}{}
if err := c.BodyParser(&payload); err != nil {
return err
}
return c.JSON(payload)
}
type User struct {
Name string `json: "email"`
Email string `json: "email"`
}
app.Post("/post", func(c *fiber.Ctx) error {
user := new(User)
if err := c.BodyParser(user); err != nil {
fmt.Println("error = ",err)
return c.SendStatus(200)
}
// getting user if no error
fmt.Println("user = ", user)
fmt.Println("user = ", user.Name)
fmt.Println("user = ", user.Email)
return c.SendString(user.Name)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With