在Go中从URL资源读取

huangapple go评论159阅读模式
英文:

Reading from a url resource in Go

问题

如何从URL资源中读取数据。我在下面的示例中使用了https://github.com/Kissaki/rest.go API。以下是我用来将字符串写入URL http://localhost:8080/cool 的示例。但现在我需要从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)    
}
英文:

How do we read from a url resource. I have used the https://github.com/Kissaki/rest.go api in the following example. Below is the example I use to write a string to the url http://localhost:8080/cool
But now I need to retrieve the data from the url, how do I read it back?

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)	
}

答案1

得分: 12

如果你只想通过HTTP获取一个文件,你可以像这样做:

resp, err := http.Get("http://your.url.com/whatever.html")
check(err) // 进行一些错误处理

// 从resp.Body中读取,它是一个ReadCloser类型的对象
英文:

if you just want to fetch a file over http you could do something like this i guess

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

// read from resp.Body which is a ReadCloser

答案2

得分: 4

response, err := http.Get(URL) //使用包"net/http"

if err != nil {
fmt.Println(err)
return
}

defer response.Body.Close()

// 将响应数据复制到标准输出
n, err1 := io.Copy(os.Stdout, response.Body) //使用包"io"和"os"
if err != nil {
fmt.Println(err1)
return
}

fmt.Println("复制到标准输出的字节数:", n)

英文:
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)

huangapple
  • 本文由 发表于 2011年7月14日 02:41:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/6683889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定