Skip to content

Learning Go – Miniblog #11 – More HTTP

January 22, 2013

This carries on from here, and started here.

Well, I got the server working. Here’s the index page:

index1

A masterful example of the web designer’s art! I’ve always been crap at HTML. And clicking on one of the index links gives you this sort of view of a CSV data file:

data1

This turned out to be pretty easy to do. I provided two request handlers for the "index" and "data" URLs:

func ServeCSV() {
    http.HandleFunc( CSVROOT + IDXSTR + "/", csvIndexHandler )
    http.HandleFunc( CSVROOT + DATASTR + "/", csvDataHandler )
    http.ListenAndServe( ":8080", nil )
}

The server will then pick the correct handler depending on the URL. The handlers look like this:

func csvIndexHandler( rw http.ResponseWriter, req *http.Request ) {
    fmt.Fprintf( rw, "<h1>CSV index</h1>\n" )
    listIndex( rw )
}

which is the handler for the index request. It just writes out the requisite HTML to the ResponseWriter object via the listIndex() function, which looks like this:

func listIndex( rw http.ResponseWriter ) {
    dir,err := CSVList( DATAPATH )
    if err != nil {
        fmt.Fprintf( rw, "Error reading directory %s", DATAPATH )
    } else {
        fmt.Fprintf( rw, "<ul>\n")
        for _,file := range( dir ) {
            fmt.Fprintf( rw, "<li>%s</li>\n", makeLink( file ) )
        }
        fmt.Fprintf( rw, "</ul>\n" )
    }
}

which basically produces an unordered list of HTML links to the actual data files, using one of the utility function I previously wrote to read the directory information. The handler for the "data" URL (which will be invoked when one of these links is clicked on) then uses another previously-written utility function to produce an HTML table from the CSV data. The complete code is available here.

This turned out to be very easy to implement – I’m reasonably impressed  at how easy, though doing it in Python (for example) would probably have been just as simple. Next, I want to turn the server code into something like an object…

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: