Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a Gin PATCH endpoint, track whether each field was sent separately from the value it contains. A JSON request such as {"active":false,"quota":0} can then explicitly set a boolean to false and a number to 0, while omitted fields remain unchanged. Avoid binding:"required" on optional scalar fields: Gin’s validator treats a type’s zero value as missing.

Why ordinary scalar fields lose PATCH presence

When Go decodes JSON into a struct with plain int, bool, or string fields, an omitted field has the type’s zero value. An explicitly supplied 0, false, or empty string also produces that value. Once decoded this way, the handler cannot tell omission from an explicit zero by inspecting the field alone.

The JSON struct option json:",omitempty" does not solve this: it controls whether zero-valued fields are omitted when encoding JSON, not whether an incoming member was present. Gin uses go-playground/validator/v10 for binding validation, and its required rule rejects default zero values, including 0, false, and "". See Gin’s model binding and validation documentation, the Go encoding/json documentation, and validator’s tag documentation.

Use pointers for the common two-state case

If your API treats JSON null the same as omission, or does not allow clients to clear a field with null, pointers provide a compact typed representation. A nil pointer means there is no decoded value to apply; a non-nil pointer can hold an explicit zero.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • 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.
type PatchUser struct {
    Age    *int    `json:"age"`
    Active *bool   `json:"active"`
    Name   *string `json:"name"`
}

func patchUser(c *gin.Context) {
    var req PatchUser
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    if req.Age != nil {
        if *req.Age < 0 {
            c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "age must be non-negative"})
            return
        }
        // Apply *req.Age, including 0.
    }
    if req.Active != nil {
        // Apply *req.Active, including false.
    }
    if req.Name != nil {
        // Apply *req.Name if the API permits an empty string.
    }
}

This is an implementation pattern, not a tested complete handler; add the imports, persistence logic, and field-specific rules your endpoint needs. The key is to check presence first, validate the supplied concrete value, and apply it only when present. Do not treat a supplied zero as absence.

Decide what JSON null means

A pointer field generally does not distinguish an omitted property from a property supplied as null; both result in nil. Choose and document the endpoint’s contract rather than letting decoding behavior decide it accidentally.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 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.
  • Null means no change: a pointer DTO is suitable; nil covers both omission and null.
  • Null is invalid: use presence-aware decoding or a custom optional type so you can reject null instead of treating it as omission.
  • Null clears the value: represent three states—omitted (leave unchanged), null (clear), and concrete value (set). A custom optional type or decoding the object into map[string]json.RawMessage before typed value handling can preserve this distinction.

The Go JSON decoder’s behavior and the fact that marshaling options do not report incoming member presence are described in the Go encoding/json documentation.

Validate supplied fields without rejecting valid zeroes

Keep presence checks separate from value rules. For example, a supplied age can be checked for a non-negative value even when it is zero; a supplied boolean can be false; and a supplied string can be empty if the API permits it. The same pattern applies to nested or more complex fields: first determine whether the client supplied the field, then validate its value according to the endpoint’s contract.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • 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.

Validator tag names can be easy to confuse because they operate in different contexts:

  • json:",omitempty" affects JSON encoding output; it is not a request-presence rule.
  • binding:"required" rejects the type’s zero value, so it is usually wrong for optional PATCH scalars where zero is meaningful.
  • Validator’s omitempty skips subsequent validation when the validator considers a field unset. It is distinct from the JSON option with the same name.
  • omitnil skips checks for nil values. omitzero skips zero values, including a pointer’s pointed-to zero, so it is unsuitable when an explicit zero must be validated or applied.

Gin supports custom validation functions and struct-level validation for reusable rules; presence semantics still need to be represented correctly in the request type. See Gin’s custom validator documentation and validator’s tag documentation.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • 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
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the representation that matches the contract

Approach Presence and null states Zero-value handling Best fit
Plain scalar field (int, bool, string) Cannot distinguish omitted from a supplied zero after ordinary decoding. Zero, false, and empty string are indistinguishable from omission. Not suitable by itself when PATCH must preserve explicit zero values.
Pointer field Distinguishes a decoded value from nil; does not inherently distinguish omission from JSON null. Non-nil pointer preserves explicit zero, false, or empty string. Simple typed DTO when null is equivalent to omission or is not a supported clearing operation.
Custom optional type or raw-key parsing Can represent omitted, null, and concrete value separately if implemented to preserve all three states. Can preserve and validate explicit zero values. APIs where null has a distinct meaning, such as clearing a field or returning a validation error.

Use ShouldBindJSON to control API errors

Gin’s ShouldBindJSON returns a binding or validation error to the handler, allowing the API to choose the response and error body. By contrast, BindJSON aborts the request and writes a 400 response on binding errors. For an endpoint with deliberate 400 versus 422 behavior, use ShouldBindJSON and make that decision explicitly. Gin’s binding documentation also shows how a missing field tagged binding:"required" produces a validation error, which is a useful distinction between a create DTO and a partial-update DTO.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 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.

PATCH validation checklist

  • Omitted field: leave the stored value unchanged.
  • Explicit 0, false, or "": preserve it as supplied and apply the field’s own validation rules.
  • null: follow the documented contract—ignore, reject, or clear.
  • Malformed JSON: return a deliberate client error from the binding failure path.
  • Invalid supplied value: return the endpoint’s chosen validation response without confusing it with omission.

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.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.