Accessing Webpage Content as a String in Go
Question:
How can I retrieve the content of a webpage as a string using Go's http package?
Answer:
To accomplish this, follow these steps:
Utilize the http Package:
Construct an HTTP GET Request:
Receive and Read Response:
Convert and Store Content:
Handle the Response Body:
Example Code:
package main import ( "fmt" "io/ioutil" "log" "net/http" ) func OnPage(link string) string { res, err := http.Get(link) if err != nil { log.Fatal(err) } content, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } return string(content) } func main() { fmt.Println(OnPage("http://www.bbc.co.uk/news/uk-england-38003934")) }
This example retrieves and prints the content of the BBC UK News page.
The above is the detailed content of How to Retrieve Webpage Content as a String in Go?. For more information, please follow other related articles on the PHP Chinese website!