2014-01-30 62 views
1

你好,我在想,如果有一個簡單的方法來打印出更漂亮的結構體在golang如何訪問響應值

我想打印出請求的報頭

package main 

import (
    "fmt" 
    "net/http" 
    // "io/ioutil" 
    "io" 
    "os" 
) 

func main() { 

    resp, err := http.Get("http://google.com/") 
    if err != nil { 
     fmt.Println("ERROR") 
    } 
    defer resp.Body.Close() 
    fmt.Println(resp) 
    // body, err := ioutil.ReadAll(resp.Body) 
    out, err := os.Create("filename.html") 
    io.Copy(out, resp.Body) 

} 

和我得到以下

&{200 OK 200 HTTP/1.1 1 1 map[Date:[Thu, 30 Jan 2014 09:05:33 GMT] Content-Type:[text/html; charset=ISO-8859-1] P3p:[CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."] X-Frame-Options:[SAMEORIGIN] Expires:[-1] Cache-Control:[private, max-age=0] Set-Cookie:[PREF=ID=5718798ffa48c7de:FF=0:TM=1391072733:LM=1391072733:S=NNfE1JSHH---lqDV; expires=Sat, 30-Jan-2016 09:05:33 GMT; path=/; domain=.google.com NID=67=aIMpDPrQ5-lBg0_1jFBSmg7KUZPprzZ6Srgbd_CVSK63Ugf_Jr75KwUaALOrBkdpAdFN6O9L8TQd2ng-g_o7HqIS-Drt_XHPj17KkjayHJ7xqUDAlL3ySyJafmRcMRD5; expires=Fri, 01-Aug-2014 09:05:33 GMT; path=/; domain=.google.com; HttpOnly] Server:[gws] X-Xss-Protection:[1; mode=block] Alternate-Protocol:[80:quic]] 0xc200092b80 -1 [chunked] false map[] 0xc20009a750} 

這不是很明顯,這是什麼樣的結構,而且我怎麼可能在響應結構訪問各種值(我希望它的正確稱呼它一個struct)

回答

1

resp變量是一個struct(你正確:))。您需要resp.Header
resp.Header是具有字符串鍵和字符串值的映射。您可以輕鬆打印它。

例如:

for header, value := range resp.Header { 
    fmt.Println(header,value) 
} 

有用的東西:

  1. About header
  2. About response
1

有幾個漂亮的打印圖書館出來的第ERE。這是一個我真的喜歡:

https://github.com/davecgh/go-spew

允許你這樣做:

package main 

import (
    "fmt" 
    "net/http" 
    // "io/ioutil" 
    "io" 
    "os" 
    "github.com/davecgh/go-spew" 
) 

func main() { 

    resp, err := http.Get("http://google.com/") 
    if err != nil { 
     fmt.Println("ERROR") 
    } 
    defer resp.Body.Close() 
    spew.Dump(resp) 
    // body, err := ioutil.ReadAll(resp.Body) 
    out, err := os.Create("filename.html") 
    io.Copy(out, resp.Body) 

} 

我認爲這將制定出很好的爲你是問。