Go Examples
Fetch and filter data
package main
import (
"encoding/json"
"fmt"
"net/http"
"sort"
)
type Response struct {
Metadata struct {
Dataset string `json:"dataset"`
RecordCount int `json:"recordCount"`
} `json:"metadata"`
Data []WindowsUpdate `json:"data"`
}
type WindowsUpdate struct {
OSType string `json:"OSType"`
MajorVersion int `json:"MajorVersion"`
WindowsVersion string `json:"WindowsVersion"`
KBNumber string `json:"KBNumber"`
OSBuild string `json:"OSBuild"`
FullVersion string `json:"FullVersion"`
ReleaseDate string `json:"ReleaseDate"`
ReleaseType string `json:"ReleaseType"`
IsExpired bool `json:"IsExpired"`
ArticleUrl string `json:"ArticleUrl"`
}
func main() {
resp, err := http.Get("https://api.datafornerds.io/v2/microsoft/windows-11-update-history.json")
if err != nil {
panic(err)
}
defer resp.Body.Close()
var result Response
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
panic(err)
}
fmt.Printf("%s: %d records\n", result.Metadata.Dataset, result.Metadata.RecordCount)
// Filter to standard releases
var standard []WindowsUpdate
for _, u := range result.Data {
if u.ReleaseType == "Standard" {
standard = append(standard, u)
}
}
// Sort by date descending and print latest 5
sort.Slice(standard, func(i, j int) bool {
return standard[i].ReleaseDate > standard[j].ReleaseDate
})
for _, u := range standard[:5] {
fmt.Printf(" %s %s %s\n", u.ReleaseDate, u.KBNumber, u.OSBuild)
}
}
Conditional requests with ETag
package main
import (
"fmt"
"io"
"net/http"
)
func getIfChanged(url string, etag *string) ([]byte, bool, error) {
req, _ := http.NewRequest("GET", url, nil)
if *etag != "" {
req.Header.Set("If-None-Match", *etag)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, false, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotModified {
return nil, false, nil
}
*etag = resp.Header.Get("ETag")
body, err := io.ReadAll(resp.Body)
return body, true, err
}
func main() {
url := "https://api.datafornerds.io/v2/microsoft/language-codes.json"
etag := ""
data, changed, _ := getIfChanged(url, &etag)
fmt.Printf("Changed: %v, Size: %d, ETag: %s\n", changed, len(data), etag)
// Second call - should return 304
_, changed, _ = getIfChanged(url, &etag)
fmt.Printf("Changed: %v\n", changed) // false
}
Language code lookup
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func main() {
resp, _ := http.Get("https://api.datafornerds.io/v2/microsoft/language-codes.json")
defer resp.Body.Close()
var result struct {
Data []struct {
LanguageCode string `json:"LanguageCode"`
Description string `json:"Description"`
BCP47 string `json:"BCP47"`
} `json:"data"`
}
json.NewDecoder(resp.Body).Decode(&result)
lookup := make(map[string]string)
for _, r := range result.Data {
lookup[r.LanguageCode] = r.BCP47
}
fmt.Println(lookup["1033"]) // en-US
}