curl命令在使用os/exec时返回404错误。

huangapple go评论121阅读模式
英文:

curl command return 404 when using os/exec

问题

我尝试使用os/execcurl从私有的gitlab仓库获取文件,但是得到了404的响应状态:

  1. func Test_curl(t *testing.T) {
  2. cmd := exec.Command(
  3. `curl`,
  4. `-H`, `PRIVATE-TOKEN:token`,
  5. `https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw\?ref\=master`,
  6. )
  7. t.Log(cmd.String())
  8. var out bytes.Buffer
  9. cmd.Stdout = &out
  10. err := cmd.Run()
  11. if err != nil {
  12. t.Fatal(err)
  13. }
  14. t.Log(out.String())
  15. }
  1. === RUN Test_curl
  2. t_test.go:166: /usr/bin/curl -H PRIVATE-TOKEN:token https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw\?ref\=master
  3. t_test.go:175: {"error":"404 Not Found"}
  4. --- PASS: Test_curl (0.25s)

但是当我尝试从zsh中使用相同的命令时,我得到了正确的响应:

  1. % /usr/bin/curl -H PRIVATE-TOKEN:token https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw\?ref\=master
  1. .DS_Store
  2. .vs/
  3. .vscode/
  4. .idea/

我认为问题出在URL上,但不知道如何修复它。

英文:

I try to get file from private gitlab repository using os/exec with curl and get 404 response status:

  1. func Test_curl(t *testing.T) {
  2. cmd := exec.Command(
  3. `curl`,
  4. `-H`, `PRIVATE-TOKEN:token`,
  5. `https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw\?ref\=master`,
  6. )
  7. t.Log(cmd.String())
  8. var out bytes.Buffer
  9. cmd.Stdout = &out
  10. err := cmd.Run()
  11. if err != nil {
  12. t.Fatal(err)
  13. }
  14. t.Log(out.String())
  15. }
  1. === RUN Test_curl
  2. t_test.go:166: /usr/bin/curl -H PRIVATE-TOKEN:token https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw\?ref\=master
  3. t_test.go:175: {"error":"404 Not Found"}
  4. --- PASS: Test_curl (0.25s)

but when I try to use the same command from zsh, I get right response:

  1. % /usr/bin/curl -H PRIVATE-TOKEN:token https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw\?ref\=master
  1. .DS_Store
  2. .vs/
  3. .vscode/
  4. .idea/

I think the problem in the url, but don't understand how to fix one.

答案1

得分: 1

?=不需要加引号:

  1. cmd := exec.Command(
  2. "curl",
  3. "-H", "PRIVATE-TOKEN:token",
  4. "https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw?ref=master",
  5. )
  6. exec.Command不会生成一个shell因此不需要转义shell通配符
英文:

? and = must not be quoted:

  1. cmd := exec.Command(
  2. `curl`,
  3. `-H`, `PRIVATE-TOKEN:token`,
  4. `https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw?ref=master`,
  5. )

exec.Command does not spawn a shell, therefore shell globs do not need escaping.

huangapple
  • 本文由 发表于 2023年1月2日 20:17:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/74982330.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定