michiwend / gomusicbrainz

a Go (Golang) MusicBrainz WS2 client library - work in progress
MIT License
57 stars 24 forks source link

Can't figure out how to use Relationships #7

Closed Cretezy closed 8 years ago

Cretezy commented 8 years ago

Hey!

I've been working on this for a few days and can't really figure it out.

In general, my goal is to give gomusicbrainz a MBID and get returned the URL relationships (Wikipedia, official website, Spotify, etc..).

For instance, this is my best try:

    // Grab Musicbrainz artist
    musicbrainzArtist, err := musicbrainzClient.LookupArtist(
        gomusicbrainz.MBID(artist.MusicbrainzID), "url-rels",
    )
    if err != nil {
        log.Warn(err)
        continue
    }
    // List all url 
    for _, url := range musicbrainzArtist.Relations["url"] {
        fmt.Println(gomusicbrainz.URLRelation(url).Target) // error, don't know what to do here
    }

My question is: How do I convert a gomusicbrainz.Relation to gomusicbrainz.URLRelation?

michiwend commented 8 years ago

Hej and sorry for my late response.

The problem in your example is, you are trying to cast an interface type to a struct. gomusicbrainz.Relation is an interface type that only requires the TypeOf() method to be implemented on the actual type.

type Relation interface {
    TypeOf() string
}

What you want to do is a type assertion. Whenever you have an interface and want to access it's 'underlying' type, you have to assert the actual type.

Here is a small example that requests an artist and prints it's URL relations

package main

import (
    "fmt"
    "gomusicbrainz"
)

func main() {

    client, _ := gomusicbrainz.NewWS2Client(
        "https://musicbrainz.org/ws/2",
        "A GoMusicBrainz example",
        "0",
        "http://github.com/michiwend/gomusicbrainz")

    artist, err := client.LookupArtist(
        gomusicbrainz.MBID("fe1a873d-2000-4789-a895-4187fe756203"),
        "url-rels")

    if err != nil {
        fmt.Println(err)
        return
    }

    if urlRels, ok := artist.Relations["url"]; ok {
        for _, rel := range urlRels {

            // type assertion
            urlRelation, ok := rel.(*gomusicbrainz.URLRelation)
            if !ok {
                fmt.Println("should not have happend!")
                continue
            }

            fmt.Printf("%s: %s\n", urlRelation.Type, urlRelation.Target)
        }
    }
}
Cretezy commented 8 years ago

Thank you! A little late and figured out another solution, but thanks for enlightening me!