Golang: Simple Golang Web Application


In this post I’d like to show you a simple web application developed using Go / Golang that demonstrate you several basic web  functionalities such as http request and http response.

The result should be something like this that runs in your web browser:

golang-x1golang-x2

main.go

package main

  import (
      "fmt"
      "html/template"
      "net/http"
      "os"
  )

  type FormData struct {
      Name    string
      Country string
  }

  func form(w http.ResponseWriter, r *http.Request) {
      folderpath, _ := os.Getwd() // Get current folder location
      form, _ := template.ParseFiles(folderpath + "/form.gtpl")
      form.Execute(w, nil)
  }

  func view(w http.ResponseWriter, r *http.Request) {
      if r.Method == "POST" {

          // Process form data
          r.ParseForm()
          name := r.Form["name"][0] // Yes, Go able to receive more than one name
          country := r.Form["country"][0]
          //fmt.Println(name)
          //fmt.Println(country)

          data := FormData{
              Name:    name,
              Country: country,
          }   

          folderpath, _ := os.Getwd() // Get current folder location
          view, _ := template.ParseFiles(folderpath + "/view.gtpl")
          view.Execute(w, data)
      } else {
         fmt.Fprintf(w, "Method not allowed!") // write data to response
      }
  }

  func main() {
      // Routes
      http.HandleFunc("/", form)
      http.HandleFunc("/view", view)

      http.ListenAndServe(":8000", nil) // setting listening port
  }

form.gtpl

<html>

      <body>
<h1>Hallo World</h1>
<form method="POST" action="/view">
              Name : <input name="name" />
              Coutry : <input name="country" />

              <input type="submit" />
          </form>

      </body>

  </html>

view.gtpl

 <html>
  <head>
  <title></title>
  </head>
      <body>
          Hello World 

          Welcome -{{.Name}}- from -{{.Country}}-
      </body>
  </html>

Build and Run The code

golang x3

Code Snapshot

VIMX1VIMX2VIMX3

Advertisements

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