### Install easyjson for Go >= 1.17 Source: https://github.com/mailru/easyjson/blob/master/README.md Use 'go get' and 'go install' for installing easyjson with Go modules. ```sh # for Go >= 1.17 go get github.com/mailru/easyjson && go install github.com/mailru/easyjson/...@latest ``` -------------------------------- ### Install easyjson for Go < 1.17 Source: https://github.com/mailru/easyjson/blob/master/README.md Use 'go get -u' to install easyjson for older Go versions. ```sh # for Go < 1.17 go get -u github.com/mailru/easyjson/... ``` -------------------------------- ### Install easyjson CLI and Library Source: https://context7.com/mailru/easyjson/llms.txt Installs the easyjson library and its associated CLI tools for Go version 1.17 and above. ```sh # Go >= 1.17 go get github.com/mailru/easyjson && go install github.com/mailru/easyjson/...@latest ``` -------------------------------- ### Write JSON to HTTP Response with easyjson.MarshalToHTTPResponseWriter Source: https://context7.com/mailru/easyjson/llms.txt Marshal JSON data and write it to an http.ResponseWriter, automatically setting Content-Type and Content-Length headers. The 'started' return value helps differentiate between marshaling errors before and after headers are sent. ```go package main import ( "log" "net/http" "github.com/mailru/easyjson" ) //easyjson:json type UserResponse struct { ID int `json:"id"` Name string `json:"name"` } func handler(w http.ResponseWriter, r *http.Request) { resp := &UserResponse{ID: 1, Name: "Alice"} started, _, err := easyjson.MarshalToHTTPResponseWriter(resp, w) if err != nil { if !started { http.Error(w, "marshal error", http.StatusInternalServerError) } log.Println("marshal error:", err) } } func main() { http.HandleFunc("/user", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } // GET /user → 200 OK, Content-Type: application/json, body: {"id":1,"name":"Alice"} ``` -------------------------------- ### easyjson.MarshalToHTTPResponseWriter Source: https://context7.com/mailru/easyjson/llms.txt Marshals a value, then sets Content-Type: application/json and Content-Length headers before writing the body. The started return value is false only if marshaling failed before any header was written, allowing a 500 response to still be sent. ```APIDOC ## `easyjson.MarshalToHTTPResponseWriter` — Write JSON to an HTTP response `MarshalToHTTPResponseWriter` marshals a value, then sets `Content-Type: application/json` and `Content-Length` headers before writing the body. The `started` return value is `false` only if marshaling failed before any header was written, allowing a 500 response to still be sent. ### Method `easyjson.MarshalToHTTPResponseWriter(v interface{}, w http.ResponseWriter) (started bool, written int64, err error)` ### Parameters #### Path Parameters - **v** (interface{}) - Required - The value to marshal. - **w** (http.ResponseWriter) - Required - The HTTP response writer. ### Response #### Success Response - **started** (bool): `true` if headers were successfully written, `false` otherwise. - **written** (int64): The number of bytes written. - **err** (error): nil if successful, otherwise an error. ### Request Example ```go package main import ( "log" "net/http" "github.com/mailru/easyjson" ) //easyjson:json type UserResponse struct { ID int `json:"id"` Name string `json:"name"` } func handler(w http.ResponseWriter, r *http.Request) { resp := &UserResponse{ID: 1, Name: "Alice"} started, _, err := easyjson.MarshalToHTTPResponseWriter(resp, w) if err != nil { if !started { http.Error(w, "marshal error", http.StatusInternalServerError) } log.Println("marshal error:", err) } } func main() { http.HandleFunc("/user", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` ### Response Example ``` // GET /user → 200 OK, Content-Type: application/json, body: {"id":1,"name":"Alice"} ``` ``` -------------------------------- ### Configure buffer.Init Memory Pool Source: https://context7.com/mailru/easyjson/llms.txt Initializes the byte-slice pooling mechanism for efficient memory management during marshaling. Call this once at application startup. ```go import "github.com/mailru/easyjson/buffer" func init() { buffer.Init(buffer.PoolConfig{ StartSize: 256, // initial chunk (bytes) PooledSize: 1024, // minimum chunk reused via sync.Pool MaxSize: 65536, // largest chunk ever allocated }) } ``` -------------------------------- ### Run easyjson Code Generator Source: https://github.com/mailru/easyjson/blob/master/README.md Execute the easyjson command-line tool to generate marshaler and unmarshaler functions for Go structs. ```sh easyjson -all .go ``` -------------------------------- ### Optional Primitive Types with easyjson/opt package Source: https://context7.com/mailru/easyjson/llms.txt Use optional wrappers like opt.String, opt.Int, etc., to distinguish between missing and zero-value JSON fields without using pointers. These wrappers implement Marshaler, Unmarshaler, and Optional for omitempty compatibility. ```go import "github.com/mailru/easyjson/opt" //easyjson:json type Settings struct { Theme opt.String `json:"theme"` // null when not set FontSize opt.Int `json:"font_size,omitempty"` // omitted when undefined Debug opt.Bool `json:"debug"` } func main() { raw := []byte(`{"theme":"dark","debug":true}`) var s Settings easyjson.Unmarshal(raw, &s) fmt.Println(s.Theme.Defined, s.Theme.V) // true dark fmt.Println(s.FontSize.Defined) // false (absent in JSON) fmt.Println(s.Debug.Defined, s.Debug.V) // true true // Construct with helpers s2 := Settings{ Theme: opt.OString("light"), FontSize: opt.OInt(14), } data, _ := easyjson.Marshal(&s2) fmt.Println(string(data)) // {"theme":"light","debug":null} (FontSize omitted because omitempty is set… wait, it IS defined) // {"theme":"light","font_size":14,"debug":null} // Get with default fmt.Println(s.FontSize.Get(12)) // 12 (undefined → default) } ``` -------------------------------- ### Generate Struct Code with easyjson:json Source: https://github.com/mailru/easyjson/blob/master/README.md Use the '//easyjson:json' comment directive to explicitly include a struct for code generation when '-all' is not used. ```go //easyjson:json type A struct {} ``` -------------------------------- ### Struct Annotations for easyjson Code Generation Source: https://context7.com/mailru/easyjson/llms.txt Defines struct-level annotations to control easyjson code generation. Use `//easyjson:json` for opt-in or `//easyjson:skip` to exclude structs when using the `-all` flag. ```go //easyjson:json // opt-in (used without -all) type User struct { ... } ``` ```go //easyjson:skip // excluded when using -all type Internal struct { ... } ``` -------------------------------- ### Generate easyjson Code for Structs Source: https://context7.com/mailru/easyjson/llms.txt Uses the easyjson CLI to generate MarshalEasyJSON/UnmarshalEasyJSON methods for Go structs. Supports various flags for customization like all structs, specific annotations, output file, and build tags. ```sh # Generate for all structs in models.go → models_easyjson.go easyjson -all models.go ``` ```sh # Generate only for structs annotated with //easyjson:json easyjson models.go ``` ```sh # Whole package, snake_case field names, omit empty fields by default easyjson -all -snake_case -omit_empty ./mypackage/ ``` ```sh # Custom output file, no standard MarshalJSON stubs, disallow unknown fields easyjson -all -no_std_marshalers -disallow_unknown_fields -output_filename out_easyjson.go models.go ``` ```sh # Add build tags to the generated file easyjson -all -build_tags "!integration" models.go ``` -------------------------------- ### Custom MarshalEasyJSON/UnmarshalEasyJSON Implementations Source: https://context7.com/mailru/easyjson/llms.txt Implement Marshaler and Unmarshaler interfaces for full control over JSON encoding/decoding. This allows seamless integration with easyjson.Marshal/Unmarshal. ```go import ( "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) type Color struct{ R, G, B uint8 } // Serialize as "#RRGGBB" hex string. func (c *Color) MarshalEasyJSON(w *jwriter.Writer) { w.String(fmt.Sprintf("#%02x%02x%02x", c.R, c.G, c.B)) } // Deserialize from "#RRGGBB" hex string. func (c *Color) UnmarshalEasyJSON(l *jlexer.Lexer) { s := l.String() if l.Ok() { fmt.Sscanf(s, "#%02x%02x%02x", &c.R, &c.G, &c.B) } } //easyjson:json type Theme struct { Background Color `json:"bg"` Foreground Color `json:"fg"` } func main() { t := &Theme{Background: Color{30, 30, 30}, Foreground: Color{220, 220, 220}} data, _ := easyjson.Marshal(t) fmt.Println(string(data)) // {"bg":"#1e1e1e","fg":"#dcdcdc"} var t2 Theme easyjson.Unmarshal(data, &t2) fmt.Printf("%+v\n", t2) // {Background:{R:30 G:30 B:30} Foreground:{R:220 G:220 B:220}} } ``` -------------------------------- ### easyjson.MarshalToWriter Source: https://context7.com/mailru/easyjson/llms.txt Writes JSON directly to any io.Writer using jwriter.Writer.DumpTo, which leverages net.Buffers for vectored I/O. This avoids the extra allocation of BuildBytes and is the most efficient path for streaming output. ```APIDOC ## `easyjson.MarshalToWriter` — Stream JSON to an `io.Writer` `MarshalToWriter` writes JSON directly to any `io.Writer` using `jwriter.Writer.DumpTo`, which leverages `net.Buffers` for vectored I/O. This avoids the extra allocation of `BuildBytes` and is the most efficient path for streaming output. ### Method `easyjson.MarshalToWriter(v interface{}, w io.Writer) (int64, error)` ### Parameters #### Path Parameters - **v** (interface{}) - Required - The value to marshal. - **w** (io.Writer) - Required - The writer to write the JSON to. ### Response #### Success Response - **int64**: The number of bytes written. - **error**: nil if successful, otherwise an error. ### Request Example ```go package main import ( "bytes" "fmt" "log" "github.com/mailru/easyjson" ) //easyjson:json type Event struct { Name string `json:"name"` Payload string `json:"payload"` } func main() { e := &Event{Name: "click", Payload: `{"x":10,"y":20}`} var buf bytes.Buffer written, err := easyjson.MarshalToWriter(e, &buf) if err != nil { log.Fatal(err) } fmt.Printf("wrote %d bytes: %s\n", written, buf.String()) } ``` ### Response Example ``` // wrote 35 bytes: {"name":"click","payload":"{\"x\":10,\"y\":20}"} ``` ``` -------------------------------- ### Stream JSON to io.Writer with easyjson.MarshalToWriter Source: https://context7.com/mailru/easyjson/llms.txt Use MarshalToWriter to efficiently stream JSON directly to an io.Writer, avoiding extra memory allocations. This is the preferred method for streaming output. ```go package main import ( "bytes" "fmt" "log" "github.com/mailru/easyjson" ) //easyjson:json type Event struct { Name string `json:"name"` Payload string `json:"payload"` } func main() { e := &Event{Name: "click", Payload: `{"x":10,"y":20}`} var buf bytes.Buffer written, err := easyjson.MarshalToWriter(e, &buf) if err != nil { log.Fatal(err) } fmt.Printf("wrote %d bytes: %s\n", written, buf.String()) // wrote 35 bytes: {"name":"click","payload":"{\"x\":10,\"y\":20}"} } ``` -------------------------------- ### Low-level JSON Output with jwriter.Writer Source: https://context7.com/mailru/easyjson/llms.txt Use jwriter.Writer as a building block for marshaling, writing typed primitives to an internal pooled buffer. Control null map/slice output with NilMapAsEmpty/NilSliceAsEmpty flags. By default, it escapes HTML characters. ```go import ( "github.com/mailru/easyjson/jwriter" "os" ) func main() { w := jwriter.Writer{ NoEscapeHTML: false, // escape <, >, & by default Flags: jwriter.NilSliceAsEmpty, // nil slice → [] } w.RawByte('{') w.String("name"); w.RawByte(':'); w.String("Alice & Bob") w.RawByte(',') w.String("score"); w.RawByte(':'); w.Float64(98.6) w.RawByte(',') w.String("active"); w.RawByte(':'); w.Bool(true) w.RawByte('}') if w.Error != nil { panic(w.Error) } w.DumpTo(os.Stdout) // {"name":"Alice \u0026 Bob","score":98.6,"active":true} } ``` -------------------------------- ### Marshal Go Struct to JSON Bytes with easyjson Source: https://context7.com/mailru/easyjson/llms.txt Serializes a Go struct into JSON bytes using `easyjson.Marshal`. This method calls the generated `MarshalEasyJSON` and avoids reflection for performance. Ensure the struct type implements the `easyjson.Marshaler` interface. ```go package main import ( "fmt" "log" "github.com/mailru/easyjson" ) //easyjson:json type Article struct { ID int `json:"id"` Title string `json:"title"` Tags []string `json:"tags"` Score float64 `json:"score,omitempty"` Draft bool `json:"draft,omitempty"` } func main() { a := &Article{ ID: 42, Title: "easyjson deep-dive", Tags: []string{"go", "json", "performance"}, Score: 9.8, } data, err := easyjson.Marshal(a) if err != nil { log.Fatal(err) } fmt.Println(string(data)) // Output: {"id":42,"title":"easyjson deep-dive","tags":["go","json","performance"],"score":9.8} } ``` -------------------------------- ### easyjson Struct Field Tags for Marshaling and Unmarshaling Control Source: https://context7.com/mailru/easyjson/llms.txt easyjson supports standard encoding/json tags plus custom directives like omitempty, omitzero, nocopy, intern, and required for fine-grained control over JSON serialization and deserialization. ```go //easyjson:json type Product struct { ID int `json:"id"` Name string `json:"name"` Description string `json:"desc,omitempty"` // omit if "" CreatedAt time.Time `json:"created_at,omitzero"` // omit if time.IsZero() Category string `json:"category,intern"` // deduplicate on unmarshal Token string `json:"token,nocopy"` // zero-copy string on unmarshal SKU string `json:"sku,required"` // error if missing Internal string `json:"-"` // never marshaled } // Marshaling a Product with empty Description and zero CreatedAt: // {"id":1,"name":"Widget","sku":"WGT-001"} // Unmarshaling without "sku" field returns an error. // Unmarshaling with repeated "category" values reuses the same string pointer. ``` -------------------------------- ### Enable String Interning in easyjson Source: https://github.com/mailru/easyjson/blob/master/README.md To enable string interning for a string field during unmarshaling, add the `intern` keyword to its `json` tag. This can reduce memory usage for fields with repetitive values, at the cost of slightly increased CPU usage. ```go type Foo struct { UUID string `json:"uuid"` // will not be interned during unmarshaling State string `json:"state,intern"` // will be interned during unmarshaling } ``` -------------------------------- ### Skip Struct Generation with easyjson:skip Source: https://github.com/mailru/easyjson/blob/master/README.md Use the '//easyjson:skip' comment directive to prevent easyjson from generating code for a specific struct. ```go //easyjson:skip type A struct {} ``` -------------------------------- ### Parse JSON with jlexer.Lexer Source: https://context7.com/mailru/easyjson/llms.txt Tokenizes JSON input for efficient field reading without allocations. Use this for low-level parsing when performance is critical. ```go import "github.com/mailru/easyjson/jlexer" func parsePoint(data []byte) (x, y int, err error) { l := jlexer.Lexer{Data: data, UseMultipleErrors: false} l.Delim('{') for !l.IsDelim('}') { key := l.UnsafeString() l.WantColon() switch key { case "x": x = l.Int() case "y": y = l.Int() default: l.SkipRecursive() // skip unknown fields } l.WantComma() } l.Delim('}') l.Consumed() return x, y, l.Error() } func main() { x, y, err := parsePoint([]byte(`{"x":10,"y":42,"z":0}`)) fmt.Println(x, y, err) // 10 42 } ``` -------------------------------- ### Struct Field Tags Source: https://context7.com/mailru/easyjson/llms.txt easyjson supports all standard encoding/json tags plus additional directives like omitempty, omitzero, nocopy, intern, and required for fine-grained control over marshaling and unmarshaling behavior. ```APIDOC ## Struct Field Tags — `omitempty`, `omitzero`, `nocopy`, `intern`, `required` easyjson supports all standard `encoding/json` tags plus additional directives. `omitempty` skips zero-value fields; `omitzero` skips fields whose `IsZero() bool` method returns true (e.g., `time.Time`); `nocopy` avoids allocating a new string on unmarshal (zero-copy, safe for short-lived objects); `intern` deduplicates repeated string values in memory; `required` causes unmarshal to error if the field is absent; `-` excludes the field entirely. ### Example Struct Definition ```go //easyjson:json type Product struct { ID int `json:"id"` Name string `json:"name"` Description string `json:"desc,omitempty"` // omit if "" CreatedAt time.Time `json:"created_at,omitzero"` // omit if time.IsZero() Category string `json:"category,intern"` // deduplicate on unmarshal Token string `json:"token,nocopy"` // zero-copy string on unmarshal SKU string `json:"sku,required"` // error if missing Internal string `json:"-"` // never marshaled } ``` ### Usage Examples **Marshaling**: When marshaling a `Product` with an empty `Description` and a zero `CreatedAt` time, the output will omit these fields: ```json // Marshaling a Product with empty Description and zero CreatedAt: // {"id":1,"name":"Widget","sku":"WGT-001"} ``` **Unmarshaling**: - Unmarshaling a JSON payload that is missing the `sku` field (marked as `required`) will result in an error. - Unmarshaling JSON with repeated values for the `category` field will cause `easyjson` to reuse the same string pointer for those values, optimizing memory usage. ``` -------------------------------- ### Serialize Go Struct to JSON Source: https://github.com/mailru/easyjson/blob/master/README.md Use easyjson.Marshal to convert a Go struct into a JSON byte slice. Ensure the struct is properly initialized. ```go someStruct := &SomeStruct{Field1: "val1", Field2: "val2"} rawBytes, err := easyjson.Marshal(someStruct) ``` -------------------------------- ### Unmarshal JSON Bytes into Go Struct with easyjson Source: https://context7.com/mailru/easyjson/llms.txt Deserializes JSON bytes into a Go struct using `easyjson.Unmarshal`. It wraps the input with a `jlexer.Lexer` and calls the generated `UnmarshalEasyJSON` method. Object keys are matched case-sensitively. ```go package main import ( "fmt" "log" "github.com/mailru/easyjson" ) //easyjson:json type Article struct { ID int `json:"id"` Title string `json:"title"` Tags []string `json:"tags"` } func main() { raw := []byte(`{"id":7,"title":"Hello easyjson","tags":["intro","tutorial"]}`) var a Article if err := easyjson.Unmarshal(raw, &a); err != nil { log.Fatal(err) } fmt.Printf("ID=%d Title=%q Tags=%v\n", a.ID, a.Title, a.Tags) // Output: ID=7 Title="Hello easyjson" Tags=[intro tutorial] } ``` -------------------------------- ### Round-trip unknown JSON fields with easyjson.UnknownFieldsProxy Source: https://context7.com/mailru/easyjson/llms.txt Embed UnknownFieldsProxy in a struct to store unknown JSON keys in an internal map during unmarshaling and re-emit them during marshaling. This ensures full round-trip fidelity for extensible schemas. ```go //easyjson:json type FlexibleRecord struct { easyjson.UnknownFieldsProxy ID int `json:"id"` Name string `json:"name"` } func main() { raw := []byte(`{"id":5,"name":"test","future_field":"value","extra":42}`) var r FlexibleRecord if err := easyjson.Unmarshal(raw, &r); err != nil { log.Fatal(err) } // r.ID=5, r.Name="test"; "future_field" and "extra" stored internally out, _ := easyjson.Marshal(&r) fmt.Println(string(out)) // {"id":5,"name":"test","future_field":"value","extra":42} } ``` -------------------------------- ### Deserialize JSON to Go Struct Source: https://github.com/mailru/easyjson/blob/master/README.md Use easyjson.Unmarshal to parse a JSON byte slice into a Go struct. The struct should be initialized before unmarshaling. ```go someStruct := &SomeStruct{} err := easyjson.Unmarshal(rawBytes, someStruct) ``` -------------------------------- ### Decode JSON from io.Reader with easyjson.UnmarshalFromReader Source: https://context7.com/mailru/easyjson/llms.txt Use UnmarshalFromReader to decode JSON from an io.Reader, suitable for handling request bodies. It reads all bytes from the reader before decoding. ```go package main import ( "fmt" "log" "net/http" "strings" "github.com/mailru/easyjson" ) //easyjson:json type CreateRequest struct { Name string `json:"name"` Email string `json:"email"` } func handler(w http.ResponseWriter, r *http.Request) { var req CreateRequest if err := easyjson.UnmarshalFromReader(r.Body, &req); err != nil { http.Error(w, "bad request", http.StatusBadRequest) return } fmt.Fprintf(w, "created user: %s <%s>", req.Name, req.Email) } func main() { body := strings.NewReader(`{"name":"Bob","email":"bob@example.com"}`) req, _ := http.NewRequest(http.MethodPost, "/users", body) req.Header.Set("Content-Type", "application/json") var cr CreateRequest if err := easyjson.UnmarshalFromReader(req.Body, &cr); err != nil { log.Fatal(err) } fmt.Printf("%+v\n", cr) // {Name:Bob Email:bob@example.com} } ``` -------------------------------- ### easyjson.UnmarshalFromReader Source: https://context7.com/mailru/easyjson/llms.txt Reads all bytes from the provided reader via ioutil.ReadAll then decodes them. Useful for HTTP request bodies. ```APIDOC ## `easyjson.UnmarshalFromReader` — Decode JSON from an `io.Reader` `UnmarshalFromReader` reads all bytes from the provided reader via `ioutil.ReadAll` then decodes them. Useful for HTTP request bodies. ### Method `easyjson.UnmarshalFromReader(r io.Reader, v interface{}) error` ### Parameters #### Path Parameters - **r** (io.Reader) - Required - The reader to read JSON from. - **v** (interface{}) - Required - The value to unmarshal into. ### Response #### Success Response - **error**: nil if successful, otherwise an error. ### Request Example ```go package main import ( "fmt" "log" "net/http" "strings" "github.com/mailru/easyjson" ) //easyjson:json type CreateRequest struct { Name string `json:"name"` Email string `json:"email"` } func handler(w http.ResponseWriter, r *http.Request) { var req CreateRequest if err := easyjson.UnmarshalFromReader(r.Body, &req); err != nil { http.Error(w, "bad request", http.StatusBadRequest) return } fmt.Fprintf(w, "created user: %s <%s>", req.Name, req.Email) } func main() { body := strings.NewReader(`{"name":"Bob","email":"bob@example.com"}`) req, _ := http.NewRequest(http.MethodPost, "/users", body) req.Header.Set("Content-Type", "application/json") var cr CreateRequest if err := easyjson.UnmarshalFromReader(req.Body, &cr); err != nil { log.Fatal(err) } fmt.Printf("%+v\n", cr) } ``` ### Response Example ``` // {Name:Bob Email:bob@example.com} ``` ``` -------------------------------- ### Embed pre-encoded JSON with easyjson.RawMessage Source: https://context7.com/mailru/easyjson/llms.txt Use RawMessage to embed pre-encoded JSON verbatim during marshaling or capture raw JSON tokens during unmarshaling without parsing. It is a []byte alias that implements Marshaler and Unmarshaler. ```go //easyjson:json type Envelope struct { Type string `json:"type"` Payload easyjson.RawMessage `json:"payload"` } func main() { // Unmarshal: capture payload without parsing raw := []byte(`{"type":"order","payload":{"item":"book","qty":3}}`) var env Envelope if err := easyjson.Unmarshal(raw, &env); err != nil { log.Fatal(err) } fmt.Printf("type=%s payload=%s\n", env.Type, env.Payload) // type=order payload={"item":"book","qty":3} // Marshal: embed pre-built JSON env2 := Envelope{ Type: "ack", Payload: easyjson.RawMessage(`{"status":"ok"}`), } data, _ := easyjson.Marshal(&env2) fmt.Println(string(data)) // {"type":"ack","payload":{"status":"ok"}} } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.