Standard Library
Go stdlib vs Python's batteries included — strings, os, json, http
Introduction
In this lesson, you'll learn about standard library in Go. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, you're familiar with go stdlib vs python's batteries included — strings, os, json, http.
Go has its own approach to go stdlib vs python's batteries included — strings, os, json, http, which we'll explore step by step.
The Go Way
Let's see how Go handles this concept. Here's a typical example:
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"regexp"
"strings"
"time"
)
func main() {
// strings package
strings.Split("hello world", " ") // ["hello","world"]
strings.Join([]string{"a","b"}, ",") // "a,b"
strings.TrimSpace(" hi ") // "hi"
strings.ToUpper("hello") // "HELLO"
// os package
os.Getenv("HOME")
os.ReadFile("file.txt") // []byte, error
os.WriteFile("out.txt", data, 0644)
// JSON
type Config struct {
Key string `json:"key"`
Val int `json:"val"`
}
var cfg Config
json.Unmarshal([]byte(`{"key":"x","val":1}`), &cfg)
out, _ := json.MarshalIndent(cfg, "", " ")
// HTTP client
resp, err := http.Get("https://example.com")
if err != nil { panic(err) }
defer resp.Body.Close()
// io.ReadAll(resp.Body)
// Regex
re := regexp.MustCompile(`\d+`)
re.FindString("abc123") // "123"
re.FindAllString("1a2b3c", -1) // ["1","2","3"]
// Time
now := time.Now()
now.Format("2006-01-02") // "YYYY-MM-DD" in Go's reference time!
time.Since(start)
}Comparing to Python
Here's how you might have written similar code in Python:
import os
import json
import re
import datetime
from pathlib import Path
from urllib.request import urlopen
# String ops
"hello world".split() # ["hello","world"]
",".join(["a","b","c"]) # "a,b,c"
" hi ".strip() # "hi"
# OS/file
os.getenv("HOME")
os.path.join("dir", "file.txt")
Path("dir/file.txt").read_text()
# JSON
data = json.loads('{"k":1}')
json.dumps(data, indent=2)
# HTTP
with urlopen("http://example.com") as r:
html = r.read().decode()
# Regex
import re
m = re.search(r"\d+", "abc123")
m.group() # "123"
# Date
from datetime import datetime
now = datetime.now()
now.strftime("%Y-%m-%d")You may be used to different syntax or behavior.
Go time format uses reference time '2006-01-02 15:04:05' — not strftime codes
You may be used to different syntax or behavior.
regexp.MustCompile panics on bad patterns — use Compile for safe compile
You may be used to different syntax or behavior.
http.Get is in stdlib — no requests package needed for basic HTTP
You may be used to different syntax or behavior.
JSON uses struct tags json:"name" for field mapping
You may be used to different syntax or behavior.
os.ReadFile/WriteFile replace Python's open() for simple cases
Step-by-Step Breakdown
1. strings Package
All string operations are in the 'strings' package. Since Go strings are immutable, all functions return new strings.
"a,b,c".split(",")
",".join(["a","b"])strings.Split("a,b,c", ",")
strings.Join([]string{"a","b"}, ",")2. Time Formatting
Go uses a reference time (Jan 2, 2006 = 01/02/06) instead of strftime codes. Memorize: 2006-01-02 15:04:05.
datetime.now().strftime("%Y-%m-%d")time.Now().Format("2006-01-02") // YYYY-MM-DD
time.Now().Format("15:04:05") // HH:MM:SS
time.Now().Format(time.RFC3339) // ISO 86013. HTTP Client
net/http includes a full HTTP client. For production use, set a timeout on the client.
import requests
resp = requests.get(url)
resp.json()client := &http.Client{Timeout: 10*time.Second}
resp, err := client.Get(url)
defer resp.Body.Close()
var result MyType
json.NewDecoder(resp.Body).Decode(&result)4. JSON with Struct Tags
Go's encoding/json uses struct field tags to map JSON keys to struct fields. Unexported fields are ignored.
data = json.loads(text) # dict, no schema
print(data["name"])type User struct {
Name string `json:"name"`
Age int `json:"age,omitempty"`
}
var u User
json.Unmarshal([]byte(text), &u)
fmt.Println(u.Name)Common Mistakes
When coming from Python, developers often make these mistakes:
- Go time format uses reference time '2006-01-02 15:04:05' — not strftime codes
- regexp.MustCompile panics on bad patterns — use Compile for safe compile
- http.Get is in stdlib — no requests package needed for basic HTTP
Key Takeaways
- strings: Split, Join, ToUpper, TrimSpace, Contains, Replace — all return new strings
- Go time format uses reference time: 2006-01-02 15:04:05 (not strftime codes)
- net/http client is production-ready stdlib; set Timeout on the client
- JSON uses struct tags json:"name" for mapping; Unmarshal into typed structs