10

Learning Go – Miniblog #11 – More HTTP | Late Developer

 2 years ago
source link: https://latedev.wordpress.com/2013/01/22/learning-go-miniblog-11-more-http/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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:

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:

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
Report this ad

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK