Decode Generic Response Envelope

Unwrap a repeated API envelope once with a generic helper, so every endpoint keeps typed payloads without repeating decode boilerplate.

GoData Fetching

Code

gosnippet
54 lines
package main

import (
	"encoding/json"
	"fmt"
)

// Envelope 字段带 json 标签:encoding/json 按标签名匹配键,
// request_id / cursor 落到带标签的字段;Data 同理对应 JSON 的 data
type Envelope[T any] struct {
	Data T     `json:"data"`
	Meta Meta  `json:"meta"`
}

type Meta struct {
	RequestID string `json:"request_id"`
	Cursor    string `json:"cursor"`
}

type User struct {
	Name string
}

type Repo struct {
	Stars int
}

// 一次解码:泛型让每个端点拿到自己的载荷类型
func decode[T any](raw []byte) (Envelope[T], error) {
	var env Envelope[T]
	if err := json.Unmarshal(raw, &env); err != nil {
		return Envelope[T]{}, err
	}
	return env, nil
}

func main() {
	userJSON := []byte("{"data":{"name":"ada"},"meta":{"request_id":"r-1"}}")
	repoJSON := []byte("{"data":{"stars":91},"meta":{"request_id":"r-2","cursor":"next-page"}}")

	users, err := decode[User](userJSON)
	if err != nil {
		fmt.Println("user:", err)
		return
	}
	fmt.Printf("user: %s (req %s)\n", users.Data.Name, users.Meta.RequestID)

	repos, err := decode[Repo](repoJSON)
	if err != nil {
		fmt.Println("repo:", err)
		return
	}
	fmt.Printf("repo: %d stars (cursor %s)\n", repos.Data.Stars, repos.Meta.Cursor)
}

How it works

Decode Generic Response Envelope comes down to the function main.

Every fallible call checks err != nil (3 sites), so an error is handled where it happens rather than bubbling invisibly.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.
  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Using it

Signature: func main()

Running the file prints labeled results such as user:, repo: — each operation’s effect is visible in the output.

Key statements

func decode[T any](raw []byte) (Envelope[T], error) {
var env Envelope[T]
if err := json.Unmarshal(raw, &env); err != nil {
return Envelope[T]{}, err
}
return env, nil
}
if err != nil {
fmt.Println("user:", err)
return
}
if err != nil {
fmt.Println("repo:", err)
return
}

Interactive Tools for This Topic

FAQ

What is the error handling style?
As returned `error` values, checked at 3 sites — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
What does Decode Generic Response Envelope print when run?
Run it as a complete program — the output lines carry labels such as `user:`, `repo:`.