John Floren

Home | Blog | Uses | Links
Back to blog archive

Posted 2013/3/21

Go: First time using reflection!

Ok so I’ve been writing a music jukebox (think MPD) in Go and just came to the part where you search for songs. I keep track of each song as an instance of a Song struct which contains fields like Artist, Name, Album, etc. How can I write a simple function that will let me search each song for whatever field I specify? Turns out, it’s my first opportunity to use reflection. I was really pleased with how short the code turned out; it’s probably not perfect but it works and it’s FAST:

type Song struct {
        Name   string
        Artist string
        Album  string
        Year   string
        Track  string
        Disc   string
        Genre  string
        Length string
        File string
}

func search(args []string) string {
        if len(args) != 2 {
                return ERR
        }

        fieldname := args[0]
        term := strings.ToLower(args[1])
        ret := ""

        // Ok, let's try reflection
        for _, s := range songs {
                v := reflect.ValueOf(s)
                if strings.Contains(strings.ToLower(v.FieldByName(fieldname).String()), term) {
                        ret += s.prettyPrint()
                }
        }
        ret += OK
        return ret
}

Now, you control the jukebox over a Unix socket (this is so I can write frontends to it easily), sending messages with a text protocol. Here’s a sample search command I might issue:

search 2
Name
transmaniacon

And here’s what I get back:

File: /home/john/music/Blue Oyster Cult/1972-Blue_Oyster_Cult/01 - Transmaniacon.mp3
Name: Transmaniacon MC
Artist: Blue Oyster Cult
Album: Blue Oyster Cult
Disc:
Track: 1
Length: 201000
OK