【问题标题】:How to get Go Flag package to accept a flag name of the form --telemetry.addr如何让 Go Flag 包接受形式为 --telemetry.addr 的标志名称
【发布时间】:2020-10-07 22:46:40
【问题描述】:

我需要编写一段代码,它将接受参数“--telemetry.addr=8080”和“--telemetry.path=/metrics”,具体格式如下。

我的代码:

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))
}

给我输出:

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

无论我对 flag.String 行做什么,我似乎都无法欺骗它接受以“--”开头的内容

【问题讨论】:

标签: go command-line go-flag


【解决方案1】:

标志参数不接受“-”。你应该做的是从标志调用中删除连字符

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.")

您可以通过添加如下所示的双连字符来执行您的二进制文件

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    相关资源
    最近更新 更多