2011-07-13 164 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