Golang Code Snippets

This collection of code snippets provides practical examples for common tasks in Go. These snippets are designed to be concise, reusable, and demonstrate best practices. Always handle errors appropriately in production code.

File System Operations

Get Current Working Directory

package main

import (
    "log"
    "syscall"
)

func main() {
    cwd, err := syscall.Getwd()
    if err != nil {
        log.Fatal("Error getting current working directory:", err)
    }
    log.Println("Working directory:", cwd)
}

Explanation: Uses syscall.Getwd() to retrieve the current working directory. Note that os.Getwd() is a more idiomatic alternative in Go.

Network Operations

Get IP Addresses of a Domain

package main

import (
    "fmt"
    "net"
)

func main() {
    addrs, err := net.LookupIP("example.com")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    for _, addr := range addrs {
        fmt.Println("IP:", addr)
    }
}

Explanation: net.LookupIP() performs a DNS lookup and returns a slice of IP addresses for the given domain.

Time and Date Handling

Format Current Time

package main

import (
    "fmt"
    "time"
)

func main() {
    today := time.Now().Format("01-02-2006")
    fmt.Println("Today's date:", today)
}

Explanation: Uses Go’s reference time format “01-02-2006” to format the current date. Adjust the layout string for different formats.

Database Operations

Access Data from a MongoDB Cursor

package main

import (
    "context"
    "fmt"
    "log"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
)

func main() {
    // Assuming 'coll' is a *mongo.Collection
    cursor, err := coll.Find(context.TODO(), bson.D{})
    if err != nil {
        panic(err)
    }
    defer cursor.Close(context.TODO())

    for cursor.Next(context.TODO()) {
        var result bson.D
        if err := cursor.Decode(&result); err != nil {
            log.Fatal(err)
        }
        fmt.Println(result)
    }
    if err := cursor.Err(); err != nil {
        log.Fatal(err)
    }
}

Explanation: Iterates over a MongoDB cursor, decoding each document into a bson.D struct. Always close the cursor and check for errors.

Additional Useful Snippets

HTTP GET Request

package main

import (
    "fmt"
    "io"
    "net/http"
)

func main() {
    resp, err := http.Get("https://api.example.com/data")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer resp.Body.Close()

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Error reading body:", err)
        return
    }
    fmt.Println(string(body))
}

JSON Encoding and Decoding

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    // Encoding
    p := Person{Name: "Alice", Age: 30}
    jsonData, _ := json.Marshal(p)
    fmt.Println(string(jsonData))

    // Decoding
    var p2 Person
    json.Unmarshal(jsonData, &p2)
    fmt.Println(p2)
}

Goroutine with Channel

package main

import (
    "fmt"
    "time"
)

func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        fmt.Println("Worker", id, "processing job", j)
        time.Sleep(time.Second)
        results <- j * 2
    }
}

func main() {
    jobs := make(chan int, 100)
    results := make(chan int, 100)

    for w := 1; w <= 3; w++ {
        go worker(w, jobs, results)
    }

    for j := 1; j <= 5; j++ {
        jobs <- j
    }
    close(jobs)

    for a := 1; a <= 5; a++ {
        <-results
    }
}

Conclusion

These snippets cover a range of common Go programming tasks. For more advanced usage, refer to the official Go documentation and libraries. Remember to write tests and handle errors gracefully in your applications.

Resources