Skip to content

The good old getopt function as a Go iterator.

License

Notifications You must be signed in to change notification settings

koron-go/getopt

Repository files navigation

koron-go/getopt

PkgGoDev Actions/Go Go Report Card

Package getopt provides the good old getopt function as a Go iterator.

Getting started

Install and upgrade:

go get github.com/koron-go/getopt@latest

Short example:

package main

import (
	"log"
	"os"

	"github.com/koron-go/getopt"
)

func usage() {
	// TODO: Show usage and exit.
	os.Exit(1)
}

func main() {
	var bflag bool
	var file *os.File

	for opt, err := range getopt.Getopt(os.Args[1:], "bf:") {
		if err != nil {
			log.Fatalf("getopt failed: opt=%+v: %s", opt, err)
		}
		switch opt.Name {
		case 'b':
			bflag = true
		case 'f':
			f, err := os.Open(*opt.Arg)
			if err != nil {
				log.Fatalf("failed to open a file: %s", err)
			}
			defer f.Close()
			file = f
		default:
			usage()
		}
	}

	// TODO: Do your task with bflag, file, and getopt.RestArgs
	log.Printf("Do your task with bflag=%t f=%+v getopt.RestArgs=%+v", bflag, file, getopt.RestArgs)
}

About

The good old getopt function as a Go iterator.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published