-1

I am trying to get the parameters made in a POST request, but I am not able to make it, my code is:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", hello)
    fmt.Printf("Starting server for testing HTTP POST...\n")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

func hello(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        http.Error(w, "404 not found.", http.StatusNotFound)
        return
    }
    switch r.Method {
    case "POST":
        // Call ParseForm() to parse the raw query and update r.PostForm and r.Form.
        if err := r.ParseForm(); err != nil {
            fmt.Fprintf(w, "ParseForm() err: %v", err)
            return
        }
        name := r.Form.Get("name")
        age := r.Form.Get("age")
        fmt.Print("This have been received:")
        fmt.Print("name: ", name)
        fmt.Print("age: ", age)
    default:
        fmt.Fprintf(w, "Sorry, only POST methods are supported.")
    }
}

I am making the POST request in the terminal as follows:

curl -X POST -d '{"name":"Alex","age":"50"}' localhost:8080

And then the output is:

This have been received:name: age: 

Why it is not taking the parameters? What I am doing wrong?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
kike
  • 658
  • 1
  • 8
  • 26
  • You need to first do `r.ParseForm()`, it parses the raw query from the URL and populates the form. – Deepak Patankar Sep 26 '20 at 19:38
  • A am doing that, after case: POST, in the if conditional – kike Sep 26 '20 at 19:41
  • 1
    You are sending a POST with json data. Set the `Content-Type` header and use `json.Decode` to parse the data in go. – super Sep 26 '20 at 19:43
  • Or you could change the curl command to post in urlencoded form, to match what the code expects: curl -X POST -d name=Alex -d age=50 localhost:8080 – mikerowehl Sep 26 '20 at 19:49
  • Does this answer your question? [Handling JSON Post Request in Go](https://stackoverflow.com/questions/15672556/handling-json-post-request-in-go) – Tibebes. M Sep 26 '20 at 20:15

1 Answers1

1

As you pass your body as a json object, you better define a Go struct matching that object and decode the request body to the object.

type Info struct {
    Name string
    Age  int
}
info := &Info{}
if err := json.NewDecoder(r.Body).Decode(info); err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}
_ = json.NewEncoder(w).Encode(info)

You can find the whole working code here.

$ curl -X POST -d '{"name":"Alex","age":50}' localhost:8080

This POST request is working fine now.

You could modify the Go struct and also the response object as you like .

Masudur Rahman
  • 1,585
  • 8
  • 16