Home > Blockchain >  Go HTTP Post Request not formatting data properly for Ruby On Rails API
Go HTTP Post Request not formatting data properly for Ruby On Rails API

Time:07-08

I've built a client in Go to interact with my Rails API. I have a model bar with a single string attribute of test. I'm trying to loop through a series of strings which are the values for the test attribute and send POST request to my API.

Here is the code for my Go client:

for _,data := range attributes{
    client := new(http.Client)

    body := []byte(fmt.Sprintf("bar: {test: %s}", data))
    fmt.Println(string(body))

    req, err := http.NewRequest(
      "POST",
      "http://localhost:3000/bars.json",
      bytes.NewReader(body),
    )

On the backend of my Rails server here is the error that I am getting:

ActionController::ParameterMissing (param is missing or the value is empty: bar):
  
app/controllers/bars_controller.rb:70:in `bar_params'
app/controllers/bars_controller.rb:25:in `create'
Invalid or incomplete POST params

I've tried formatting my Go request a couple different ways but nothing seems to work properly with the API. How do I format the data for my post request correctly?

CodePudding user response:

  1. That's "bar: {test: %s}" not a valid json, try "{ "bar": {"test": "%s"} }" (notice quotes and brackets), its better to use json.Marshal.
  2. Add json content type header req.Header.Set("Content-Type", "application/json; charset=UTF-8")

CodePudding user response:

"bar: {test: %s}" is a random, arbitrary encoding that you've just invented, and Rails cannot possibly understand how to parse it, unless you've also written some custom decoder on the Rails side.

You can't invent new encodings of data on only one end of a communications channel. You need to stick to encodings that both the client and the server can understand. For HTTP, this typically means encoding your request body in a known format, for example application/x-www-form-urlencoded.

Because this is part of a well-known standard, Go provides ways for you to do this easily; it will handle encoding the data into the body of the request and setting the correct Content-Type header which tells Rails how to decode the body:

data := url.Values{
    "bar[test]": "%s"       
}

resp, err := http.PostForm("http://localhost:3000/bars.json", data)
  • Related