Skip to content

Golang: Get HTTP Response as a String

When you read a response it is in []byte format but you can convert it to string simply by using string() function:

string()

Use this snippet and use it as a simple template for your work:

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

func main() {
	url := "https://www.code-paste.com/"

	resp, err := http.Get(url)
	if err != nil {
		log.Fatalf("failed to get: %s", err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("failed to read body: %s", err)
	}

	myBodyString := string(body)

	fmt.Print(myBodyString)
}

Leave a Reply

Your email address will not be published. Required fields are marked *