2011-07-13 166 views
2

我們如何從url資源中讀取數據。在下面的例子中我使用了https://github.com/Kissaki/rest.go api。下面是我用來寫一個字符串到URL的例子http://localhost:8080/cool 但是現在我需要從url中檢索數據,我該如何讀取它?從URL資源中讀取

package main 

import (
    "fmt" 
    "http" 
    "github.com/nathankerr/rest.go" 
) 

type FileString struct { 
    value string 
} 

func (t *FileString) Index(w http.ResponseWriter) { 
    fmt.Fprintf(w, "%v", t.value) 
} 

func main(){ 
    rest.Resource("cool", &FileString{s:"this is file"})  
    http.ListenAndServe(":3000", nil) 
} 

回答

4

,如果你只是想獲取通過HTTP文件,你可以做這樣的事情我想

resp, err := http.Get("http://your.url.com/whatever.html") 
check(err) // does some error handling 

// read from resp.Body which is a ReadCloser 
+0

你能告訴我怎麼做,我讀了resp.Body內容是什麼? – chinmay

+0

'content:= make([] byte,resp.ContentLength); n,err:= resp.Body.Read(content);檢查(err)'這樣的事情?如果ContentLength不應該在整個塊中讀取,我猜 – bjarneh

+0

typo,我的意思是說,讀取整個文件在一個大的[]字節'塊可能不是理想的'resp.ContentLength'是巨大的,即它應該說ContentLength是否大......等等 – bjarneh