Contents

File Handling and IO

Syntax

Go provides robust and straightforward support for file I/O, JSON manipulation, command-line argument handling, and HTTP requests. These are essential tasks for building applications that interact with files, communicate over networks, and take user input. 

Reading and Writing Files

Go’s os and io/ioutil (deprecated in favor of os and io) packages provide functionalities for file operations.

Reading Files

You can read files using the os package or the bufio package for more control over reading.

Example: Reading a file

				
					package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    file, err := os.Open("example.txt")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        fmt.Println("Error reading file:", err)
    }
}

				
			

Writing Files

You can write to files using the os package.

Example: Writing to a file

				
					package main

import (
    "fmt"
    "os"
)

func main() {
    content := []byte("Hello, Go!\nThis is a new line.\n")

    err := os.WriteFile("example.txt", content, 0644) // Use os.WriteFile for simple write
    if err != nil {
        fmt.Println("Error writing file:", err)
        return
    }

    fmt.Println("File written successfully")
}

				
			

Working with JSON

The encoding/json package provides functions to encode and decode JSON data.

JSON Encoding and Decoding

Example: Encoding data to JSON

				
					package main

import (
    "encoding/json"
    "fmt"
)

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

func main() {
    person := Person{Name: "Alice", Age: 30}
    jsonData, err := json.Marshal(person)
    if err != nil {
        fmt.Println("Error encoding JSON:", err)
        return
    }

    fmt.Println("JSON Data:", string(jsonData))
}

				
			

Example: Decoding JSON data

				
					package main

import (
    "encoding/json"
    "fmt"
)

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

func main() {
    jsonData := `{"name": "Alice", "age": 30}`
    var person Person
    err := json.Unmarshal([]byte(jsonData), &person)
    if err != nil {
        fmt.Println("Error decoding JSON:", err)
        return
    }

    fmt.Printf("Decoded Person: %+v\n", person)
}

				
			

Handling Command Line Arguments

Go’s os package provides the Args slice to access command-line arguments.

Example: Accessing command-line arguments

				
					package main

import (
    "fmt"
    "os"
)

func main() {
    args := os.Args
    if len(args) < 2 {
        fmt.Println("Usage: go run main.go [arguments]")
        return
    }

    for i, arg := range args[1:] {
        fmt.Printf("Argument %d: %s\n", i+1, arg)
    }
}

				
			

HTTP Requests

The net/http package provides comprehensive support for making HTTP requests.

Making HTTP GET Requests

Example: HTTP GET request

				
					package main

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

func main() {
    response, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
    if err != nil {
        fmt.Println("Error making request:", err)
        return
    }
    defer response.Body.Close()

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

    fmt.Println("Response:", string(body))
}

				
			

Making HTTP POST Requests

Example: HTTP POST request

				
					package main

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

func main() {
    jsonData := []byte(`{"title": "foo", "body": "bar", "userId": 1}`)

    response, err := http.Post("https://jsonplaceholder.typicode.com/posts", "application/json", bytes.NewBuffer(jsonData))
    if err != nil {
        fmt.Println("Error making POST request:", err)
        return
    }
    defer response.Body.Close()

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

    fmt.Println("Response:", string(body))
}