英文:
list OrientDb databases using HTTP protocol and golang
问题
我正在尝试使用HTTP协议获取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
}
英文:
I am trying to get a list of OrientDb
databases using HTTP protocol. But I cannot get expected response, which I can get in a browser.
If I input in a browser address line http://localhost:2480/listDatabases
then I have
response:
{"@type":"d","@version":0,"databases":["MaximDB","GratefulDeadConcerts"],"@fieldTypes":"databases=e"}
How can I get the same using golang
?
My code:
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
}
It outputs in console:
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
}
答案1
得分: 2
您的请求是正确的,问题在于您尝试打印响应的方式。
您将整个响应对象转换为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
表示包括正文,否则只会显示状态和头信息)
英文:
Your request is fine, it's the way you're trying to print out the response.
You're marshaling the entire response object to JSON and you can see the "Body": {},
where your body is missing. A *http.Response
won't marshal to JSON the way you want. This is because the Body
field is not just a string
or []bytes
, it's an io.ReadCloser
and the JSON marshaling code isn't going to call .Read
on it.
Try one of these to just get the response body
var b bytes.Buffer
_, err = b.ReadFrom(resp.Body)
if err != nil {
log.Fatal("Error : %s", err)
}
fmt.Println(b.String())
or
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("Error : %s", err)
}
fmt.Println(string(contents))
Or to get the extra response meta information you could do this
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
log.Fatal("Error : %s", err)
}
fmt.Println(string(dump))
(The second flag the true
says to include the body, otherwise it would just show status and headers)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论