我们如何从url资源中读取内容。我在以下示例中使用了https://github.com/Kissaki/rest.go api。下面是我用来将字符串写入网址http://localhost:8080/cool的示例 但现在我需要从网址中检索数据,我该如何阅读?
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)
}
答案 0 :(得分: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
答案 1 :(得分:0)
response, err := http.Get(URL) //use package "net/http"
if err != nil {
fmt.Println(err)
return
}
defer response.Body.Close()
// Copy data from the response to standard output
n, err1 := io.Copy(os.Stdout, response.Body) //use package "io" and "os"
if err != nil {
fmt.Println(err1)
return
}
fmt.Println("Number of bytes copied to STDOUT:", n)