Fetch like Javascript in Golang
If you are javascript developer and just starting to write a golang code you might find that performing http request in golang is not easy writing fetch request in javascript. But I have good news for you, you can use this snippet for you to write http request just like fetch request in javascript.
Fetch function
When working on news feed for Readclip I need to perform http request to scraping some content from several sources. So I came up with this simple http request wraper to run the request just like we do in javascript.
We will not going to use any external dependencies for this. Just put this code in your utility folder.
package fetch
import (
"io"
"net/http"
"github.com/ahmadrosid/readclip/internal/util"
)
func Fetch(path string) (string, error) {
req, err := http.Get(path)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", " */*")
body, err := io.ReadAll(req.Body)
if err != nil {
return "", err
}
return string(body), nil
}
Here's how to use it
If you need to fetch html content as string, you can just do this.
htmlSource, err := fetch.Fetch("https://example.com")
if err != nil {
return nil, err
}
And here's for example if you need to run fetch request with json response.
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
func Fetch(path string) (string, error) {
// fetch code here....
}
type GithubResponse struct {
ID int `json:"id"`
AvatarURL string `json:"avatar_url"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
Name string `json:"name"`
Blog string `json:"blog"`
Email interface{} `json:"email"`
Bio string `json:"bio"`
TwitterUsername string `json:"twitter_username"`
Followers int `json:"followers"`
Following int `json:"following"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func main() {
response, err := Fetch("https://api.github.com/users/ahmadrosid")
// continue
if err != nil {
fmt.Println("Error fetching data:", err)
return
}
var githubResponse GithubResponse
if err := json.Unmarshal([]byte(response), &githubResponse); err != nil {
fmt.Println("Error parsing JSON:", err)
return
}
fmt.Printf("User ID: %d\n", githubResponse.ID)
fmt.Printf("User Name: %s\n", githubResponse.Name)
fmt.Printf("Followers: %d\n", githubResponse.Followers)
fmt.Printf("Twitter Username: %s\n", githubResponse.TwitterUsername)
fmt.Printf("Bio: %s\n", githubResponse.Bio)
}