Copy docker run --rm zchencow/innozverse-go:latest go run - << 'EOF'
package main
import (
"bufio"
"encoding/csv"
"encoding/json"
"fmt"
"io/fs"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
// Step 4: Custom JSON marshaler
type Money struct{ Cents int64; Currency string }
func (m Money) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]any{
"amount": fmt.Sprintf("%.2f", float64(m.Cents)/100),
"currency": m.Currency,
})
}
func (m *Money) UnmarshalJSON(data []byte) error {
var raw struct{ Amount string; Currency string }
if err := json.Unmarshal(data, &raw); err != nil { return err }
f, err := strconv.ParseFloat(raw.Amount, 64)
if err != nil { return err }
m.Cents = int64(f * 100)
m.Currency = raw.Currency
return nil
}
// Step 5: CSV handling
type SaleRecord struct {
Date string
Product string
Quantity int
Price float64
Total float64
}
func writeCSV(path string, records []SaleRecord) error {
f, err := os.Create(path)
if err != nil { return err }
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
w.Write([]string{"Date", "Product", "Quantity", "Price", "Total"})
for _, r := range records {
w.Write([]string{
r.Date, r.Product,
strconv.Itoa(r.Quantity),
fmt.Sprintf("%.2f", r.Price),
fmt.Sprintf("%.2f", r.Total),
})
}
return w.Error()
}
func readCSV(path string) ([]SaleRecord, error) {
f, err := os.Open(path)
if err != nil { return nil, err }
defer f.Close()
r := csv.NewReader(f)
rows, err := r.ReadAll()
if err != nil { return nil, err }
records := make([]SaleRecord, 0, len(rows)-1)
for _, row := range rows[1:] { // skip header
qty, _ := strconv.Atoi(row[2])
price, _ := strconv.ParseFloat(row[3], 64)
total, _ := strconv.ParseFloat(row[4], 64)
records = append(records, SaleRecord{row[0], row[1], qty, price, total})
}
return records, nil
}
// Step 6: Config file (JSON-based)
type AppConfig struct {
Name string `json:"name"`
Version string `json:"version"`
Debug bool `json:"debug"`
Port int `json:"port"`
DB DBConfig `json:"database"`
Features map[string]bool `json:"features"`
}
type DBConfig struct {
Driver string `json:"driver"`
Host string `json:"host"`
Port int `json:"port"`
Database string `json:"database"`
}
func loadConfig(path string) (*AppConfig, error) {
data, err := os.ReadFile(path)
if err != nil { return nil, fmt.Errorf("read config: %w", err) }
var cfg AppConfig
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("parse config: %w", err)
}
return &cfg, nil
}
// Step 7: Directory walker
type FileStats struct {
TotalFiles int
TotalSize int64
ByExt map[string]int
}
func walkDir(root string) (*FileStats, error) {
stats := &FileStats{ByExt: make(map[string]int)}
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil { return err }
if d.IsDir() { return nil }
info, _ := d.Info()
stats.TotalFiles++
stats.TotalSize += info.Size()
ext := strings.ToLower(filepath.Ext(path))
if ext == "" { ext = "(no ext)" }
stats.ByExt[ext]++
return nil
})
return stats, err
}
// Step 8: Capstone — data pipeline
func main() {
dir, _ := os.MkdirTemp("", "golab-")
defer os.RemoveAll(dir)
// Custom marshaler
price := Money{86400, "USD"}
data, _ := json.Marshal(price)
fmt.Println("Money JSON:", string(data))
// CSV write + read
csvPath := filepath.Join(dir, "sales.csv")
sales := []SaleRecord{
{"2026-03-01", "Surface Pro", 2, 864.00, 1728.00},
{"2026-03-02", "Surface Pen", 5, 49.99, 249.95},
{"2026-03-03", "Office 365", 10, 99.99, 999.90},
}
writeCSV(csvPath, sales)
loaded, _ := readCSV(csvPath)
fmt.Printf("\nCSV: loaded %d records\n", len(loaded))
totalRevenue := 0.0
for _, r := range loaded {
fmt.Printf(" %s: %dx%s = $%.2f\n", r.Date, r.Quantity, r.Product, r.Total)
totalRevenue += r.Total
}
fmt.Printf("Total revenue: $%.2f\n", totalRevenue)
// Config file
configPath := filepath.Join(dir, "config.json")
cfg := AppConfig{
Name: "innoZverse", Version: "1.0.0", Debug: true, Port: 8080,
DB: DBConfig{"sqlite", "localhost", 5432, "innozverse"},
Features: map[string]bool{"auth": true, "api": true, "beta": false},
}
cfgData, _ := json.MarshalIndent(cfg, "", " ")
os.WriteFile(configPath, cfgData, 0644)
loaded2, _ := loadConfig(configPath)
fmt.Printf("\nConfig: %s v%s port=%d\n", loaded2.Name, loaded2.Version, loaded2.Port)
fmt.Println("DB:", loaded2.DB.Driver, loaded2.DB.Database)
for k, v := range loaded2.Features {
fmt.Printf(" feature.%s = %v\n", k, v)
}
// Generate some files for walker
for _, name := range []string{"a.json", "b.json", "c.txt", "d.csv"} {
os.WriteFile(filepath.Join(dir, name), []byte("test content"), 0644)
}
stats, _ := walkDir(dir)
fmt.Printf("\nWalked %s: %d files, %d bytes\n", dir, stats.TotalFiles, stats.TotalSize)
for ext, count := range stats.ByExt {
fmt.Printf(" %s: %d file(s)\n", ext, count)
}
// Buffered log writer
logPath := filepath.Join(dir, "app.log")
lf, _ := os.Create(logPath)
lw := bufio.NewWriter(lf)
for i := 0; i < 5; i++ {
fmt.Fprintf(lw, "[%s] Event %d processed\n", time.Now().Format("15:04:05"), i+1)
}
lw.Flush()
lf.Close()
logData, _ := os.ReadFile(logPath)
lines := strings.Split(strings.TrimSpace(string(logData)), "\n")
fmt.Printf("\nLog file: %d entries\n", len(lines))
fmt.Println("Last:", lines[len(lines)-1])
}
EOF