Track F · Tutorial 1

Go Fundamentals & REST APIs

Chapter 29 · Backend Specialization
~3 hours Intermediate Go · HTTP · REST · GORM

Overview

Go (Golang) is a statically typed, compiled language designed for high‑performance backend systems. This tutorial covers project setup, building HTTP servers with the standard library, implementing REST APIs, and integrating with databases using GORM.

Why this matters: Go powers some of the world's most demanding applications (Docker, Kubernetes, etc.). Its simplicity, concurrency model, and performance make it an excellent choice for modern backend development.

1. Introduction to Go

Key features of Go:

  • Simplicity: Minimal syntax, easy to learn and read.
  • Concurrency: Goroutines and channels for concurrent programming.
  • Fast compilation: Compiles to a single binary.
  • Garbage collection: Automatic memory management.
  • Standard library: Rich standard library with excellent HTTP support.
// Hello World in Go package main import "fmt" func main() { fmt.Println("Hello, World!") }

2. Setting Up a Go Project

Installation

Download Go from golang.org.

Project Setup

mkdir my-api cd my-api go mod init my-api go get -u github.com/gin-gonic/gin

Using Gin (popular web framework) or the standard library:

// main.go using Gin package main import "github.com/gin-gonic/gin" func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{"message": "pong"}) }) r.Run() }

3. HTTP Servers with Standard Library

Go's standard library has excellent HTTP support.

// main.go with standard library package main import ( "encoding/json" "net/http" ) type Product struct { ID int `json:"id"` Name string `json:"name"` Price float64 `json:"price"` } func getProducts(w http.ResponseWriter, r *http.Request) { products := []Product{ {ID: 1, Name: "Laptop", Price: 999.99}, } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(products) } func main() { http.HandleFunc("/api/products", getProducts) http.ListenAndServe(":8080", nil) }

4. Routing & Handlers

Gin provides expressive routing with parameter extraction.

// Product handler with Gin func main() { r := gin.Default() r.GET("/api/products", getProducts) r.GET("/api/products/:id", getProduct) r.POST("/api/products", createProduct) r.PUT("/api/products/:id", updateProduct) r.DELETE("/api/products/:id", deleteProduct) r.Run(":8080") } func getProduct(c *gin.Context) { id := c.Param("id") c.JSON(200, Product{ID: 1, Name: "Laptop"}) } func createProduct(c *gin.Context) { var product Product c.BindJSON(&product) c.JSON(201, product) }

5. Database Access with GORM

GORM is the most popular ORM for Go.

go get -u gorm.io/gorm go get -u gorm.io/driver/sqlite
// product.go package main import ( "gorm.io/gorm" "gorm.io/driver/sqlite" ) type Product struct { ID uint `gorm:"primaryKey"` Name string `json:"name"` Price float64 `json:"price"` } func initDB() *gorm.DB { db, err := gorm.Open(sqlite.Open("products.db"), &gorm.Config{}) if err != nil { panic("Failed to connect to database") } db.AutoMigrate(&Product{}) return db } // Using in handlers func getProducts(c *gin.Context) { db := initDB() var products []Product db.Find(&products) c.JSON(200, products) }
Tip: For production, use environment variables for database connection strings and consider connection pooling.

Quiz

Question 1

Which command initialises a Go module?

  • go init
  • go mod init
  • go create
  • go new
Show answer
B. go mod init.

Question 2

Which package is the most popular web framework in Go?

  • http
  • gin
  • echo
  • fiber
Show answer
B. gin (though all are valid, Gin is the most popular).

Question 3

Which ORM is most commonly used in Go?

  • GORM
  • Sequelize
  • Hibernate
  • TypeORM
Show answer
A. GORM.

Exercises

Exercise 1

Create a User struct with ID, Name, Email. Write a handler that returns a list of users.

Sample answer
type User struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email"` } func getUsers(c *gin.Context) { users := []User{ {ID: 1, Name: "Alice", Email: "alice@ex.com"}, } c.JSON(200, users) }

Exercise 2

Add a POST /api/users endpoint that accepts JSON and returns the created user.

Sample answer
func createUser(c *gin.Context) { var user User if err := c.BindJSON(&user); err != nil { c.JSON(400, gin.H{"error": err.Error()}) return } user.ID = 2 // Simulate saving c.JSON(201, user) }

Homework

Homework 1

Build a complete CRUD API for a Todo resource with fields: ID, Title, Completed. Use GORM and Gin.

Sample outline
  • Model: Todo (ID, Title, Completed)
  • Handlers: GET /api/todos, GET /api/todos/:id, POST /api/todos, PUT /api/todos/:id, DELETE /api/todos/:id
  • Database: SQLite or PostgreSQL with GORM
  • Main: Setup routes, connect to DB, run server

Mini‑Project

Task Manager API

Build a Task Manager API with Go and Gin:

  • Task: ID, Title, Description, Status (pending/in progress/done), CreatedAt
  • CRUD endpoints
  • Filter by status: GET /api/tasks?status=pending
  • Use GORM with SQLite
  • Add validation for required fields
Sample implementation outline
  • Model: Task struct with gorm tags
  • Repository: Functions for CRUD operations
  • Handlers: Gin handlers with error handling
  • Query params: c.Query("status") for filtering
  • Validation: Check required fields before saving

Test using curl or Postman.

Tutorial Summary

You learned the fundamentals of Go backend development: project setup, building HTTP servers with the standard library and Gin, implementing REST APIs with routing and handlers, and integrating with databases using GORM. You built a solid foundation for high‑performance backend development in Go.

Key takeaway: Go's simplicity, performance, and excellent concurrency model make it a compelling choice for modern backend systems. Its standard library provides everything you need to build production‑ready APIs.