在 vanilla go 中,设置环境变量似乎很简单。该os
库具有Setenv
应该完成工作的功能。我在 cobra 命令中遇到了麻烦。有没有我遗漏的简单方法,或者目前不支持此功能?
我正在尝试做的示例:
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"k8s.io/cli-runtime/pkg/genericclioptions"
)
func main() {
flags := pflag.NewFlagSet("ex-com", pflag.ExitOnError)
pflag.CommandLine = flags
root := newCmdEx(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr})
if err := root.Execute(); err != nil {
fmt.Fprintf(os.Stdout, "Error: %[1]s", err.Error())
os.Exit(1)
}
os.Exit(0)
}
type ExOpOptions struct {
configFlags genericclioptions.ConfigFlags
}
func NewExOpOptions(streams genericclioptions.IOStreams) *ExOpOptions {
return &ExOpOptions{}
}
func newCmdEx(streams genericclioptions.IOStreams) *cobra.Command {
o := NewExOpOptions(streams)
cmd := &cobra.Command{
RunE: func(c *cobra.Command, args []string) error {
return o.Run()
},
}
o.configFlags.AddFlags(cmd.Flags())
return cmd
}
func (o *ExOpOptions) Run() error {
return os.Setenv("THEBESTOFTIMES", "Sure it was.")
}
示例构建和测试脚本:
GO111MODULE="on" go build cmd/ex-com.go && \
echo "First Print:" && \
echo "$THEBESTOFTIMES" && \
./ex-com && \
echo "Second Print:" && \
echo "$THEBESTOFTIMES"
我希望输出看起来像这样(因为环境变量是在 go 代码的第 48 行设置的):
go: finding k8s.io/cli-runtime/pkg/genericclioptions latest
go: finding k8s.io/cli-runtime/pkg latest
go: finding k8s.io/cli-runtime latest
First Print:
Second Print:
Sure it was.
但目前它看起来像这样:
go: finding k8s.io/cli-runtime/pkg/genericclioptions latest
go: finding k8s.io/cli-runtime/pkg latest
go: finding k8s.io/cli-runtime latest
First Print:
Second Print: