Go – Simple web application on Docker

A simple web application running on 8080 and prints “Hello” and the name you pass

1. Create a hello.go file and copy the below code
hello.go:


package main

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello %s", r.URL.Path[1:])    
    
}

func queryHandler(w http.ResponseWriter, r *http.Request) {
    name := r.URL.Query().Get("name")
    if name == "" {
        fmt.Fprintf(w, "Hello")
    }else{
       fmt.Fprintf(w, "Hello %s", name)
   }
}

func main() {
    http.HandleFunc("/", helloHandler)
    http.HandleFunc("/query", queryHandler)
    http.ListenAndServe(":8080", nil)
}


2. Then create a Dockerfile and copy the below code
Dockerfile:


   FROM golang:1.6-onbuild
   EXPOSE 8080

3. Then type “docker build -t hello-go-lang . ” to build the images
4. Finally run by typing “docker run -p 8080:8080 hello-go-lang”

Then in the browser type the below urls and check the output
http://localhost:8080/ – Hello
http://localhost:8080/test – Hello test
http://localhost:8080/query?name=test – Hello test

Advertisements