Search code examples
gocommand-linego-flag

How to get Go Flag package to accept a flag name of the form --telemetry.addr


I need to write a piece of code that will take in the arguments "--telemetry.addr=8080" and "--telemetry.path=/metrics", formatted specifically like this.

My code:

package main

import (
    "flag"
    "fmt"
    "net/http"
    "os"

    "github.com/prometheus/client_golang/prometheus/promhttp"
    "github.com/prometheus/common/log"
)

var portNumber = flag.String("-telementry.addr", "8080", "a string denoting what port number the data should be accessible at.")
var endpoint = flag.String("-telemetry.path", "/metrics", "a string denoting what endpoint the data should be accessible at.")

func main() {
    log.Info(os.Args[1])
    log.Info(os.Args[2])
    flag.Parse()

    http.Handle("/"+*endpoint, promhttp.Handler())
    log.Info("Endpoint set to " + *endpoint)
    log.Info("Beginning to serve on port :" + *portNumber)

    fmt.Printf("Test %s %s", *endpoint, *portNumber)

    log.Fatal(http.ListenAndServe(":"+*portNumber, nil))
}

gives me the output:

JORDYT-MBP:array-exporter jordy$ go run array-exporter.go --telemetry.addr=8080 --telemetry.path=/metrics
INFO[0000] --telemetry.addr=8080                         source="array-exporter.go:17"
INFO[0000] --telemetry.path=/metrics                     source="array-exporter.go:18"
flag provided but not defined: -telemetry.addr
Usage of /var/folders/mv/466rq_qj7zj9ywd11w4t8wc00000gp/T/go-build765060090/b001/exe/array-exporter:
  --telementry.addr string
        a string denoting what port number the data should be accessible at. (default "8080")
  --telemetry.path string
        a string denoting what endpoint the data should be accessible at. (default "/metrics")
exit status 2

No matter what I do to the flag.String line, I can't seem to trick it into accepting something that starts with "--"


Solution

  • The flag arguments do not accept "-". What you should do is to remove the hyphen from the flag call

    var portNumber = flag.String("telemetry.addr", "8080", "a string denoting what port number the data should be accessible at.")
    var endpoint = flag.String("telemetry.path", "/metrics", "a string denoting what endpoint the data should be accessible at.")
    

    You can execute your binary by adding double hyphen like below

    go build --telemenary.addr=8080 --telemetry.path=metrics