Search code examples
functiongogo-flag

Golang execute function using flags


How can I execute a specific function by entering a flag, for example, I have three flags:

    wordPtr
    numbPtr
    forkPtr

And when executing a single one, the function that calls is executed:

.\data -wordPtr Test

When executing that flag, only the word function is executed:

package main

import (
    "flag"
    "fmt"
)

var (
    wordPtr string
    numbPtr int
    forkPtr bool
)

func main() {

    flag.StringVar(&wordPtr, "word", "foo", "a string")
    flag.IntVar(&numbPtr, "numb", 42, "an int")
    flag.BoolVar(&forkPtr, "fork", false, "a bool")
    flag.Parse()

    if wordPtr != `` {
        word(wordPtr)
    }

    if numbPtr != 0 {
        numb(numbPtr)
    }

    if forkPtr {
        fork(forkPtr)
    }

}

func word(word string) {
    fmt.Println("word:", word)
}

func numb(numb int) {
    fmt.Println("numb:", numb)
}

func fork(fork bool) {
    fmt.Println("fork:", fork)
}

But, when I execute the last flag, all functions are executed

PS C:\golang> .\logdata.exe -fork
word: foo
numb: 42      
fork: true    
PS C:\golang> 

Do you know why?


Solution

  • You provide default values for the word and numb flags, which means if you don't provide them as cli arguments, they will get the default value.

    And after flag.Parse() you only test if wordPtr is not empty or numbPtr is not 0, and since the default values are not these, the tests will pass and the functions will be executed.

    If you use the empty string and 0 as the defaults:

    flag.StringVar(&wordPtr, "word", "", "a string")
    flag.IntVar(&numbPtr, "numb", 0, "an int")
    

    Then if you don't provide these as cli arguments, your tests will not pass:

    .\logdata.exe -fork
    

    Will output:

    fork: true
    

    If you want to test if word or numb was provided as cli arguments, see Check if Flag Was Provided in Go.