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

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

curl command return 404 when using os/exec

问题

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

func Test_curl(t *testing.T) {
	cmd := exec.Command(
		`curl`,
		`-H`, `PRIVATE-TOKEN:token`,
		`https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw\?ref\=master`,
	)
	t.Log(cmd.String())

	var out bytes.Buffer
	cmd.Stdout = &out

	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
	t.Log(out.String())
}
=== RUN   Test_curl
    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
    t_test.go:175: {"error":"404 Not Found"}
--- PASS: Test_curl (0.25s)

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

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

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

英文:

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

func Test_curl(t *testing.T) {
	cmd := exec.Command(
		`curl`,
		`-H`, `PRIVATE-TOKEN:token`,
		`https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw\?ref\=master`,
	)
	t.Log(cmd.String())

	var out bytes.Buffer
	cmd.Stdout = &out

	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
	t.Log(out.String())
}

=== RUN   Test_curl
    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
    t_test.go:175: {"error":"404 Not Found"}
--- PASS: Test_curl (0.25s)

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

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

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

答案1

得分: 1

?=不需要加引号:

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

exec.Command不会生成一个shell因此不需要转义shell通配符
英文:

? and = must not be quoted:

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

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:

确定