dpj775835868
dpj775835868
2018-01-02 14:20

导入Vault / builtin / credential / aws会将测试标记添加到命令行应用程序

已采纳

I'm creating a quick and dirty Go app to pull application secrets from Vault, and authenticating using the Vault code itself. As part of this, I'm importing the aws credential module from github.com/hashicorp/vault/builtin/credential/aws. This is all working well.

However when running my app, I notice that the command line flags from the Go "testing" module are appearing in the flags.

This can be reproduced by compiling and running the following example script:

package main

import (
    "flag"
    _ "github.com/hashicorp/vault/builtin/credential/aws"
    // Note: this import is masked only to make this demo script compile.
    // In my actual code I need to use it, and it is not masked.
)

var myFlag string

func main() {
    flag.StringVar(
        &myFlag, "myFlag", "", "Test flag",
    )
    flag.Parse()
    flag.Usage()
}

The flags appear like so when calling the binary:

Usage of poc:
  -myFlag string
        Test flag
  -test.bench regexp
        run only benchmarks matching regexp
  -test.benchmem
        print memory allocations for benchmarks
  -test.benchtime d
        run each benchmark for duration d (default 1s)
  -test.blockprofile file
        write a goroutine blocking profile to file
  -test.blockprofilerate rate
        set blocking profile rate (see runtime.SetBlockProfileRate) (default 1)
  -test.count n
        run tests and benchmarks n times (default 1)
  [... more flags from the go testing module ...]

I'm a newbie to Go, so it's entirely possible I'm doing something I'm not supposed to here, but at first glance it seems reasonable to import this module for a command-line tool.

As far as I can see, nothing within the module uses the testing library (other than backend_test.go), so I'm a bit confused as to how these flags are appearing, especially as they don't appear in the Vault command line interface itself.

Is it possible to import and use Vault's credential/aws module without including these flags? Or somehow clear the testing flags before defining my own?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duankang5285 duankang5285 3年前

    That is because even though you use _ to mask github.com/hashicorp/vault/builtin/credential/aws, the import auctually happened. And the package imported testing, which generate all these flags.

    You can get rid of the testing flags by using a new FlagSet.

    func main() {
        f:=flag.NewFlagSet("Your app name",flag.ExitOnError)
        f.StringVar(
            &myFlag, "myFlag", "", "Test flag",
        )
        f.Parse(os.Args)
        f.Usage()
    }
    

    Playground: https://play.golang.org/p/O8ibPn77L46

    点赞 评论 复制链接分享