How to Retrieve Webpage Content as a String in Go?

Susan Sarandon
Release: 2024-11-23 01:33:25
Original
843 people have browsed it

How to Retrieve Webpage Content as a String in Go?

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:

  1. Utilize the http Package:

    • Start by importing the http package: import "net/http".
  2. Construct an HTTP GET Request:

    • Use the http.Get(link) function to create an HTTP GET request for the specified webpage URL (stored in the link variable).
  3. Receive and Read Response:

    • If the request is successful, store the response in the res variable.
    • Use io.ReadAll(res.Body) to read the content of the webpage and convert it to a byte slice.
  4. Convert and Store Content:

    • Convert the byte slice into a string using string(content).
    • Return the resulting string, which represents the webpage content.
  5. Handle the Response Body:

    • Remember to close the response body using res.Body.Close() to prevent resource leaks.
  6. 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"))
    }
    Copy after login

    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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template