Golang is a blockbuster server side language in the field of efficiency and concurrency. If you are a Nodejs developer definitely you will come across express js for building your web api services. Gofiber is exactly like the express framework for golang and no doubt it booms with the efficiency of Fasthttp and golang.
In this blog post we will create a simple image upload server using gofiber and we will use reactjs for frontend to select image from file and upload to server.
we will use axios for http request to server and it is really awesome when we deal with implementing authentication and handling lots of api requests. It has lots of features which make life easy when dealing with api in react.
we will use chakra ui for designing material like button , images and layout it shins in Accessibility that directly effect better SEO.
library and tools we will use
golang
gofiber
reactjs
axios
chakra ui
Setup backend
create new directory and enter into it
mkdir go-react-image-upload
cd go-react-image-upload
create a new directory server inside go-react-image-upload and enter into it
mkdir server
cd server
Setup go environment
go mod init github.com/harshmangalam
install packages required for backend
go get github.com/gofiber/fiber/v2
go get github.com/google/uuid
uuid will help to generate unique id so that we can name our image easily and no two image will have same name.
create new go file main.go inside server and start writting code
packagemainimport("fmt""log""os""strings""github.com/gofiber/fiber/v2""github.com/gofiber/fiber/v2/middleware/cors""github.com/google/uuid")funcmain(){// create new fiber instance and use across whole appapp:=fiber.New()// middleware to allow all clients to communicate using http and allow corsapp.Use(cors.New())// serve images from images directory prefixed with /images// i.e http://localhost:4000/images/someimage.webpapp.Static("/images","./images")// handle image uploading using post requestapp.Post("/",handleFileupload)// delete uploaded image by providing unique image nameapp.Delete("/:imageName",handleDeleteImage)// start dev server on port 4000log.Fatal(app.Listen(":4000"))}funchandleFileupload(c*fiber.Ctx)error{// parse incomming image filefile,err:=c.FormFile("image")iferr!=nil{log.Println("image upload error --> ",err)returnc.JSON(fiber.Map{"status":500,"message":"Server error","data":nil})}// generate new uuid for image name uniqueId:=uuid.New()// remove "- from imageName"filename:=strings.Replace(uniqueId.String(),"-","",-1)// extract image extension from original file filenamefileExt:=strings.Split(file.Filename,".")[1]// generate image from filename and extensionimage:=fmt.Sprintf("%s.%s",filename,fileExt)// save image to ./images dir err=c.SaveFile(file,fmt.Sprintf("./images/%s",image))iferr!=nil{log.Println("image save error --> ",err)returnc.JSON(fiber.Map{"status":500,"message":"Server error","data":nil})}// generate image url to serve to client using CDNimageUrl:=fmt.Sprintf("http://localhost:4000/images/%s",image)// create meta data and send to clientdata:=map[string]interface{}{"imageName":image,"imageUrl":imageUrl,"header":file.Header,"size":file.Size,}returnc.JSON(fiber.Map{"status":201,"message":"Image uploaded successfully","data":data})}funchandleDeleteImage(c*fiber.Ctx)error{// extract image name from paramsimageName:=c.Params("imageName")// delete image from ./imageserr:=os.Remove(fmt.Sprintf("./images/%s",imageName))iferr!=nil{log.Println(err)returnc.JSON(fiber.Map{"status":500,"message":"Server Error","data":nil})}returnc.JSON(fiber.Map{"status":201,"message":"Image deleted successfully","data":nil})}
run main.go from server
go run main.go
Now our server is up and running we can test it using Postman
setup frontend
come outside from server directory and generate reactjs project using create-react-app
npx create-react-app reactjs
cd reactjs
install dependencies
npm i @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^4 axios