Search code examples
gomultipartform-datago-echo

How to retrieve form.Value of []string type from echo.Context.MultipartForm()


I'm parsing a Multipart form from echo.Context. I retrieve the value of a slice ([]string) using form.Value. This returns a value with double braces. (eg. [["this","something"]]).

I tried reading from a non-slice (string) value and it returns correctly.

This parses the Form from c echo.Context

// Parse the Multipart form
    form, err := c.MultipartForm()
    if err != nil {
        return dataModel, err
    }

This retrieves value from the Form.

    product := form.Value["products"]
    if len(product) > 0 {
        dataModel.Product = form.Value["products"]
    }

dataModel defines a JSON struct as follows:

// LockRequest is the model for incoming lock requests
type LockRequest struct {
    Product     []string `json:"products" form:"products" query:"products"`
}

The value that dataModel.Product returns is [["crm","something"]]. It's creating a list of list probably. I want it to return ["crm","something"].

Expected: ["crm","something"] Actual: [["crm","something"]]


Solution

  • I realized that I was curl-ing the data incorrectly.

    curl -XPOST -H 'Content-Type: multipart/form-data' -F 'products=crm,something' http://localhost:50051/lockHandler

    instead of

    curl -XPOST -H 'Content-Type: multipart/form-data' -F 'products="crm","something"' http://localhost:50051/lockHandler

    worked for me.