dongpin1059 2018-04-05 16:34
浏览 4
已采纳

前往:从文件中读取命令行标志

When creating a command line program in Go, is there a way (either provided by the core libraries, or a widely accepted practice) to implement a command line flag that reads its contents from a file?

If that's not clear, I'm thinking of something like the @ symbol in the command line curl program. Many of curl's arguments allow you to do something like this to read a flag's value in from a file

# setting the value 
curl --data-binary '{...}' http://example.com

# setting the value by reading from a file
curl --data-binary @path/to/data.txt http://example.com  

Does go have any code for automatically implementing these sorts of flags? I've read through the official docs and didn't see anything obvious, but I'm still getting the hang of navigating those docs.

If there's nothing official, is there a de-facto standard "better flags" library provided by someone in the go community that includes this functionality?

Or is it down to an individual programmer to create a string flag, scan it for the @, and handle reading the file's contents in myself?

  • 写回答

1条回答 默认 最新

  • douyue1481 2018-04-05 16:50
    关注

    flag.Value allows you to implement arbitrary flag behaviour:

    package main
    
    import (
            "flag"
            "fmt"
            "io/ioutil"
            "strings"
    )
    
    type T string
    
    // String implements flag.Value
    func (t *T) String() string {
            return string(*t)
    }
    
    // Set implements flag.Value
    func (t *T) Set(maybeFilename string) error {
            if !strings.HasPrefix(maybeFilename, "@") {
                    *t = T(maybeFilename)
                    return nil
            }
    
            filename := maybeFilename[1:]
            b, err := ioutil.ReadFile(filename)
            if err != nil {
                    return err
            }
    
            *t = T(string(b))
            return nil
    }
    
    func main() {
            var t T
            flag.Var(&t, "data-binary", "(description)")
            flag.Parse()
            fmt.Println(t)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里