Form Data with Fiber
This example demonstrates how to parse application/x-www-form-urlencoded request bodies into Go structs, slices and maps using Fiber v3's Bind().Body().
Description
This project shows four ways a urlencoded form body can be parsed: a flat struct, a repeated field into a []string, a nested struct plus a slice of structs, and dynamic keys into a map via net/url.ParseQuery.
Requirements
Project Structure
main.go: The main application entry point.go.mod: The Go module file.
Setup
-
Clone the repository:
git clone https://github.com/gofiber/recipes.gitcd recipes/form-data -
Install the dependencies:
go mod download -
Run the application:
go run main.go
The application should now be running on http://localhost:3000.
Example Usage
-
Send a POST request to
http://localhost:3000/structwith a flat form:curl -X POST http://localhost:3000/struct -d "[email protected]&age=30" -
Send a POST request to
http://localhost:3000/slicewith a repeated field:curl -X POST http://localhost:3000/slice -d "tags=go&tags=web"{"tags":["go","web"]} -
Send a POST request to
http://localhost:3000/nestedwith a nested struct and a slice of structs:curl -X POST http://localhost:3000/nested -d "customer=Jane&address.street=Main+St&address.city=Springfield&items.0.name=Widget&items.0.qty=2&items.1.name=Gadget&items.1.qty=1"{"customer":"Jane","address":{"street":"Main St","city":"Springfield"},"items":[{"name":"Widget","qty":2},{"name":"Gadget","qty":1}]} -
Send a POST request to
http://localhost:3000/mapwith keys that have no matching struct field:curl -X POST http://localhost:3000/map -d "color=blue&size=M&size=L"{"color":["blue"],"size":["M","L"]} -
A field that cannot convert to its declared Go type returns a 400 with the bind error:
curl -X POST http://localhost:3000/struct -d "[email protected]&age=notanumber"{"error":"bind \"age\" from body: schema: error converting value for \"age\""}
Code Overview
main.go
The main Go file sets up the Fiber application and four routes, each binding a urlencoded form body into a different Go shape:
POST /structbinds a flat form into a struct withBind().Body().POST /slicebinds a repeated field (tags=go&tags=web) into a[]string.POST /nestedbinds a dotted key path (address.street) into a nested struct, and a dotted, indexed key path (items.0.qty) into a slice of structs.POST /mapparses the raw body into amap[string][]stringusingnet/url.ParseQueryas a standard-library alternative (Fiber'sBind().Body()also natively supports binding form bodies into maps).
Conclusion
This example provides a minimal reference for binding application/x-www-form-urlencoded bodies in a Go Fiber application, covering scalar fields, repeated fields, nested structs, slices of structs, and dynamic keys.