Skip to content

Instantly share code, notes, and snippets.

@vomnes
Created April 8, 2018 14:38
Show Gist options
  • Save vomnes/866ffd7cf7ccbe1918530aaaefa1291b to your computer and use it in GitHub Desktop.
Save vomnes/866ffd7cf7ccbe1918530aaaefa1291b to your computer and use it in GitHub Desktop.
Read the data from the body of a HTTP response
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
)
func printDataUrl(httpUrl string) (string, error) {
client := http.DefaultClient
respHttp, err := http.NewRequest("GET", httpUrl, nil)
if err != nil {
return "", err
}
resp, err := client.Do(respHttp)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode == 404 {
return "", errors.New("Error 404 : Page not found")
}
respText, err := ioutil.ReadAll(resp.Body) // Body io.ReadCloser
if err != nil {
return "", err
}
trueText := string(respText)
return trueText, nil
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage: go run print-data-url.go url_link\n")
return
}
text, err := printDataUrl(os.Args[1])
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%s", text)
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment