Practical Code Examples
File Handling with os Package
package main
import (
"fmt"
"os"
"log"
)
func main() {
// Create a new file
file, err := os.Create("/tmp/example.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Write data to file
file.WriteString("Hello, LabEx!")
}
Network Programming with net Package
package main
import (
"fmt"
"net"
"time"
)
func main() {
listener, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("Error listening:", err)
return
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
continue
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
// Connection handling logic
}
Concurrency with sync Package
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
fmt.Println("All workers completed")
}
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d done\n", id)
}
JSON Processing with encoding/json Package
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
}
func main() {
// Marshaling (Go struct to JSON)
user := User{
Name: "John Doe",
Age: 30,
Email: "[email protected]",
}
jsonData, err := json.Marshal(user)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(jsonData))
// Unmarshaling (JSON to Go struct)
var newUser User
jsonStr := `{"name":"Jane Doe","age":25,"email":"[email protected]"}`
err = json.Unmarshal([]byte(jsonStr), &newUser)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("%+v\n", newUser)
}
Error Handling with errors Package
package main
import (
"errors"
"fmt"
)
func divideNumbers(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
result, err := divideNumbers(10, 0)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
}
Package Usage Workflow
graph TD
A[Import Packages] --> B[Initialize Variables]
B --> C[Perform Operations]
C --> D[Handle Errors]
D --> E[Process Results]
Standard Library Package Categories
Category |
Key Packages |
Primary Use |
Data Handling |
encoding/json, encoding/xml |
Data serialization |
Networking |
net, http |
Network communication |
Concurrency |
sync, context |
Parallel processing |
File I/O |
os, io |
File system operations |
Cryptography |
crypto/* |
Security operations |
Best Practices
- Always handle potential errors
- Use defer for resource cleanup
- Leverage goroutines for concurrent operations
- Choose appropriate packages for specific tasks
Exploring with LabEx
LabEx provides an interactive platform to experiment with these standard library packages, allowing developers to practice and understand their usage in real-world scenarios.
Conclusion
Mastering Golang's standard library packages is crucial for writing efficient, robust, and maintainable code. These practical examples demonstrate the versatility and power of Go's built-in packages.