Skip to content

Instantly share code, notes, and snippets.

@dav1dddd
Last active January 11, 2021 19:45
Show Gist options
  • Save dav1dddd/7fc3f8d99678ed2f882b1a94b648ca77 to your computer and use it in GitHub Desktop.
Save dav1dddd/7fc3f8d99678ed2f882b1a94b648ca77 to your computer and use it in GitHub Desktop.
JSON GET request
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
// Remove anything in the structs that you don't care about, or any struct that you don't care about. Use JSON-to-Go (I am not using inline type definitions, as I prefer this way.)
// API struct
type API struct {
Data Data `json:"data"`
}
// Uploader struct
type Uploader struct {
Username string `json:"username"`
}
// Data struct
type Data struct {
ID string `json:"id"`
URL string `json:"url"`
Uploader Uploader `json:"uploader"`
Resolution string `json:"resolution"`
}
func check(text string, err error) {
if err != nil {
log.Fatal(text, err)
}
}
func main() {
// HTTP client
client := &http.Client{}
url := "https://wallhaven.cc/api/v1/w/5dw9q9"
request, err := http.NewRequest("GET", url, nil)
check("Couldn't create request:", err)
request.Header.Add("User-Agent", "jsonrequest gist [@dps910_]")
// Do the request and get response of http request (HTTP but not JSON)
response, err := client.Do(request)
status := response.Status
protocol := response.Proto
log.Printf("\nStatus: %s\nProtocol: %s", status, protocol)
// Defer response body so it can be read (until surrounding functions return)
defer response.Body.Close()
// Read json response from response body
JSON, err := ioutil.ReadAll(response.Body)
check("Couldn't read JSON response:", err)
//log.Println(string(JSON))
/*
So now you can see all of the data from the API that we sent a GET request to.
If you want to get certain key/value data and use them in a database etc, you
need to use json.Unmarshal function to unmarshal this data into structs.
Use JSON-To-Go as it is easiest and untick "Inline type definitions"
*/
API := API{}
json.Unmarshal(JSON, &API)
// Now you can do what you want with the data..
uploaderName := API.Data.Uploader.Username
imgURL := API.Data.URL
imgID := API.Data.ID
imgResolution := API.Data.Resolution
log.Printf("\nUploader: %s\nURL: %s\nID: %s\nResolution: %s", uploaderName, imgURL, imgID, imgResolution)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment