#only showing specific struct fields for structs that don’t belong to you

6 messages · Page 1 of 1 (latest)

brazen mica
#

👋 I have an API where I’m returning JSON to the frontend. The struct I’m using belongs to an external library though (Kubernetes pod struct found here: https://pkg.go.dev/k8s.io/api/core/v1#Pod) point is it’s very complex and when I return it to the frontend it’s very messy.

I guess this is a non-issue since the frontend side can be in charge of simplifying the JSON. But I’d rather not send a bunch of bulky json requests.

I guess I could create my own struct and only pass on what I need but I’d rather not create my own structs just to populate these third party structs for every single one I add.

Just wanted to know if there’s some other alternatives / libs used to deal with this use case? Had trouble trying to Google this.

Here’s some of of the API code for better context (uses go-chi):


type PodResponse struct {
    Pod v1.Pod
}

func (*PodResponse) Render(w http.ResponseWriter, r *http.Request) error {
    return nil
}

func main() {
…

    r.Get("/pods", func(w http.ResponseWriter, r *http.Request) {
        pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
        if err != nil {
            log.Println(err)
            render.Render(w, r, ErrNotFound)
            return
        }
        render.Render(w, r, &PodResponse{Pod: pods.Items[0]})
    })

…
}

fluid lance
#

I suppose you don't want to dim a lot of struct and you will not to use these struct repeatable.

so I think you can use anonymous struct for this

func main() {
    b, _ := json.Marshal(struct {
        A int
        B int
        C string
    }{
        A: 1,
        B: 2,
        C: "just put what you want in it",
    })
    fmt.Println(string(b))
}

just temporary dim a struct and give it property what you want in your pods.

narrow elbow
#

but Id rather not
You should just do so. Any other alternative will just be much worse and less clear

brazen mica
#

Fair enough ur right gotta define data models anyway and it forces me to really figure out what from k8s I actually need

#

I didn’t think about anon structs thanks nimo! Not using it here but good to keep in mind as a quick and dirty Marshall

#

Given it’s k8s ideally there won’t be any breaking changes at this level and they’ll practice good API design