struct-to-pflags

command module
v0.0.0-...-9a993ed Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 16 Imported by: 0

README

Installation

go install github.com/kr3v/struct-to-pflags@latest

Example

Given:

//go:generate struct-to-pflags -file=config.go -struct=config -output=config.gen.go

package example

type config struct {
	// path to file where logs will be written
	logFile string
	// enable debug mode
	debug bool
	// port number to listen on
	port int
	// internal version field
	version string `pflags:"-"`
}

var defaultConfig = config{
	logFile: "/var/log/app.log",
	debug:   false,
	port:    8080,
	version: "v1.0.0",
}

Generates:

// Code generated by struct-to-pflags; DO NOT EDIT.

package example

import (
	"github.com/spf13/pflag"
)

const (
	flagLogFile = "log-file"
	flagDebug   = "debug"
	flagPort    = "port"
)

func withConfigFlags(flags *pflag.FlagSet) {
	flags.String(flagLogFile, defaultConfig.logFile, "path to file where logs will be written")
	flags.Bool(flagDebug, defaultConfig.debug, "enable debug mode")
	flags.Int(flagPort, defaultConfig.port, "port number to listen on")
}

func loadConfig(flags *pflag.FlagSet, version string) (*config, error) {
	logFile, err := flags.GetString(flagLogFile)
	if err != nil {
		return nil, err
	}

	debug, err := flags.GetBool(flagDebug)
	if err != nil {
		return nil, err
	}

	port, err := flags.GetInt(flagPort)
	if err != nil {
		return nil, err
	}

	return &config{
		logFile: logFile,
		debug:   debug,
		port:    port,
		version: version,
	}, nil
}

Check example.

Linter

struct-to-pflags validate-rec -dir <directory>

Looks for all the go:generate directives in the specified directory (recursively) and validates the generated files against the source structs.

Check validate-rec-output for an example output.

$ struct-to-pflags validate-rec -dir=./example >./example/validate-rec-output 2>&1; echo "exit_code =" $? >> ./example/validate-rec-output

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL