What You Will Learn
By the end of this chapter, you will know how to:
- Read and write files using the
osandiopackages - Use buffered I/O for performance
- Marshal and unmarshal JSON
- Work with encoding formats: JSON, XML, and CSV
- Make HTTP requests with
net/http - Access environment variables and interact with the OS
This chapter prepares you to handle real-world data processing.
10.1 Reading and Writing Files
Go provides the os package for filesystem access.
a. Write to a File
package main
import (
"os"
)
func main() {
content := []byte("Hello, Go file!")
err := os.WriteFile("example.txt", content, 0644)
if err != nil {
panic(err)
}
}b. Read a File
data, err := os.ReadFile("example.txt")
if err != nil {
panic(err)
}
fmt.Println(string(data))c. Writing with Append Mode
f, err := os.OpenFile("example.txt", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer f.Close()
f.WriteString("\nAppending text!")10.2 Buffered I/O (io & bufio)
Buffered I/O improves performance by reducing system calls.
a. Writing Buffered Output
f, _ := os.Create("buffer.txt")
w := bufio.NewWriter(f)
w.WriteString("Buffered write example!")
w.Flush()b. Reading Buffered Input
file, _ := os.Open("buffer.txt")
r := bufio.NewReader(file)
line, _ := r.ReadString('\n')
fmt.Println(line)10.3 Working With JSON
Go uses encoding/json.
a. Struct → JSON (Marshalling)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
user := User{"Alice", 30}
jsonData, _ := json.MarshalIndent(user, "", " ")
fmt.Println(string(jsonData))b. JSON → Struct (Unmarshalling)
var u User
json.Unmarshal(jsonData, &u)
fmt.Println(u.Name, u.Age)10.4 Encoding Formats: JSON, XML, CSV
✔ XML
type Person struct {
XMLName xml.Name `xml:"person"`
Name string `xml:"name"`
Age int `xml:"age"`
}
p := Person{"John", 25}
out, _ := xml.MarshalIndent(p, "", " ")
fmt.Println(string(out))✔ CSV
file, _ := os.Create("data.csv")
writer := csv.NewWriter(file)
writer.Write([]string{"Name", "Age"})
writer.Write([]string{"Alice", "30"})
writer.Flush()Read CSV:
file, _ := os.Open("data.csv")
reader := csv.NewReader(file)
records, _ := reader.ReadAll()
fmt.Println(records)10.5 HTTP Requests (net/http)
a. GET Request
resp, _ := http.Get("https://api.github.com")
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))b. POST Request (JSON)
payload := strings.NewReader(`{"name":"test"}`)
resp, _ := http.Post("https://httpbin.org/post", "application/json", payload)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))10.6 Environment Variables & OS Package
a. Get Environment Variable
value := os.Getenv("HOME")
fmt.Println("Home directory:", value)b. Set an Environment Variable (Temporary)
os.Setenv("APP_ENV", "production")
fmt.Println(os.Getenv("APP_ENV"))c. Listing System Files
entries, _ := os.ReadDir(".")
for _, e := range entries {
fmt.Println(e.Name())
}Summary of Chapter 10
You now understand how to:
✔ Read & write files with os and io
✔ Use buffered I/O to improve performance
✔ Encode and decode JSON, XML, and CSV
✔ Make HTTP requests and consume APIs
✔ Read environment variables and interact with the operating system