Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from a url resource in Go

Tags:

url

go

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)   
}
like image 830
chinmay Avatar asked Jul 13 '11 18:07

chinmay


2 Answers

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
like image 135
bjarneh Avatar answered Oct 11 '22 13:10

bjarneh


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)
like image 25
Wolfack Avatar answered Oct 11 '22 15:10

Wolfack