Standard Library
Go's rich standard library — fmt, strings, os, json, http
Introduction
In this lesson, you'll learn about standard library in Go. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with go's rich standard library — fmt, strings, os, json, http.
Go has its own approach to go's rich standard library — fmt, 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"
"strings"
"strconv"
)
func main() {
// fmt — formatted I/O
fmt.Println("hello")
fmt.Printf("name=%s age=%d\n", "Alice", 30)
s := fmt.Sprintf("value=%d", 42)
// strings — string operations
strings.ToUpper("hello") // "HELLO"
strings.Split("a,b,c", ",") // ["a","b","c"]
strings.TrimSpace(" hi ") // "hi"
strings.Contains("hello", "ell") // true
strings.Join([]string{"a","b"},"-") // "a-b"
strings.ReplaceAll("aaa","a","b") // "bbb"
// strconv — type conversions
n, _ := strconv.Atoi("42") // string → int
strconv.Itoa(42) // int → string
strconv.ParseFloat("3.14", 64) // string → float64
// os — file system
data, _ := os.ReadFile("data.txt")
os.WriteFile("out.txt", []byte("hi"), 0644)
os.Getenv("HOME")
os.Args // command-line args
// JSON
type Person struct { Name string; Age int }
p := Person{"Alice", 30}
b, _ := json.Marshal(p)
var p2 Person
json.Unmarshal(b, &p2)
// HTTP server
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello!")
})
http.ListenAndServe(":8080", nil)
}Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
import { readFileSync, writeFileSync } from "fs";
import { join } from "path";
import http from "http";
// String ops (built-in)
"hello".toUpperCase(); // "HELLO"
"hello world".split(" "); // ["hello","world"]
" hi ".trim(); // "hi"
// JSON
JSON.stringify({ a: 1 });
JSON.parse('{"a":1}');
// HTTP server
const server = http.createServer((req, res) => {
res.writeHead(200, {"Content-Type":"text/plain"});
res.end("Hello");
});
server.listen(8080);You may be used to different syntax or behavior.
fmt.Sprintf for string formatting (like JS template literals or util.format)
You may be used to different syntax or behavior.
strings package has all string operations; strings are immutable value types
You may be used to different syntax or behavior.
strconv converts between strings and numeric types
You may be used to different syntax or behavior.
os.ReadFile/WriteFile replace fs.readFileSync/writeFileSync
You may be used to different syntax or behavior.
net/http is a production-ready HTTP package in stdlib — no express needed
Step-by-Step Breakdown
1. fmt Package
fmt handles formatted I/O. Printf verbs: %s string, %d int, %f float, %v any value, %T type, %q quoted string.
console.log(`name=${name} age=${age}`)fmt.Printf("name=%s age=%d\n", name, age)
result := fmt.Sprintf("x=%d", x) // to string2. strings Package
The strings package covers all string operations. Since strings are immutable, all functions return new strings.
s.toUpperCase(); s.split(","); s.includes("x"); s.trim()strings.ToUpper(s)
strings.Split(s, ",")
strings.Contains(s, "x")
strings.TrimSpace(s)3. JSON Marshaling
json.Marshal/Unmarshal convert structs to/from JSON. Use struct tags to control field names.
JSON.stringify(obj); JSON.parse(text)type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
b, _ := json.Marshal(User{"Alice",30}) // []byte
var u User
json.Unmarshal(b, &u)4. net/http Server
Go's net/http package is production-grade. No third-party framework needed for basic services — just HandleFunc and ListenAndServe.
const app = express();
app.get("/", (req,res) => res.send("Hi"));
app.listen(8080);http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hi")
})
log.Fatal(http.ListenAndServe(":8080", nil))Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- fmt.Sprintf for string formatting (like JS template literals or util.format)
- strings package has all string operations; strings are immutable value types
- strconv converts between strings and numeric types
Key Takeaways
- fmt.Printf/Sprintf for formatted output; %s %d %f %v are the common verbs
- strings package: ToUpper, Split, Contains, TrimSpace, Join, ReplaceAll
- strconv: Atoi (str→int), Itoa (int→str), ParseFloat for type conversions
- net/http is stdlib — HandleFunc + ListenAndServe covers most HTTP needs