April 19, 2013

Go for Web Application: Template and jQuery Integration

In this article I will explain about using Go to develop web application together with template and jQuery integration. Develop a web server is a trivial task in Go. Interestingly, Go which initially meant to ease the development of server software has lots of standard libraries for that purpose. Web server is not the only one, although we will explore this capability now. Before we continue, make sure that you already have jQuery (I use jquery-ui 1.9.1) and of course Go (1.0.3). For now, we do not need template engine since Go comes with html/template package. That's enough for now.

Ok, let me give an overview first. We will develop a simple Web application. Our application (let's say its name is go-jquery-example) will read the template, put a string inside the template and display the template. Wait, that's not quite complex, we will add jQuery into that page so in the future we may develop a Web application with good UI. To this end we should make a static file explorer into our Web application so that we can place jQuery into the template (like /js/jquery-ui.js).

Let's see the directory structure first.



  • assets: this directory will be used to serve static files. It consists of css (all CSS files), img (all image files), and js (all javascript files). We put jQuery into that directory.
  • gojquery.go: our main application. 
  • templates: this directory will serve all template files.
default.tpl


gojquery.go

package main

import (
 "html/template"
 "log"
 "net/http"
)

// this handler will be executed when we use web client 
// to access http://server/display
func handler(w http.ResponseWriter, req *http.Request) {

  // read the whole template
  t, err := template.ParseFiles("templates/default.tpl")

  if err != nil {
    log.Fatal(err)
  }

  // The person's name struct which will be substituted 
  // into the template
  type Person struct {
    Name string
  }

  // put the person name here
  p := Person{Name: "bpdp"}

  // put the name into the template and populate the view
  // w is the response which will be sent to web client
  t.Execute(w, p)

}

func main() {

  // assign the handler (http://server/display)
  http.HandleFunc("/display", handler)

  // put assets dir to serve static files (see dir structure below)
  http.Handle("/", http.FileServer(http.Dir("assets/")))

  // put web server to work, port 8123
  http.ListenAndServe(":8123", nil)
}

Now, to run this Web application, go to the root directory where gojquery.go reside, and run the application:

go run gojquery.go

Try access http://server:8123/ and http://server:8123/display to see the result.

Full source code available at https://github.com/bpdp/go-jquery-example. Enjoy!

0 comments:

Posting Komentar