# 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?**

* H**igh 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:**

```bash
go version

```

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

### **2️⃣ Writing Your First Go Program**

Create a new file **`main.go`** and add:

```go
package main

import "fmt"

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

```

Run the program:

```bash
go run main.go

```

**Output:** `"Hello, Golang! 🚀"`

### **3️⃣ Go Project Structure**

Typical Go project:

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

```

Initialize a Go Module:

```bash
go mod init myproject

```

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

### GoLang Backend Architecture:

<figure><img src="/files/bSQzDe3tomk45C9os7l3" alt=""><figcaption></figcaption></figure>

## **Web Development with Golang**

### **1️⃣ Setting Up a Simple Web Server**

&#x20;**Install `net/http` Package**

```go
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:

```bash
go run main.go

```

**Visit:** \*\*[http://localhost:8080\*\*\\](https://www.anandisheladiya.com/skills-and-experience/backend/http:/localhost:8080**\\)
**Output:** `"Welcome to Go Web Server!"`

### **2️⃣ Using Fiber (Fast Web Framework)**

**Install Fiber:**

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

```

Create a Fiber Web Server

```go
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**

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

```

Connect to Database:

```go
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**

```go
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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.anandisheladiya.com/skills-and-experience/backend/golang.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
