Skip to content

Instantly share code, notes, and snippets.

@mike-carey
Created August 2, 2023 18:37
Show Gist options
  • Save mike-carey/f9ad5e0f120e9b5fad3a04e1acd58d03 to your computer and use it in GitHub Desktop.
Save mike-carey/f9ad5e0f120e9b5fad3a04e1acd58d03 to your computer and use it in GitHub Desktop.
Example using golang generics
[
{
"name": "Fluffy",
"declawed": false
},
{
"name": "Muffins",
"declawed": true
}
]
[
{
"name": "Pugsly",
"tail": true
},
{
"name": "Rover",
"tail": false
}
]
package main
import (
_ "embed"
"encoding/json"
"fmt"
)
var (
//go:embed cats.json
catJSON []byte
//go:embed dogs.json
dogJSON []byte
)
const (
catEndpoint = "/api/cats"
dogEndpoint = "/api/dogs"
)
type Cat struct {
Name string `json:"name"`
Declawed bool `json:"declawed"`
}
func (c *Cat) String() string {
is := "is"
if !c.Declawed {
is = "is not"
}
return fmt.Sprintf("%s %s declawed", c.Name, is)
}
type Dog struct {
Name string `json:"name"`
Tail bool `json:"tailclipped"`
}
func (c *Dog) String() string {
is := "does"
if !c.Tail {
is = "does not"
}
return fmt.Sprintf("%s %s have a tail", c.Name, is)
}
func getBody(endpoint string) (body []byte, err error) {
switch endpoint {
case catEndpoint:
body = catJSON
case dogEndpoint:
body = dogJSON
default:
err = fmt.Errorf("unknown endpoint: %s", endpoint)
}
return
}
func Pull[T interface {}](endpoint string) ([]T, error) {
body, err := getBody(endpoint)
if err != nil {
return nil, err
}
t := []T{}
err = json.Unmarshal(body, &t)
return t, err
}
func main() {
dogs, err := Pull[*Dog]("/api/dogs")
if err != nil {
panic(err)
}
cats, err := Pull[*Cat]("/api/cats")
if err != nil {
panic(err)
}
fmt.Println("-- Cats --")
for _, cat := range cats {
fmt.Println(cat)
}
fmt.Println("-- Dogs --")
for _, dog := range dogs {
fmt.Println(dog)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment