C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Get: We use the Get() func to download the home page of Wikipedia—the HTTPS protocol is used here.
Defer: We require that the Body (a stream) is entirely closed before continuing. The defer keyword waits for the Body to close.
ReadAll: We use the ioutil package to access the ReadAll method—this func is useful in many Go programs.
FileGolang program that uses http.Get, Body
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// Get Wikipedia home page.
resp, _ := http.Get("https://en.wikipedia.org/")
// Defer close the response Body.
defer resp.Body.Close()
// Read everything from Body.
body, _ := ioutil.ReadAll(resp.Body)
// Convert body bytes to string.
bodyText := string(body)
fmt.Println("DONE")
fmt.Println("Response length: ", len(bodyText))
// Convert to rune slice to take substring.
runeSlice := []rune(bodyText)
fmt.Println("First chars: ", string(runeSlice[0:10]))
}
Output
DONE
Response length: 73727
First chars: <!DOCTYPE
And: We can access the int code itself with StatusCode. This is probably easier to use when testing for a 404 error.
Tip: When using http.Get(), a 404 error is not returned as an error in Go. It is returned as a successful download with a 404 code.
Golang program that uses Status, StatusCode
package main
import (
"fmt"
"net/http"
"strings"
)
func main() {
// This file does not exist.
resp, _ := http.Get("https://www.dotnetCodex.com/robots.txt")
defer resp.Body.Close()
// Test status string.
fmt.Println("Status:", resp.Status)
if strings.Contains(resp.Status, "404") {
fmt.Println("Is not found (string tested)")
}
// Test status code of the response.
fmt.Println("Status code:", resp.StatusCode)
if resp.StatusCode == 404 {
fmt.Println("Is not found (int tested)")
}
}
Output
Status: 404 Not Found
Is not found (string tested)
Status code: 404
Is not found (int tested)