Simple HTTP Web Server in Golang

PROGRAM:

package main

import (
"fmt"
"net/http"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Inside homeHandler...")
/* Write text to web page */
fmt.Fprintf(w, "Hi, This is from Home Handler")
}

func page1Handler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Inside page1Handler...")
fmt.Fprintf(w, "Hello, This is from Page 1 Handler")
}

func page2Handler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Inside page2Handler...")
fmt.Fprintf(w, "Hello, This is from Page 2 Handler")
}

func main() {
/* Add handler */
http.HandleFunc("/", homeHandler)
http.HandleFunc("/page1", page1Handler);
http.HandleFunc("/page2", page2Handler);

/* Listen on a port */
fmt.Println("Listening...")
err := http.ListenAndServe(":9090", nil)
if err != nil {
fmt.Println("ERROR: ListenAndServe:", err)
}
}


Container list in Golang

PROGRAM:

package main

import (
"container/list"
"fmt"
)

func displayList(l *list.List) {
/* Traverse the list */
for e := l.Front(); e != nil; e = e.Next() {
fmt.Printf("%d ", e.Value)
}
fmt.Printf("\n")
}

func removeList(l *list.List, data int) {
/* Traverse the list and check */
for e := l.Front(); e != nil; e = e.Next() {
if e.Value == data {
l.Remove(e)
}
}
}

func main() {
/* Create the list */
mylist := list.New()

/* Push element at end */
mylist.PushBack(10)
mylist.PushBack(20)
fmt.Printf("Count-%d: ", mylist.Len())
displayList(mylist)

/* Push element at first */
mylist.PushFront(13)
mylist.PushFront(17)
fmt.Printf("Count-%d: ", mylist.Len())
displayList(mylist)

/* Remove element from list */
removeList(mylist, 10)
fmt.Printf("Count-%d: ", mylist.Len())
displayList(mylist)

/* Clear the list */
mylist.Init()
fmt.Printf("Count-%d: ", mylist.Len())
displayList(mylist)
}

OUTPUT:

sujin@sujin:~/workspace/go$ go build list.go

sujin@sujin:~/workspace/go$ ./list
Count-2: 10 20 
Count-4: 17 13 10 20 
Count-3: 17 13 20 
Count-0: 

Wait For All Goroutines to Finish Using WaitGroup in Golang

PROGRAM:

package main

import (
"fmt"
"sync"
"time"
)

func conFun(wg *sync.WaitGroup, count int) {
time.Sleep(time.Duration(count) * time.Second)
fmt.Println(time.Now(), "Go routine -", count, "finished")
wg.Done()
}

func main() {
var wg sync.WaitGroup

/* initialize wait group counter to 5 */
wg.Add(5)

count := 5
for it := 1; it <= 5; it++ {
go conFun(&wg, it)
}

fmt.Println(time.Now(), "Waiting for", count, "go routines to finish")
wg.Wait()
fmt.Println(time.Now(), "All", count, "go routines were finished")
}


OUTPUT:

sujin@sujin:~$ go build waitgroup.go 

sujin@sujin:~$ ./waitgroup 
2015-06-14 18:09:13.566058414 +0530 IST Waiting for 5 go routines to finish
2015-06-14 18:09:14.566488928 +0530 IST Go routine - 1 finished
2015-06-14 18:09:15.566480056 +0530 IST Go routine - 2 finished
2015-06-14 18:09:16.566474898 +0530 IST Go routine - 3 finished
2015-06-14 18:09:17.566485676 +0530 IST Go routine - 4 finished
2015-06-14 18:09:18.566478132 +0530 IST Go routine - 5 finished
2015-06-14 18:09:18.566549988 +0530 IST All 5 go routines were finished

Variable argument function in Golang

PROGRAM:

package main

import "fmt"

func main() {
myfunc(10, 20, 30)
fmt.Printf("\n")

myfunc(52, 43, 24, 78, 23)
fmt.Printf("\n")

vals := []int{1, 2, 3, 4, 5, 6, 7, 8}
myfunc(vals...)
}

func myfunc(args ...int) {
for ind, val := range args {
fmt.Println(ind, "->", val)
}
}


OUTPUT:

0 -> 10
1 -> 20
2 -> 30

0 -> 52
1 -> 43
2 -> 24
3 -> 78
4 -> 23

0 -> 1
1 -> 2
2 -> 3
3 -> 4
4 -> 5
5 -> 6
6 -> 7
7 -> 8

Command line flags in Golang

Command line flags helps to pass the value from command line itself when running the program. If you are a C/C++ programmer in unix platform then you must aware of getopt. Command line flags in golang is similar to getopt in C. 

This facility provided in golang with the help of a package called flag.


Command line flags support for three data types. Those are

  1. Integer (int)
  2. Boolean (bool)
  3. String (String)
Below is the example program and its output

PROGRAM:

package main
import (
"flag"
"fmt"
)
func main() {
/* define int, string and bool type flags, it return pointer value */
agePtr := flag.Int("age", 18, "age as integer")
namePtr := flag.String("name", "John", "name as string")
availPtr := flag.Bool("avail", false, "availability boolean")
/* Parse all defined flags */
flag.Parse()
/* since flag return pointer value, dereference it to get value */
fmt.Println("Name:", *namePtr, " Age:", *agePtr, " Availability:", *availPtr)
}

Run:
go run flag.go



OUTPUT:

./flag -name=Bruce -age=35 -avail
Name: Bruce  Age: 35  Availability: true



./flag -name=Mark -age=26
Name: Mark  Age: 26  Availability: false



./flag
Name: John  Age: 18  Availability: false




flag declaration take three arguments flagname, default value and flag name description

    agePtr := flag.Int("age", 18, "age as integer")

This means it declare integer flag with flag name as 'age' its default value '18' and description 'age as integer'. It return pointer value so agePtr has to be de-referenced when using as value.


There is one more way to declare command line flag in golang example program below. 

PROGRAM:
package main

import (
"flag"
"fmt"
)

func main() {
var (
age int
name string
avail bool
)

flag.IntVar(&age, "age", 20, "age as integer")
flag.StringVar(&name, "name", "Peter", "name as string")
flag.BoolVar(&avail, "avail", false, "avail as boolean")

/* Parse all defined flags */
flag.Parse()

/* value type so dereferencing not needed */
fmt.Println("Name:", name, " Age:", age, " Avail:", avail)
}
OUTPUT:
./flag -name=jack -avail -age=31
Name: jack Age: 31 Avail: true


instead of returning flag value as pointer here we can pass a variable and get the the value. 

    flag.StringVar(&name, "name", "Peter", "name as string")
This take four parameters address of variable, name of the flag, default value and flag description