For our API we will have an endpoint responsible for uploads. This endpoint will be a multipart/form-data content type.
Go to /pkg/handler/expenses.go and implement the upload action.
// Upload an attachmentit's
func (h ExpenseHandler) Upload(ctx *fiber.Ctx) error {
id, err := strconv.ParseInt(ctx.Params("id"), 10, 64)
if err != nil {
return ctx.Status(422).JSON(fiber.Map{"errors": [1]string{"We were not able to process your expense"}})
}
file, err := ctx.FormFile("attachment")
if err != nil {
return ctx.Status(422).JSON(fiber.Map{"errors": [1]string{"We were not able upload your attachment"}})
}
ctx.SaveFile(file, fmt.Sprintf("./uploads/%s", file.Filename))
var expenseDB entity.Expense
h.DB.First(&expenseDB, id)
h.DB.Model(&expenseDB).Update("attachment", file.Filename)
return ctx.JSON(fiber.Map{"message": "Attachment uploaded successfully"})
}
Through Fiber’s context, we can get the uploaded file using ctx.FormFile function. The “attachment” should be the input file name. Then we call ctx.SaveFile, that receives a file and we pass the location that we want to store the file, in my case, it will be under the /uploads folder. For now, we will be using the original file’s name, however, you might create your own naming conventions for it.
We need to update our /pkg/route/expenses.go with our new upload route.
// Expenses route
func Expenses(app *fiber.App, db *gorm.DB) {
h := &handler.ExpenseHandler{
DB: db,
}
r := app.Group("/expenses")
r.Get("/", h.Index)
r.Get("/:id", h.Show)
r.Post("/", h.Store)
r.Put("/:id", h.Update)
r.Delete("/:id", h.Destroy)
r.Post("/:id/upload", h.Upload)
}
To run your tests against our API you could use Insomnia client or any other, like Postman.

You can now upload your attachment and check the /uploads folder and the record on the database.
As always, check if your application is running if not, run the following command.
DB_NAME=figo DB_USER=root DB_PASS=4321 DB_HOST=172.17.0.2 go run .
Github repository: https://github.com/bootmind/figo-api
Part 01 https://blog.bootmind.com/golang/how-to-create-an-api-with-golang-and-fiber-part-01/
Part 02 https://blog.bootmind.com/golang/how-to-create-an-api-with-golang-and-fiber-part-02/
Part 03 https://blog.bootmind.com/golang/how-to-create-an-api-with-golang-and-fiber-part-03/
Part 04 https://blog.bootmind.com/golang/how-to-create-an-api-with-golang-and-fiber-part-04/

Leave a Reply