登录
首页 >  Golang >  Go问答

如何过滤掉 Gerrit JSON api 响应的前几个坏字符

来源:stackoverflow

时间:2024-04-20 14:27:36 465浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《如何过滤掉 Gerrit JSON api 响应的前几个坏字符》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

在查询 gerrit 时,他们故意在 api 响应的开头放置了 )]}',请参阅:https://gerrit-review.googlesource.com/documentation/rest-api-changes.html。我正在尝试删除它,以便 json 有效,但我不确定在 go 中执行此操作的最佳方法

这是我当前的程序,用于查询 gerrit 并从其 json 中提取 changeid 和状态:

package main

import (
    "encoding/json"
    "flag"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type gerritData struct {
    ChangeID string `json:"change_id"`
    Status   string `json:"status"`
}

func gerritQuery(gerrit string) (gerritData, error) {
    username := "redacted"
    password := "redacted"
    client := &http.Client{}
    req, err := http.NewRequest("GET", "https://gerrit.company.com/a/changes/?q="+gerrit, nil)
    req.SetBasicAuth(username, password)

    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }

    respBody, err := ioutil.ReadAll(resp.Body)

        // Trying to cut it out manually.
    respBody = respBody[:len(respBody)-4]

    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    var gerritResponse gerritData
    if err := json.NewDecoder(resp.Body).Decode(&gerritResponse); err != nil {
        panic(err.Error())
    }

    return gerritResponse, nil
}

func main() {
    gerritFlag := flag.String("gerrit", "foo", "The Gerrit you want to query")
    flag.Parse()

    gerritResponse, _ := gerritQuery(*gerritFlag)

    fmt.Println(gerritResponse)
}

go 仍在抱怨 panic:无效字符 ')' 正在寻找 value 的开头。我对这门语言还很陌生,所以任何建议都会很好。


解决方案


问题中的代码从响应末尾删除了四个字节。

从响应开头修剪字节:

respBoby = respBody[4:]

本篇关于《如何过滤掉 Gerrit JSON api 响应的前几个坏字符》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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