英文:
Equivalent to cat <<EOF in golang
问题
我正在尝试执行以下代码的等效操作:
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: ConfigMap
metadata:
name: testMap
namespace: default
data:
details:
host: "localhost:${reg_port}"
EOF
在golang中。
我目前的尝试可以简化为:
func generateConfig(port string) string {
return `
apiVersion: v1
kind: ConfigMap
metadata:
name: testMap
namespace: default
data:
details:
host: "localhost:" + port`
}
func main() {
exec.Command("kubectl", "apply", "-f", "-", generateConfig(5000))
}
我并不感到特别惊讶它没有起作用,出现了错误:
error: Unexpected args: [
apiVersion: v1
kind: ConfigMap
metadata:
name: testMap
namespace: default
data:
details:
host: "localhost:5000"]
我意识到我正在将它们作为参数传递,而kubectl期望一个文件,但我完全不知道如何继续下去。
我不想创建一个临时文件或调用一个单独的bash脚本,因为这似乎比我希望的更混乱。
英文:
I am trying to perform the equiavalent of this:
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: ConfigMap
metadata:
name: testMap
namespace: default
data:
details:
host: "localhost:${reg_port}"
EOF
in golang.
My current attempt boils down to:
func generateConfig(port string) string {
return `
apiVersion: v1
kind: ConfigMap
metadata:
name: testMap
namespace: default
data:
details:
host: "localhost:" + port`
}
func main() {
exec.Command("kubectl", "apply", "-f", "-", generateConfig(5000))
}
I was not particularly surprised to find it did not work, with error:
error: Unexpected args: [
apiVersion: v1
kind: ConfigMap
metadata:
name: testMap
namespace: default
data:
details:
host: "localhost:5000"]
I recognise that I am passing these as args and that kubectl expects a file, however I find myself at a complete loss at how I might continue.
I would rather not make a temporary file or call a separate bash script since this seems messier than I would hope is necessary.
答案1
得分: 5
这里是将命令的标准输入(stdin)设置为generateConfig函数结果的方法:
cmd := exec.Command("kubectl", "apply", "-f", "-")
cmd.Stdin = strings.NewReader(generateConfig("5000"))
if err := cmd.Run(); err != nil {
// 处理错误
}
在这里,shell的here document被重定向到命令的stdin。
英文:
The shell here document is directed to the command's stdin.
Here's how to set the command's stdin to the result of generateConfig:
cmd := exec.Command("kubectl", "apply", "-f", "-")
cmd.Stdin = strings.NewReader(generateConfig("5000"))
if err := cmd.Run(); err != nil {
// handle error
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论