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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么