make a http get request in go

To make an HTTP GET request in Go, you can use the standard net/http package. Here is an example code snippet:

main.go
import (
    "fmt"
    "net/http"
)

func main() {
    // Create a new HTTP GET request to the specified URL
    resp, err := http.Get("https://www.example.com")
    if err != nil {
        // Handle error
        fmt.Println("Error:", err)
        return
    }
    defer resp.Body.Close()

    // Print the HTTP response status code
    fmt.Println("Status code:", resp.StatusCode)

    // Print the response body
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // Handle error
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Response body:", string(body))
}
608 chars
28 lines

In this example, we create a new HTTP GET request to the URL "https://www.example.com". We then check for any errors, print the status code of the HTTP response, and finally print the body of the response. Remember to always close the response body to prevent resource leaks.

related categories

gistlibby LogSnag