登录
首页 >  Golang >  Go问答

如何在发送POST请求前移除反斜杠?

来源:stackoverflow

时间:2024-02-06 13:39:22 422浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《如何在发送POST请求前移除反斜杠?》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

我正在编写一个发送 post 请求的程序,该请求的正文需要纯文本中的双引号。因为每次发送请求时我都会使用 fmt.sprintf 注入变量,所以在发送请求时我使用字符串文字

func searchlocalimage(imagename, imagetag, artifactoryusername, artifactorypassword string) (localimagerepo string) {
    a := types.artifactoryclient{
        url:      "",
        username: artifactoryusername,
        password: artifactorypassword,
        client:   resty.new(),
    }
    var responsebody map[string]interface{}

    url := a.url + "/search/aql"
    res, _ := a.client.r().
        setheader("content-type", "text/plain").
        setbasicauth(a.username, a.password).
        setbody(fmt.sprintf(`items.find({"$and": [{"repo":{"$match":""}},{"path": {"$match":"%s/%s"}},{"name":{"$match":""}}]}).include("repo","path","name")`, imagename, imagetag)).
        post(url)

当然,这会自动将转义字符注入返回的字符串。

"items.find({\"$and\": [{\"repo\":{\"$match\":\"\"}},{\"path\": {\"$match\":\"\"}},{\"name\":{\"$match\":\"\"}}]}).include(\"repo\",\"path\",\"name\")"

不幸的是,这会导致响应成为错误消息。有没有人找到一种方法可以按照我需要的方式发送这样的请求,而无需发送这些反斜杠?


正确答案


当然,这会自动将转义字符注入返回的字符串。

不,这不是真的。您会看到转义字符,因为您使用的工具(很可能是调试器)将内容显示为带引号的字符串。

您可以简单地转储请求以查看发送的内容。并将转储内容粘贴到 insomnia 中以找出问题所在。

package main

import (
    "fmt"
    "net/http"
    "net/http/httptest"
    "net/http/httputil"

    "github.com/go-resty/resty/v2"
)

func main() {
    ts := httptest.newserver(http.handlerfunc(func(w http.responsewriter, r *http.request) {
        buf, err := httputil.dumprequest(r, true)
        if err != nil {
            panic(err)
        }

        fmt.printf("%s\n", buf)
    }))
    defer ts.close()

    client := resty.new()

    imagename := "image name"
    imagetag := "image tag"
    _, err := client.r().
        setheader("content-type", "text/plain").
        setbasicauth("", "").
        setbody(fmt.sprintf(`items.find({"$and": [{"repo":{"$match":""}},{"path": {"$match":"%s/%s"}},{"name":{"$match":""}}]}).include("repo","path","name")`, imagename, imagetag)).
        post(ts.url)
    if err != nil {
        panic(err)
    }
}
POST / HTTP/1.1
Host: 127.0.0.1:41937
Accept-Encoding: gzip
Authorization: Basic PHVzZXJuYW1lPjo8cGFzc3dvcmQ+
Content-Length: 156
Content-Type: text/plain
User-Agent: go-resty/2.7.0 (https://github.com/go-resty/resty)

items.find({"$and": [{"repo":{"$match":""}},{"path": {"$match":"image name/image tag"}},{"name":{"$match":""}}]}).include("repo","path","name")

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>