Decode Status Enums With Custom UnmarshalJSON

Validate enum-like fields at decode time by implementing UnmarshalJSON, so unknown status values become decode errors instead of leaking into business logic.

GoData Integrity

Code

gosnippet
52 lines
package main

import (
	"encoding/json"
	"fmt"
)

// Status 是枚举(enum)型状态字段,只允许三个合法取值
type Status string

const (
	StatusActive   Status = "active"
	StatusPaused   Status = "paused"
	StatusArchived Status = "archived"
)

// UnmarshalJSON 在解码(decode)期校验取值:非法状态直接报错,不流入业务层
func (s *Status) UnmarshalJSON(data []byte) error {
	var raw string
	if err := json.Unmarshal(data, &raw); err != nil {
		return err
	}
	switch Status(raw) {
	case StatusActive, StatusPaused, StatusArchived:
		*s = Status(raw)
		return nil
	default:
		return fmt.Errorf("unknown status %q (want active, paused or archived)", raw)
	}
}

type Subscription struct {
	ID     string `json:"id"`
	Status Status `json:"status"`
}

func main() {
	payloads := []string{
		`{"id":"s1","status":"active"}`,
		`{"id":"s2","status":"paused"}`,
		`{"id":"s3","status":"deleted"}`,
	}
	for _, payload := range payloads {
		var sub Subscription
		err := json.Unmarshal([]byte(payload), &sub)
		if err != nil {
			fmt.Println("rejected:", err)
			continue
		}
		fmt.Printf("accepted: id=%s status=%s\n", sub.ID, sub.Status)
	}
}

Line-by-line reading

Count the functions UnmarshalJSON and main as the entire surface area of Decode Status Enums With Custom UnmarshalJSON.

The one repetition in this snippet is the loop for _, payload := range payloads. The Go idiom runs throughout — 2 if err != nil checks, each handling the failure on the spot.

What to watch for

  • The function reports failure by returning error — callers branch on it before touching other results.

Applying it

Entry signature: func (s *Status) UnmarshalJSON(data []byte) error

The demo output is labeled (rejected:, accepted: id=), so the printed output reads as a trace of the operations performed.

Statements that matter

return fmt.Errorf("unknown status %q (want active, paused or archived)", raw)
for _, payload := range payloads {
var sub Subscription
err := json.Unmarshal([]byte(payload), &sub)
if err != nil {
fmt.Println("rejected:", err)
continue
}
fmt.Printf("accepted: id=%s status=%s\n", sub.ID, sub.Status)
}

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
As returned `error` values — 2 sites in the snippet check `err` before using other results.
What does Decode Status Enums With Custom UnmarshalJSON print when run?
Execute the whole file; each printed line is prefixed with a label like `rejected:`, `accepted: id=`.