How to create Base64-API using GoLang in 5 minutes?

Ujjwal Mahar
7 min readOct 15, 2023
GO!!!!

In this project, we will be creating a Base64 encoder—decoder API using GoLang.

The Base64 Encoder and Decoder API is a versatile tool that allows users to easily encode text into Base64 format and decode Base64-encoded data back into plain text or strings. Base64 encoding is commonly used for transmitting binary data as ASCII text, making it suitable for various applications such as secure data transmission, email attachments, and more.

Prerequisite —

You must have Go installed in your system. If not you can get help from here Go-Install .

Use any text editor, I will be using VSCode.

Use GoLang Extension in VSCode it will help you auto-import and many more

Setting up Directory

  1. Make a directory to store your code for me it is Base64-API.

mkdir Base64-API

2. Go into the Base64-Api directory and use go mod init <Name>command, it creates a go.mod file to track your code’s dependencies.

Alright! Once we are all set up let us install the necessary packages that we need for making our API.

Installing Packages

  1. Gin — Gin is a web framework written in Go

go get -u github.com/gin-gonic/gin

2. godotenv — This Package will help us to load vars from .env file

Folder Structure for the Project

Let us start by creating and understanding the folders required for our API

This is inside Base64-API directory:-

  1. main.go — This is going to be the main entry point of our API
  2. controllers — This directory contains our postsController.go file. This file will contain the code for handler functions.
  3. initializers — This directory contains our loadEnvVariables.gofile. This file will help us load the env var from the .env file.
  4. .env — This has our .env variables
  5. go.mod — This tracks our code dependencies
  6. go.sum — This provides checksums for the exact contents of each dependency at the time it is added to your module.
Folder Structure For Base64-Api Project

Controllers

Create a Controller directory inside the Base64-Api directory. And create a go file — postsController.goto create handler functions for our API.

The API has two main functions: PostEncode for base64 encoding and PostDecode for base64 decoding.

Handler Functions

  1. GetRoot Function (GetRoot):
  • Defines a handler for the root endpoint ("/").
  • Responds with a JSON message when the root endpoint is accessed.
//Root endpoint
func GetRoot(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Base64-Api Created With ❤️ by Ujjwal Mahar",
})}

2. PostEncode Function (PostEncode):

  • Defines a handler for encoding a provided value using base64.
  • Reads the input to be encoded from the request body and binds it to a struct.
  • Encodes the input value using base64 encoding.
  • Responds with the encoded result in a JSON message.
//For encoding the value 
func PostEncode(c *gin.Context) {

//Getting input by the user
var Encoder struct{
EncodeValue string
}
c.Bind(&Encoder)

//Encoder logic
encoder:= base64.StdEncoding.EncodeToString([]byte(Encoder.EncodeValue))

//return response

c.JSON(200, gin.H{
"EncodedResult": encoder,
})
}

The function named PostEncode that takes a pointer to an gin.Context object as a parameter. This function will handle the base64 encoding logic.

Next, we created a struct Encoder with a single field EncodeValue of type string. This struct will be used to hold the input value provided by the user.

c.Bind(&Encoder) binds the data from the request body to the Encoder struct. It extracts the EncodeValue from the request and populates it in the Encoder struct.

Now, here comes the logic to encode text to base64 encoder := base64.StdEncoding.EncoderToString([]byte(Encoder.EncoderValue)) , I used the base64 package offered by Golang. This line encodes the EncodeValue using base64 encoding. It first converts the string Encoder.EncodeValue to a byte slice and then applies base64 encoding using base64.StdEncoding.EncodeToString.

Finally, we respond to the client with a JSON message containing the encoded result. We use c.JSON to format the response with a status code of 200 and a JSON object with the key "EncodedResult" and the encoded value as the corresponding value.

3. PostDecode Function (PostDecode):

  • Defines a handler for decoding a provided base64-encoded value.
  • Reads the input to be decoded from the request body and binds it to a struct.
  • Decodes the input value using base64 decoding.
  • Responds with the decoded result in a JSON message.
