提前感谢您,因为我花了2天时间。这是一个有效的curl命令。
curl -ku login:pass -X POST -H 'Content-Type: application/json'-d'{"type":"page","title":"Testpage","space":{"key":"ITDept"},"body":{"storage":{"value":"<p>Blank Page.</p>","representation":"storage"}}}' https://confluence/rest/api/content
我需要使用exec.Command执行此操作。
鉴于现在我已经尝试了逃避和各种其他方法来实现这一点。问题很可能是这个荒谬的JSON字符串。我现在将JSON字符串保存到var中以便这样尝试。
jsonPayload := '{"type":"page","title":"Testpage","space":{"key":"ITDept"},"body":{"storage":{"value":"<p>Blank Page.</p>","representation":"storage"}}}'
execCmd := "bash", "-c", "curl -ku login:pass -X POST -H 'Content-Type: application/json' -d" jsonPayload "https://confluence/rest/api/content"
所以jsonPayload是-d的参数。我已经使用Marshal json / encoding和net / http包尝试了这个,但它经历了一些关于stdlib如何发送它的原因导致API声明它是错误的格式。
我也尝试过这个,并且从println中复制出来的curl可以正常工作,但是当实际在golang中运行时,它的格式不正确。
env := os.Environ()
curlCmd, err := exec.LookPath("curl")
if err != nil {
fmt.Println("Path not found to binary!")
panic(err)
}
args := []string{"curl", "-ku", "login:pass", "-X", "POST", "-H", "'Content-Type: application/json'", "-d", payloadJson, "https://confluence/rest/api/content"}
execErr := syscall.Exec(curlcmd, args, env)
if execErr != nil {
panic(execErr)
}
fmt.Println(curlCmd)
当来自最后一行的curlCmd打印出来时,它可以被复制并粘贴到终端中,但是当它通过golang时它会带有不支持的格式。任何帮助将不胜感激。
答案 0 :(得分:1)
试试这个:
payload := `{"type":"page","title":"Testpage","space":{"key":"ITDept"},"body":{"storage":{"value":"<p>Blank Page.</p>","representation":"storage"}}}`
cmd := exec.Command("curl", "-ku", "login:pass", "-X", "POST", "-H", "Content-Type: application/json", "-d", payload, "http://localhost:8080/confluence/rest/api/content")
p, err := cmd.CombinedOutput()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", p)
问题中代码的重要更改:
顺便说一下,您还可以使用解释的字符串文字:
payload := "{\"type\":\"page\",\"title\":\"Testpage\",\"space\":{\"key\":\"ITDept\"},\"body\":{\"storage\":{\"value\":\"<p>Blank Page.</p>\",\"representation\":\"storage\"}}}"