英文:
Argument Processing in golang
问题
我将把以下内容翻译为中文:
我将使用以下命令来运行我的Go程序。
go run app.go 3001-3005
这个命令的作用是在服务器端口3001到3005上运行我的Go Rest API。
这是处理该参数的主要函数的一部分。
func main() {
ipfile := os.Args[1:]
s := strings.Split(ipfile, "-")
mux := routes.New()
mux.Put("/:key1/:value1", PutData)
mux.Get("/profile/:key1", GetSingleData)
mux.Get("/profile", GetData)
http.Handle("/", mux)
for i := range s {
http.ListenAndServe(":"+s[i], nil)
}
}
我得到以下输出:
cannot use ipfile (type []string) as type string in argument to strings.Split
os.Args返回的是什么数据类型?
我尝试将其转换为字符串然后进行拆分,但不起作用。
请告诉我问题出在哪里?
英文:
I will be giving the following as the command to run my go program.
> go run app.go 3001-3005
What this is supposed to do is, run my go Rest api on server ports 3001 to 3005.
This part of my main function which handles this argument.
func main() {
ipfile := os.Args[1:]
s := strings.Split(ipfile, "-")
mux := routes.New()
mux.Put("/:key1/:value1", PutData)
mux.Get("/profile/:key1", GetSingleData)
mux.Get("/profile", GetData)
http.Handle("/", mix)
Here I will run a for loop and replace the first argument with s[i].
http.ListenAndServe(":3000", nil)
}
I get the following output:
cannot use ipfile (type []string) as type string in argument to strings.Split
What datatype does os.args return?
I tried converting it to string and then splitting. Does not work.
Please let me know what is wrong?
答案1
得分: 4
根据错误提示,ipfile
是一个 []string
类型。即使只有一个元素,[1:]
切片操作也会返回一个切片。
在检查 os.Args
是否有足够的元素后,可以使用以下代码:
ipfile := os.Args[1]
s := strings.Split(ipfile, "-")
英文:
Like the error says, ipfile
is a []string
. The [1:]
slice operation is going to return a slice, even if there's only 1 element.
After checking that os.Args
has the enough elements, use:
ipfile := os.Args[1]
s := strings.Split(ipfile, "-")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论