func PostDecode(c *gin.Context){

//get data from the user
var Decoder struct{
ToDecodeValue string
}
c.Bind(&Decoder)

//decode logic

decoder,err := base64.StdEncoding.DecodeString(Decoder.ToDecodeValue)
if err !=nil{
log.Fatal("Error decoding the value")
}

//return the response
c.JSON(200, gin.H{
"DecodedResult": string(decoder),
})

}

Complete Code for postsController.go

package controllers

import (
"encoding/base64"
"log"

"github.com/gin-gonic/gin"
)

//Root endpoint
func GetRoot(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Base64-Api Created With ❤️ by Ujjwal Mahar",
})}

//For encoding the value
func PostEncode(c *gin.Context) {

//Getting input by the user
var Encoder struct{
EncodeValue string
}
c.Bind(&Encoder)

//Encoder logic
encoder:= base64.StdEncoding.EncodeToString([]byte(Encoder.EncodeValue))

//return response

c.JSON(200, gin.H{
"EncodedResult": encoder,
})
}

//for decoding the Base64 vale

func PostDecode(c *gin.Context){

//get data from the user
var Decoder struct{
ToDecodeValue string
}
c.Bind(&Decoder)

//decode logic

decoder,err := base64.StdEncoding.DecodeString(Decoder.ToDecodeValue)
if err !=nil{
log.Fatal("Error decoding the value")
}

//return the response
c.JSON(200, gin.H{
"DecodedResult": string(decoder),
})

}

.env File

In Go, you often use environment variables to configure aspects of your application dynamically, such as the port on which your HTTP server will listen. This allows for flexibility and easy configuration changes without modifying the code directly.

This file contains PORT= , that you want your HTTP server will use to run on.

PORT=3000

Initializers

This function is responsible for loading environment variables from a .env file using the github.com/joho/godotenv package.

package initializers

import (
"log"

"github.com/joho/godotenv"
)

func LoadEnvVariables() {
err := godotenv.Load()
if err != nil{
log.Fatal("Error loading .env file")
}
}
  • godotenv.Load() is a function that loads environment variables from a .env file in the current directory.
  • The function returns an error, which is assigned to the variable err.

Initializers folder and .env file are not much needed if are making it for fun but it is good practice to have them.

main.go

Let’s start by creating our main.go file

Start by initializing our env Variable using our initializers package.

func init() {
initializers.LoadEnvVariables()
}

The init function is a special function in Go that runs automatically before the main function. It calls the LoadEnvVariables function from the initializers package to load environment variables from a .env file.

Defining the main function

func main() {
r := gin.Default()
r.GET("/", controllers.GetRoot)
r.POST("/encode", controllers.PostEncode)
r.POST("/decode", controllers.PostDecode)
r.Run()
}

main function works as the entry point for our program.

r := gin.Default() creates a new Gin router with the default middleware.

If you face any problems try referring to Gin Documentation

  • r.GET("/", controllers.GetRoot) sets up a route for the root endpoint (HTTP GET method) and associates it with the GetRoot handler from the controllers package.
  • r.POST("/encode", controllers.PostEncode) sets up a route for the "/encode" endpoint (HTTP POST method) and associates it with the PostEncode handler from the controllers package.
  • r.POST("/decode", controllers.PostDecode) sets up a route for the "/decode" endpoint (HTTP POST method) and associates it with the PostDecode handler from the controllers package.
  • r.Run() starts the HTTP server, and it will listen on port 3000.

Let’s start our API —

go run main.go
After running it should look like this!

Let’s Try Our API

I will be using Postman to try my API you can use any tool you want.

  1. Checking for the root endpoint http://localhost:3000
GET /

As you can see we received a response message that means our API is working.

2. Now let’s make the POST request to encode the value for this start by giving the value of JSON in the Body.

{
"EncodeValue": "Base64 By Ujjwal"
}

Now as you click on send we must receive the encoded value.

POST /encode

And yes we received the message successfully !!

3. Decoding the base64 we will use the out /decode endpoint, give the base64 value in the Body, and Click Send you should see the decode value in the response.

{
"ToDecodeValue": "QmFzZTY0IEJ5IFVqandhbA=="
}
POST /decode

And yes it also works amazing!!

Cool ! We successfully created our Base64-API🥳

🤠 Checkout — Github

🐳Directly pull image from docker — Docker

--

--