JS
GO

JavaScript to Go

10 lessons

Progress0%
1Variables & Types2Functions3Objects → Structs4Async → Goroutines5Errors & Panic6Interfaces7Slices and Maps8Packages and Modules9Testing10Standard Library
All Mirror Courses
JS
GO
Standard Library
MirrorLesson 10 of 10
Lesson 10

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.

Mirror Card
JS
From JavaScript:

In JavaScript, you're familiar with go's rich standard library — fmt, strings, os, json, http.

GO
In Go:

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:

GO
Go 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:

JS
JavaScript (What you know)
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);
Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

GO
In Go:

fmt.Sprintf for string formatting (like JS template literals or util.format)

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

GO
In Go:

strings package has all string operations; strings are immutable value types

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

GO
In Go:

strconv converts between strings and numeric types

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

GO
In Go:

os.ReadFile/WriteFile replace fs.readFileSync/writeFileSync

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

GO
In Go:

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.

JS
JavaScript
console.log(`name=${name} age=${age}`)
GO
Go
fmt.Printf("name=%s age=%d\n", name, age)
result := fmt.Sprintf("x=%d", x)  // to string

2. strings Package

The strings package covers all string operations. Since strings are immutable, all functions return new strings.

JS
JavaScript
s.toUpperCase(); s.split(","); s.includes("x"); s.trim()
GO
Go
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.

JS
JavaScript
JSON.stringify(obj); JSON.parse(text)
GO
Go
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.

JS
JavaScript
const app = express();
app.get("/", (req,res) => res.send("Hi"));
app.listen(8080);
GO
Go
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hi")
})
log.Fatal(http.ListenAndServe(":8080", nil))
Rule of Thumb
For simple APIs, use net/http directly. For routing needs, chi or gorilla/mux are lightweight additions.

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
Common Pitfall
Don't assume Go works exactly like JavaScript. While the concepts may be similar, the syntax and behavior can differ significantly.

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
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your JavaScript code in Go to practice these concepts.
PreviousFinish