douxian4376 2015-01-30 05:32
浏览 88
已采纳

docopt.go奇怪的错误消息

using docopt.go to refactor an old project and minimalise code the program looks like this

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
}

however when I run the program go run ./serve.go help expecting the help message i get this

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

and running go run ./serve.go --port 5000 it returns the same thing however running go run ./serve.go --port 5000 . return

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

where did i go wrong?

  • 写回答

1条回答 默认 最新

  • dongshi1880 2015-01-30 05:58
    关注

    You need to declare an argument for port:

    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
    

    Use the two value type assertion to handle the case where port is not set:

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

    Also, remove the "[]" from around the map key.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动