Skip to content

Learning Go – Miniblog #9 – Reading CSV

January 16, 2013

This carries on from here, and started here.

This project is supposed to serve CSV data as HTML tables. I thought I would probably have to write my own CSV parser, but was pleasantly surprised to find that Go provides one out of the box as part of its library. It’s pretty easy to use – you create a reader object (similar to the buffered reader I used earlier), give it a file (or more accurately, something that supports the io.Reader interface) and then read the CSV data, which gets stuffed into a slice. I then format that slice as an HTML table. I haven’t bothered worrying about special HTML characters like ampersands when doing this. Here’s the code:

func CSVToHTML( r io.Reader ) (string,error) {
    reader := csv.NewReader( r )
    var html string
    for {
        record,err := reader.Read()
        if err == io.EOF {
            break
        } else if( err != nil ) {
            return "", err
        }
        html += makeHTMLRow( record )
    }
    return "<table>\n" + html + "\n</table>\n", nil
}

where makeHTMLRow() is my own function to add the <tr> and <td> HTML tags to format the data appropriately.

One thing I’ve noticed that I’m having  a hard time stopping myself doing is adding extraneous parentheses around if-conditions, like this one:

else if( err != nil )

In C and C++ those parens are required, but they are not in Go (and in fact are not syntactically part of the if). I should simply be writing:

 else if err != nil

No doubt in time I will stop doing it.

Well, that’s most of the low-hanging fruit picked – I guess I now need to look at how to implement the server stuff…

Advertisements

From → golang

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: