TS
GO

TypeScript to Go

10 lessons

Progress0%
1Introduction: Transpiled to Compiled Binary2Type Systems: Structural Interfaces3Functions4Objects to Structs5Generics6Error Handling7Async to Goroutines8Ecosystem9Testing10Go Standard Library
All Mirror Courses
TS
GO
Go Standard Library
MirrorLesson 10 of 10
Lesson 10

Go Standard Library

Go's batteries-included standard library covers HTTP, JSON, strings, and OS operations — replacing most Node.js third-party packages like axios, lodash, and node-fetch.

Introduction

In this lesson, you'll learn about go standard library in Go. Coming from TypeScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.

Mirror Card
TS
From TypeScript:

In TypeScript, you're familiar with go's batteries-included standard library covers http, json, strings, and os operations — replacing most node.js third-party packages like axios, lodash, and node-fetch..

GO
In Go:

Go has its own approach to go's batteries-included standard library covers http, json, strings, and os operations — replacing most node.js third-party packages like axios, lodash, and node-fetch., which we'll explore step by step.

The Go Way

Let's see how Go handles this concept. Here's a typical example:

GO
Go Example
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "os"
    "path/filepath"
    "strings"
    "time"
)

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

func main() {
    // HTTP client — net/http (no axios needed)
    client := &http.Client{Timeout: 5 * time.Second}
    resp, err := client.Get("https://api.example.com/users")
    if err != nil { panic(err) }
    defer resp.Body.Close()

    var users []User
    json.NewDecoder(resp.Body).Decode(&users)
    fmt.Println(users)

    // Strings — strings package
    s := "  hello world  "
    s = strings.TrimSpace(s)
    words := strings.Fields(s)              // split on whitespace
    joined := strings.Join(words, "-")       // "hello-world"
    fmt.Println(strings.ToUpper(joined))     // "HELLO-WORLD"
    fmt.Println(strings.Contains(s, "world")) // true

    // JSON file I/O
    data, _ := os.ReadFile("config.json")
    var cfg map[string]any
    json.Unmarshal(data, &cfg)
    out, _ := json.MarshalIndent(cfg, "", "  ")
    os.WriteFile("out.json", out, 0644)

    // Paths — filepath
    full := filepath.Join("config", "app.json")
    fmt.Println(filepath.Ext(full)) // ".json"
}

Comparing to TypeScript

Here's how you might have written similar code in TypeScript:

TS
TypeScript (What you know)
import axios from "axios";
import { readFileSync } from "fs";
import path from "path";

// HTTP request (needs axios or node-fetch)
const res = await axios.get<User[]>("https://api.example.com/users");
console.log(res.data);

// String manipulation (often lodash)
const words = "  hello world  ".trim().split(/s+/);
const joined = words.join("-");  // "hello-world"

// JSON
const data = JSON.parse(readFileSync("config.json", "utf-8"));
const text = JSON.stringify(data, null, 2);

// Paths
const full = path.join("config", "app.json");
Mirror Card
TS
From TypeScript:

You may be used to different syntax or behavior.

GO
In Go:

Go's net/http is production-ready with no external package; Node.js needs fetch/axios for HTTP clients

Mirror Card
TS
From TypeScript:

You may be used to different syntax or behavior.

GO
In Go:

strings package: Fields (split on whitespace), TrimSpace, Contains, HasPrefix, Join, ToUpper — all in stdlib

Mirror Card
TS
From TypeScript:

You may be used to different syntax or behavior.

GO
In Go:

encoding/json: json.NewDecoder(body).Decode(&v) for streaming; json.Unmarshal([]byte, &v) for in-memory

Mirror Card
TS
From TypeScript:

You may be used to different syntax or behavior.

GO
In Go:

Struct tags (`json:"name"`) control JSON field names during marshal/unmarshal

Mirror Card
TS
From TypeScript:

You may be used to different syntax or behavior.

GO
In Go:

os.ReadFile/WriteFile are the modern (Go 1.16+) single-call file I/O functions

Step-by-Step Breakdown

1. HTTP Client

net/http.Client handles all HTTP operations. Always set a Timeout, always close resp.Body with defer, and check status codes.

TS
TypeScript
const res = await fetch("https://api.example.com/data");
const data = await res.json();
GO
Go
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get("https://api.example.com/data")
if err != nil { return err }
defer resp.Body.Close()
if resp.StatusCode != 200 { return fmt.Errorf("status %d", resp.StatusCode) }
var data MyType
json.NewDecoder(resp.Body).Decode(&data)

2. JSON Encode/Decode

json.Unmarshal decodes a []byte; json.NewDecoder streams from an io.Reader. Struct tags control field names. Use any (interface{}) for dynamic JSON.

TS
TypeScript
JSON.parse(str)
JSON.stringify(obj, null, 2)
GO
Go
// Decode
var cfg Config
json.Unmarshal([]byte(str), &cfg)

// Encode
out, _ := json.MarshalIndent(cfg, "", "  ")
fmt.Println(string(out))

3. String Package

The strings package provides the common string operations that lodash/underscore provide in JS ecosystems — all in stdlib.

TS
TypeScript
str.trim()
str.split(/\s+/)
str.includes("x")
str.startsWith("http")
GO
Go
strings.TrimSpace(s)
strings.Fields(s)          // split on whitespace
strings.Contains(s, "x")
strings.HasPrefix(s, "http")
strings.ReplaceAll(s, "a", "b")
strings.Split(s, ",")

4. HTTP Server

net/http.ServeMux routes requests. Handlers are functions with (ResponseWriter, *Request). No Express needed.

TS
TypeScript
app.get("/hello", (req, res) => res.send("Hello"));
app.listen(8080);
GO
Go
mux := http.NewServeMux()
mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello")
})
http.ListenAndServe(":8080", mux)
Rule of Thumb
Check err from every I/O call. Use defer resp.Body.Close() immediately after a successful GET/POST — forgetting it leaks connections.

Common Mistakes

When coming from TypeScript, developers often make these mistakes:

  • Go's net/http is production-ready with no external package; Node.js needs fetch/axios for HTTP clients
  • strings package: Fields (split on whitespace), TrimSpace, Contains, HasPrefix, Join, ToUpper — all in stdlib
  • encoding/json: json.NewDecoder(body).Decode(&v) for streaming; json.Unmarshal([]byte, &v) for in-memory
Common Pitfall
Don't assume Go works exactly like TypeScript. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • net/http: production-ready HTTP client and server — no axios, no Express needed
  • encoding/json: Unmarshal([]byte) for in-memory, NewDecoder(reader).Decode for streaming
  • strings package replaces lodash string utilities: Fields, TrimSpace, Contains, HasPrefix, Join
  • os.ReadFile/WriteFile for simple file I/O; struct tags `json:"name"` control JSON field names
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your TypeScript code in Go to practice these concepts.
PreviousFinish