gpt4 book ai didi

go - 使用 HTTP 协议(protocol)和 golang 列出 OrientDb 数据库

转载 作者:IT王子 更新时间:2023-10-29 01:42:40 26 4
gpt4 key购买 nike

我正在尝试使用 HTTP 协议(protocol)获取 OrientDb 数据库的列表。但是我无法得到预期的响应,我可以在浏览器中获得。

如果我在浏览器地址行中输入 http://localhost:2480/listDatabases 那么我有回应:

{"@type":"d","@version":0,"databases":["MaximDB","GratefulDeadConcerts"],"@fieldTypes":"databases=e"}

如何使用 golang 获得相同的结果?

我的代码:

package main

import (
"encoding/json"
"fmt"
"net/http"
)

func main() {
client := &http.Client{}
req, err := http.NewRequest("GET", "http://localhost:2480/listDatabases", nil)
req.SetBasicAuth("root", "1")
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Error : %s", err)
}
fmt.Println("resp")
fmt.Println(ToJson(resp))
}

func ToJson(obj interface{}) string {
b, err := json.MarshalIndent(&obj, "", " ")
if err != nil {
fmt.Printf("Error : %s", err)
}
strJson := string(b)

return strJson
}

控制台输出:

resp
{
"Status": "200 OK",
"StatusCode": 200,
"Proto": "HTTP/1.1",
"ProtoMajor": 1,
"ProtoMinor": 1,
"Header": {
"Connection": [
"Keep-Alive"
],
"Content-Type": [
"application/json; charset=utf-8"
],
"Date": [
"Fri Jun 05 22:19:23 MSK 2015"
],
"Etag": [
"0"
],
"Server": [
"OrientDB Server v.2.0.10 (build UNKNOWN@r; 2015-05-25 16:48:43+0000)"
],
"Set-Cookie": [
"OSESSIONID=-; Path=/; HttpOnly"
]
},
"Body": {},
"ContentLength": -1,
"TransferEncoding": null,
"Close": false,
"Trailer": null,
"Request": {
"Method": "GET",
"URL": {
"Scheme": "http",
"Opaque": "",
"User": null,
"Host": "localhost:2480",
"Path": "/listDatabases",
"RawQuery": "",
"Fragment": ""
},
"Proto": "HTTP/1.1",
"ProtoMajor": 1,
"ProtoMinor": 1,
"Header": {
"Authorization": [
"Basic cm9vdDox"
]
},
"Body": null,
"ContentLength": 0,
"TransferEncoding": null,
"Close": false,
"Host": "localhost:2480",
"Form": null,
"PostForm": null,
"MultipartForm": null,
"Trailer": null,
"RemoteAddr": "",
"RequestURI": "",
"TLS": null
},
"TLS": null
}

最佳答案

您的请求很好,这是您尝试打印响应的方式。

您正在将整个响应对象编码为 JSON,您可以看到 "Body": {}, 缺少您的正文。 *http.Response不会按照您想要的方式编码为 JSON。这是因为 Body 字段不仅仅是一个 string[]bytes,它是一个 io.ReadCloser。并且 JSON 编码代码不会对其调用 .Read

尝试其中之一来获取响应正文

var b bytes.Buffer
_, err = b.ReadFrom(resp.Body)
if err != nil {
log.Fatal("Error : %s", err)
}
fmt.Println(b.String())

contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("Error : %s", err)
}
fmt.Println(string(contents))

或者要获得额外的响应元信息,您可以这样做

dump, err := httputil.DumpResponse(resp, true)
if err != nil {
log.Fatal("Error : %s", err)
}
fmt.Println(string(dump))

(第二个标志 true 表示包含正文,否则它只会显示状态和标题)

关于go - 使用 HTTP 协议(protocol)和 golang 列出 OrientDb 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30673437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com