JV
GO

Java to Go

10 lessons

Progress0%
1Variables & Types2Classes → Structs3Interfaces4Exception Handling → Error Values5Threads → Goroutines6Slices and Collections7Packages and Modules8Testing9Go Standard Library10Context and Cancellation
All Mirror Courses
JV
GO
Go Standard Library
MirrorLesson 9 of 10
Lesson 9

Go Standard Library

Go's standard library covers HTTP, JSON, strings, and OS operations without third-party dependencies — replacing most Java Apache Commons, Guava, and Jackson packages.

Introduction

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

Mirror Card
JV
From Java:

In Java, you're familiar with go's standard library covers http, json, strings, and os operations without third-party dependencies — replacing most java apache commons, guava, and jackson packages..

GO
In Go:

Go has its own approach to go's standard library covers http, json, strings, and os operations without third-party dependencies — replacing most java apache commons, guava, and jackson packages., 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"
    "time"
)

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

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

    // JSON — encoding/json
    var users []User
    if err := json.NewDecoder(resp.Body).Decode(&users); err != nil {
        panic(err)
    }
    fmt.Println(users)

    // String utilities — strings package (replaces Apache Commons)
    parts := []string{"a", "b", "c"}
    joined := strings.Join(parts, "-")          // "a-b-c"
    blank := strings.TrimSpace("  ") == ""      // true
    has := strings.Contains("hello", "ell")     // true
    fmt.Println(joined, blank, has)

    // File I/O — os package
    content, err := os.ReadFile("data.txt")
    if err != nil { panic(err) }
    os.WriteFile("out.txt", content, 0644)
}

Comparing to Java

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

JV
Java (What you know)
import java.net.http.*;
import java.net.URI;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import java.nio.file.*;

public class Stdlib {
    public static void main(String[] args) throws Exception {
        // HTTP client (Java 11+)
        var client = HttpClient.newHttpClient();
        var req = HttpRequest.newBuilder()
            .uri(URI.create("https://api.example.com/users"))
            .build();
        var resp = client.send(req, HttpResponse.BodyHandlers.ofString());

        // JSON (Jackson)
        var mapper = new ObjectMapper();
        var users = mapper.readValue(resp.body(), User[].class);

        // String utils (Apache Commons)
        String joined = StringUtils.join(new String[]{"a","b","c"}, "-");
        boolean blank = StringUtils.isBlank("  ");

        // File I/O (NIO)
        String content = Files.readString(Path.of("data.txt"));
        Files.writeString(Path.of("out.txt"), content);
    }
}
Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

GO
In Go:

Go's net/http is production-ready; Java's HttpClient (11+) is similar but needs more boilerplate

Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

GO
In Go:

encoding/json uses struct tags (`json:"name"`) like Jackson @JsonProperty — no ObjectMapper setup required

Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

GO
In Go:

strings package replaces Apache Commons StringUtils: Contains, HasPrefix, Fields, TrimSpace, Join, ReplaceAll

Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

GO
In Go:

os.ReadFile/WriteFile (Go 1.16+) replace Java's Files.readString/writeString — simpler API

Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

GO
In Go:

Go has no Guava, no Apache Commons — stdlib covers ~90% of utility needs; fewer dependencies means fewer vulnerabilities

Step-by-Step Breakdown

1. HTTP Client

net/http.Client handles GET/POST/etc. Always set Timeout and close resp.Body with defer. Check resp.StatusCode before decoding.

JV
Java
var client = HttpClient.newHttpClient();
var resp = client.send(req, BodyHandlers.ofString());
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 != http.StatusOK {
    return fmt.Errorf("unexpected status %d", resp.StatusCode)
}

2. JSON Marshaling

json.Unmarshal decodes bytes; json.NewDecoder streams from readers. Struct tags control JSON field names — equivalent to @JsonProperty.

JV
Java
var mapper = new ObjectMapper();
var users = mapper.readValue(body, User[].class);
GO
Go
type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}
var users []User
json.NewDecoder(resp.Body).Decode(&users)

// Encoding:
out, _ := json.MarshalIndent(users, "", "  ")

3. Strings Package

The strings package covers everything Apache Commons StringUtils provides. No dependency needed.

JV
Java
StringUtils.join(arr, "-")
StringUtils.isBlank(s)
StringUtils.containsIgnoreCase(s, sub)
GO
Go
strings.Join(parts, "-")
strings.TrimSpace(s) == ""
strings.Contains(strings.ToLower(s), sub)
strings.Fields(s)        // split on whitespace
strings.ReplaceAll(s, "a", "b")

4. File and Path Operations

os.ReadFile/WriteFile are single-call file I/O (Go 1.16+). filepath.Join handles OS separators. Use bufio.Scanner for large files.

JV
Java
Files.readString(Path.of("f.txt"))
Files.writeString(Path.of("out.txt"), s)
GO
Go
// Simple:
data, err := os.ReadFile("f.txt")
os.WriteFile("out.txt", data, 0644)

// Large files line-by-line:
f, _ := os.Open("big.txt")
scanner := bufio.NewScanner(f)
for scanner.Scan() { process(scanner.Text()) }
f.Close()
Rule of Thumb
Avoid adding external dependencies for string/file/JSON/HTTP work — Go stdlib handles all of these reliably.

Common Mistakes

When coming from Java, developers often make these mistakes:

  • Go's net/http is production-ready; Java's HttpClient (11+) is similar but needs more boilerplate
  • encoding/json uses struct tags (`json:"name"`) like Jackson @JsonProperty — no ObjectMapper setup required
  • strings package replaces Apache Commons StringUtils: Contains, HasPrefix, Fields, TrimSpace, Join, ReplaceAll
Common Pitfall
Don't assume Go works exactly like Java. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • net/http: production HTTP client + server — always set Timeout, defer resp.Body.Close()
  • encoding/json: struct tags (`json:"name"`) control marshaling; NewDecoder for streaming, Unmarshal for []byte
  • strings package replaces Apache Commons: Join, Fields, TrimSpace, Contains, HasPrefix, ReplaceAll
  • os.ReadFile/WriteFile for simple files; bufio.Scanner for large files line-by-line
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your Java code in Go to practice these concepts.
PreviousNext