GoLang

Introduction

Golang, commonly known as Go, is a modern, statically typed programming language developed by Google. It is designed for efficiency, concurrency, and scalability, making it an excellent choice for backend development, cloud computing, and microservices.

Why Use Golang?

  • High Performance – Faster execution than interpreted languages like Python.

  • Simple & Readable Syntax – Easy to learn, like Python but with better performance.

  • Built-in Concurrency – Goroutines for efficient multi-threading.

  • Garbage Collection – Automatic memory management.

  • Static Typing – Prevents runtime errors.

  • Great for Microservices – Lightweight and scalable.

  • Cross-Platform – Works on Windows, macOS, Linux, and more.

Installing Golang

1️⃣ Install Go on Your System

Windows/macOS/Linux

📌 Download from: https://go.dev/dl/

Check Installation:

go version

Output: go version go1.xx.x (your OS)

2️⃣ Writing Your First Go Program

Create a new file main.go and add:

package main

import "fmt"

func main() {
    fmt.Println("Hello, Golang! 🚀")
}

Run the program:

go run main.go

Output: "Hello, Golang! 🚀"

3️⃣ Go Project Structure

Typical Go project:

myproject/
│── main.go         # Main file
│── go.mod         # Module definition
│── handlers/      # Business logic
│── models/        # Data models
│── routes/        # API routes

Initialize a Go Module:

go mod init myproject

This will create a go.mod file to manage dependencies.

GoLang Backend Architecture:

Web Development with Golang

1️⃣ Setting Up a Simple Web Server

Install net/http Package

package main
import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Welcome to Go Web Server!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Run:

go run main.go

Visit: http://localhost:8080 Output: "Welcome to Go Web Server!"

2️⃣ Using Fiber (Fast Web Framework)

Install Fiber:

go get -u github.com/gofiber/fiber/v2

Create a Fiber Web Server

package main
import "github.com/gofiber/fiber/v2"

func main() {
    app := fiber.New()
    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello from Fiber!")
    })
    app.Listen(":8080")
}

Visit: http://localhost:8080

3️⃣ Database Connection (PostgreSQL with GORM)

Install GORM & PostgreSQL Driver

go get -u gorm.io/gorm
go get -u gorm.io/driver/postgres

Connect to Database:

package main
import (
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
    "fmt"
)

var DB *gorm.DB

func ConnectDatabase() {
    dsn := "host=localhost user=postgres password=mypassword dbname=mydb port=5432 sslmode=disable"
    database, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("Failed to connect to database!")
    }
    DB = database
    fmt.Println("Database connected successfully!")
}

Run: go run main.go to check connection.

Golang for Microservices

1️⃣ Why Use Go for Microservices?

  • Lightweight & Fast – Minimal overhead.

  • Concurrency Support – Handles multiple requests efficiently.

  • Scalable – Ideal for cloud-native applications.

2️⃣ Example of a REST API in Go

Using Fiber & GORM

package main
import (
    "github.com/gofiber/fiber/v2"
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type User struct {
    ID   uint   `json:"id"`
    Name string `json:"name"`
}

var db *gorm.DB

func main() {
    app := fiber.New()
    db, _ = gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
    db.AutoMigrate(&User{})

    app.Get("/users", func(c *fiber.Ctx) error {
        var users []User
        db.Find(&users)
        return c.JSON(users)
    })

    app.Listen(":8080")
}

Run: go run main.go Visit: http://localhost:8080/users

Conclusion

Golang is a powerful, fast, and scalable language for backend development, cloud computing, and microservices. Whether you're building APIs, web servers, or microservices, Go provides simplicity, efficiency, and concurrency like no other.

Last updated

Was this helpful?