How to ensure required fields in struct consistently?

This page summarizes the projects mentioned and recommended in the original post on /r/golang

Our great sponsors
  • WorkOS - The modern identity platform for B2B SaaS
  • InfluxDB - Power Real-Time Data Analytics at Scale
  • SaaSHub - Software Alternatives and Reviews
  • validator

    :100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving

  • Use https://github.com/go-playground/validator, which would just simply require you to add a tag to your struct for those fields.

  • semgrep

    Lightweight static analysis for many languages. Find bug variants with patterns that look like source code.

  • FWIW you can probably write a semgrep rule or something, to find all struct literals which don't mention a specific field.

  • WorkOS

    The modern identity platform for B2B SaaS. The APIs are flexible and easy-to-use, supporting authentication, user identity, and complex enterprise features like SSO and SCIM provisioning.

    WorkOS logo
  • mapstructure

    Go library for decoding generic map values into native Go structures and vice versa.

  • I'm doing it by validating a map[string]any first then putting it into a structure using mapstructure. It covers most use-cases and offers the most flexibility, at the expense of a bit of performance.

  • go-exhaustruct

    golang analyzer that finds structures with uninitialized fields

  • Have you consider adding a linter as part of you build process to detect those un-initialized fields? Like go-exhaustruct, (it's already included in golangci-lint if you use that already)

NOTE: The number of mentions on this list indicates mentions on common posts plus user suggested alternatives. Hence, a higher number means a more popular project.

Suggest a related project

Related posts