使用HTTP协议和golang列出OrientDb数据库

时间:2015-06-05 18:30:01

标签: go orientdb

我正在尝试使用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
}

1 个答案:

答案 0 :(得分: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表示包含正文的第二个标记,否则只会显示状态和标题)