Blog

GoLang. Fiber. Passing Array by POST

One of the great web frameworks for GoLang is called Fiber. It is a relatively new framework but already has set an impressive fingerprint and many more developers check it out each day.

I personally like it for the following features. Its really fast, supports routing groups, and has an easy learning curve

Being a young framework there are some features that are still not implemented. Here is one such feature. Posting arrays.

While developing an online editor for the BCSV format, I had to post a two dimensional array, which Fiber would accept and process.

As it turned out Fiber has no method out of the box to accept array POST requests.

So to complete the goal I had to find a way to do it myself. Seemed an easy task, but but turned out quite a headache. Took me quite a while to figure it out.

 

// FiberGetValueArray2D return a 2D array of a post body

// Defaults to nil if the form key doesn't exist.

// If a default value is given, it will return that value if the form key does not exist.

// Returned value is only valid within the handler. Do not store any references.

// Make copies or use the Immutable setting instead.

func FiberGetValueArray2D(c *fiber.Ctx, key string, defaultValue ...[]string) [][]string {

    postBody := string(c.Body())

    m, _ := url.ParseQuery(postBody)

    rows := [][]string{}

    for i := 0; i < len(m); i++ {

        index := key + "[" + strconv.Itoa(i) + "][]"

        keyValue, keyExists := m[index]

        if keyExists == false {

            if i == 0 {

                return defaultValue

            }

            continue

        }

        rows = append(rows, keyValue)

    }

 

    return rows

}

 

 

The function above follows the fingerprint of the Fiber framework, so should be straightforward to use.

 

rows := FiberGetValueArray2D(c, "rows")

if rows == nil {

    return c.JSON(fiber.Map{

        "status":  "error",

         "message": "rows is required field",

    })

}

 

 

So happy coding, and hopefully this will save some other poor soul some precious time.

Good day, or night :)