【问题标题】:docopt.go weird error messagedocopt.go 奇怪的错误信息
【发布时间】:2015-01-30 13:58:33
【问题描述】:

使用 docopt.go 重构旧项目并最小化代码,程序看起来像这样

package main

import (
    "fmt"
    "github.com/docopt/docopt.go"
)

const Version = `2.0`
const Usage = `
Usage:
    serve [--port] <dir>
    serve help | --help
    serve --version 

Options:
    -p, --port       port for the sever to listen on
    -h, --help       display help information
    -v, --version    display Version
`

func check(err error) {
    if err != nil {
        panic(err)
    }
}

func main() {
    args, err := docopt.Parse(Usage, nil, true, Version, false)
    check(err)

    port := args["[--port]"].(string)

    fmt.Println(args)
    fmt.Println(port)v
}

但是,当我运行程序 go run ./serve.go help 期待帮助消息时,我得到了这个

panic: interface conversion: interface is nil, not string

goroutine 1 [running]:
main.main()
    /Users/jburns/Development/Gopath/src/github.com/nyumal/serve/serve.go:31 +0x148

goroutine 2 [runnable]:
runtime.forcegchelper()
    /usr/local/Cellar/go/1.4.1/libexec/src/runtime/proc.go:90
runtime.goexit()
    /usr/local/Cellar/go/1.4.1/libexec/src/runtime/asm_amd64.s:2232 +0x1

goroutine 3 [runnable]:
runtime.bgsweep()
    /usr/local/Cellar/go/1.4.1/libexec/src/runtime/mgc0.go:82
runtime.goexit()
    /usr/local/Cellar/go/1.4.1/libexec/src/runtime/asm_amd64.s:2232 +0x1

goroutine 4 [runnable]:
runtime.runfinq()
    /usr/local/Cellar/go/1.4.1/libexec/src/runtime/malloc.go:712
runtime.goexit()
    /usr/local/Cellar/go/1.4.1/libexec/src/runtime/asm_amd64.s:2232 +0x1
exit status 2

并运行go run ./serve.go --port 5000 它返回相同的东西但是运行go run ./serve.go --port 5000 . 返回

Usage:
    serve [--port] <dir>
    serve help | --help
    serve --version
exit status 1

我哪里做错了?

【问题讨论】:

    标签: go command-line-interface docopt


    【解决方案1】:

    你需要为端口声明一个参数:

    const Usage = `
    Usage:
        serve [--port=<arg>] <dir>
        serve help | --help
        serve --version 
    
    Options:
        -p, --port=<arg> port for the sever to listen on
        -h, --help       display help information
        -v, --version    display Version
    

    使用二值类型断言处理未设置端口的情况:

    port, ok := args["--port"].(string)
    if ok {
       // port is set
    }
    

    另外,删除地图键周围的“[]”。

    【讨论】:

      猜你喜欢
      • 2012-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 2011-01-01
      • 1970-01-01
      • 2017-12-04
      相关资源
      最近更新 更多