What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Gin’s ShouldBindJSON decodes a request body; it does not decide how that body updates a stored resource. To make a PATCH handler preserve omitted fields and handle explicit null correctly, bind into a request-only patch model, track presence when necessary, and apply each field according to the endpoint’s documented rules.
Why does my Gin PATCH request clear fields I didn’t send?
The usual cause is treating a partial request as a complete replacement. Suppose a stored user has a nonempty name and enabled set to true. A handler binds a body containing only {"name":"Rae"} into a newly allocated struct. The request struct’s enabled field remains its Go zero value, false. If the handler then replaces the stored user with that struct, the omitted field is overwritten.
Omission did not instruct Go to clear the field. The handler’s whole-object assignment turned the zero-valued, partial DTO into a replacement object. Gin documents ShouldBindJSON as a shortcut to its JSON binding engine; binding decodes input, while the application must decide what the decoded fields mean for existing state (Gin package documentation).
What should absent, null, and a value mean?
PATCH describes partial modification, but it does not give every field a universal interpretation for null. Define the behavior in the endpoint contract. For each field, decide whether an omitted member leaves the current value unchanged, whether null clears it or is rejected, and how a concrete value is validated and applied. The patch document’s rules determine those field-level semantics (RFC 5789).
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
- Absent: The client did not request a change; ordinarily preserve the current value.
- Null: Apply the documented behavior for that field, such as clearing a nullable value or returning a validation error.
- Concrete value: Validate it, then assign it.
For nonnullable scalars, a pointer can distinguish an omitted field from an explicitly supplied zero such as false, 0, or "". But a basic pointer field does not distinguish omission from null in a fresh struct under Go’s legacy encoding/json behavior: a present null sets the pointer to nil, and an omitted member also leaves it nil. The Go package documentation describes null as setting pointers, interfaces, maps, and slices to nil (Go encoding/json documentation).
How do I distinguish a missing JSON field from null in Go?
Use a request-only representation that records whether a key appeared as well as what it contained. The following generic wrapper targets the legacy encoding/json API and records three states for fields whose type is PatchField[T]:
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
type PatchField[T any] struct {
Set bool
Null bool
Value T
}
func (p *PatchField[T]) UnmarshalJSON(data []byte) error {
p.Set = true
p.Null = bytes.Equal(bytes.TrimSpace(data), []byte("null"))
if p.Null {
var zero T
p.Value = zero
return nil
}
return json.Unmarshal(data, &p.Value)
}
type UserPatch struct {
Name PatchField[string] `json:"name"`
Email PatchField[*string] `json:"email"`
}
This requires imports for bytes and encoding/json. A field omitted from the JSON object does not invoke its unmarshaler, so its zero-valued wrapper remains Set == false. A supplied null invokes the wrapper’s UnmarshalJSON method and sets Set and Null to true. A concrete JSON value sets Set and is decoded into Value. Verify this behavior with the Go decoder and field design used by your service; Go’s JSON v2 APIs or options may have different behavior.
Here is an explicit application flow. The example treats a null email as a request to clear it; choose a different rule if that is not your endpoint’s contract.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
func applyUserPatch(current *User, patch UserPatch) error {
if patch.Name.Set {
if patch.Name.Null {
return errors.New("name cannot be null")
}
if patch.Name.Value == "" {
return errors.New("name cannot be empty")
}
current.Name = patch.Name.Value
}
if patch.Email.Set {
if patch.Email.Null {
current.Email = nil
} else {
current.Email = patch.Email.Value
}
}
return nil
}
Another option is a custom request DTO unmarshaler that records key presence, or a map[string]json.RawMessage decoded at the object boundary. With the map approach, check whether a key exists before inspecting its raw JSON for null or decoding a concrete value. It is flexible, but makes per-field decoding and validation explicit. Typed wrappers provide clearer field-level types at the cost of additional scaffolding.
How should the Gin handler process a PATCH?
Keep decoding, validation, state changes, and persistence distinct. Gin’s guide explains that ShouldBind methods return errors for the handler to handle, unlike Bind methods, which abort with a 400 response on binding errors. JSON-bound fields should use JSON tags when their names do not otherwise match (Gin model binding guide; Gin package documentation).
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
- Decode: Call
ShouldBindJSONwith a patch DTO and stop if binding fails. - Validate: Check values and the allowed null behavior before changing stored state.
- Load: Fetch the current resource.
- Apply: Change only fields marked present, using the contract’s rule for null.
- Persist and respond: Save the updated resource and return the status or representation required by the endpoint.
Do not replace the persistent resource with the partially populated DTO. Do not conflate malformed JSON, invalid field values, rejected nulls, and persistence failures: they occur at different stages and may require different responses.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Does omitempty make PATCH fields optional?
No. omitempty affects JSON marshaling output; it does not record whether an input key appeared. It cannot distinguish an omitted request member from an explicitly supplied value by itself (Go encoding/json marshaling documentation).
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Why does ShouldBindJSON ignore null?
Binding and patch semantics are separate. A decoder may successfully decode null into a pointer as nil, but that does not tell the handler whether the client omitted the key or explicitly sent null. If the handler only checks whether a pointer is nil, those two input states have collapsed. Track presence independently when they require different actions; if your contract treats null like omission or disallows null, a basic pointer may be sufficient.
How do I reject unknown keys and test the fix?
Unknown keys
The Go JSON decoder ignores unknown struct keys by default. If the API should reject them, a decoder configured with DisallowUnknownFields can do so. Do not assume Gin’s ordinary ShouldBindJSON shortcut enforces that policy; check the configuration supported by the Gin binding version used in your service (Go decoder documentation; Gin model binding guide).
Regression tests
Start each case with a stored resource that has nonzero values, then assert both the resulting stored state and the HTTP response. The expected result for null depends on the endpoint contract.
| Request member | What to verify |
|---|---|
| Omitted | The stored value remains unchanged. |
null |
The field is cleared, rejected, or handled according to its documented rule. |
| Ordinary value | The value is validated and assigned. |
Explicit zero: 0, false, or "" |
A supplied zero is treated as an update, not mistaken for omission. |
| Empty list or object | The field’s contract distinguishes the supplied empty value from omission where required. |
Also cover malformed JSON, invalid field values, and unknown keys if the endpoint rejects them. This catches both decoding errors and mistakes in the later application logic.
Free tools Windows power users keep installed
One-click scans. No signup required.
Which patch representation should I choose?
Choose based on the endpoint’s actual update semantics, rather than looking for a Gin-specific tag. Compare whether each representation can distinguish absent, null, and value; how conveniently it supports validation; how nested objects and collections are updated; whether application code can avoid modifying unrelated state; whether it fits the endpoint’s advertised media type and clients; and how much custom decoding code it adds. A typed wrapper is a good fit for a stable DTO with clear field-level rules. A raw-message map is useful when keys or update shapes are dynamic, but requires explicit decoding and validation for each field.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

