Basics of Backend Development with Go (Golang)
Basics of Backend Development with Go (Golang)

Basics of Backend Development with Go (Golang)

Date
Aug 1, 2023
Tags
backend
programming
At my current workplace (as of Aug 2023 - Seoul Robotics), we use Go for backend development. I’m not a backend developer but I would like to expand my knowledge so I started learning it
Here are some of my notes that I took when I got started with Golang.
 

Getting Started with Backend Development in Go: Creating APIs

Prerequisites

Before we dive into backend development with Go, ensure you have the following prerequisites:
  1. Go Installation: If you haven't already, download and install Go from the official website: https://golang.org/dl/.

Step 1: Setting Up Your Project

  1. Create a Project Directory: Begin by creating a project directory for your backend development work.
  1. Initialize Go Module: Open your terminal, navigate to the project directory, and run the following command to initialize a Go module:
    1. go mod init mybackendapp
       

Step 2: Creating an API (using "net/http”)

  1. Create a File: Inside your project directory, create a new file named main.go.
  1. Import Necessary Packages: Open main.go and import the required packages:
package main import ( "fmt" "net/http" )
  1. Define a Handler Function: Create a handler function that will respond to HTTP requests. This function will be called whenever an HTTP request is made to your API:
    1. func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, World!") }
  1. Set Up Routes: In the main function, set up the routes for your API using the http package:
func main() { http.HandleFunc("/", helloHandler) http.ListenAndServe(":8080", nil) }

Step 3: Running Your API

  1. Run the API: Open your terminal, navigate to the project directory, and run the following command to start your API:
    1. go run main.go
  1. Access Your API: Open your web browser or a tool like curl and navigate to http://localhost:8080/. You should see the message "Hello, World!" displayed.
 

Using Fiber

Fiber is a Go web framework built on top of Fasthttp, the fastest HTTP engine for Go, and this is what we use at work.
Install Fiber: In your terminal, navigate to your project directory and run the following command to install Fiber:
go get -u github.com/gofiber/fiber/v2

Step 3: Creating a Fiber API

We'll create a simple API that responds to HTTP requests with a JSON message.
  1. Create a File: Inside your project directory, create a new file named main.go.
  1. Import Necessary Packages: Open main.go and import the required packages:
    1. goCopy code package main import ( "github.com/gofiber/fiber/v2" )
  1. Define a Handler Function: Create a handler function that will respond to HTTP requests. This function will be called whenever an HTTP request is made to your API:
    1. func helloHandler(c *fiber.Ctx) error { return c.JSON(fiber.Map{"message": "Hello, Fiber!"}) }
  1. Set Up Fiber App: In the main function, set up the Fiber app and define routes:
    1. func main() { app := fiber.New() app.Get("/", helloHandler) err := app.Listen(":8080") if err != nil { panic(err) } }

Step 4: Running Your Fiber API

  1. Run the API: Open your terminal, navigate to the project directory, and run the following command to start your Fiber API:
    1. go run main.go
  1. Access Your API: Open your web browser or a tool like curl and navigate to http://localhost:8080/. You should receive a JSON response with the message "Hello, Fiber!".
Fiber's easy-to-use syntax and efficient routing mechanisms make it a strong choice for building APIs. As you explore further, you can expand your API by adding more routes, integrating with databases, and incorporating middleware.
 

A slightly advanced example

Here's another example demonstrating how to create a basic API endpoint using Fiber's context in Go. In this case, we'll create an API to manage user profiles.
package main import ( "fmt" "github.com/gofiber/fiber/v2" ) // User struct to represent a user profile type User struct { ID int `json:"id"` Username string `json:"username"` Email string `json:"email"` } var users []User func main() { app := fiber.New() // Create a new user profile app.Post("/users", CreateUser) // Get all user profiles app.Get("/users", GetUsers) // Get a specific user profile by ID app.Get("/users/:id", GetUserByID) // Start the Fiber app on port 8080 err := app.Listen(":8080") if err != nil { panic(err) } } // CreateUser creates a new user profile func CreateUser(c *fiber.Ctx) error { user := new(User) err := c.BodyParser(user) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ "message": "Invalid JSON format", }) } user.ID = len(users) + 1 users = append(users, *user) return c.Status(fiber.StatusCreated).JSON(user) } // GetUsers retrieves all user profiles func GetUsers(c *fiber.Ctx) error { return c.JSON(users) } // GetUserByID retrieves a specific user profile by ID func GetUserByID(c *fiber.Ctx) error { id := c.Params("id") userID := parseID(id) if userID == -1 || userID > len(users) { return c.Status(fiber.StatusNotFound).JSON(fiber.Map{ "message": "User not found", }) } user := users[userID-1] return c.JSON(user) } // Utility function to parse ID parameter func parseID(id string) int { var userID int _, err := fmt.Sscanf(id, "%d", &userID) if err != nil { return -1 } return userID }
In this example, we're using Fiber to create a basic API for managing user profiles. The API allows you to create new user profiles, retrieve a list of all user profiles, and retrieve a specific user profile by its ID. The User struct represents a user profile, and the users slice stores all created user profiles.
Remember that this is a simplified example, and in a real-world scenario, you'd likely connect this API to a database for persistent storage and implement more sophisticated validation and error handling.