Skip to content

Go Programming Language

Resources

Install Go

Go is designed to work when your code is inside a workspace. The workspace is a folder composed of bin, pkg, and src subfolders. Don’t force Go to follow your own style. Create a go folder with a src subfolder wherever you expect to put your projects.

Install Go Dependency Management Tool (dep)

Follow install instructions.

1
2
3
export PATH=$PATH:/usr/local/go/bin
export GOPATH=/usr/local/go
curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh

Create Project Directory

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
export GOPATH=/usr/local/go:/home/tparikh/code/go
mkdir -p /home/tparikh/code/go/src /home/tparikh/code/go/bin /home/tparikh/code/go/pkg
mkdir -p /home/tparikh/code/go/src/github.com
mkdir -p /home/tparikh/code/go/src/github.com/hello-world-go
cd /home/tparikh/code/go/src/github.com/hello-world-go
dep init
mkdir cmd
mkdir pkg
touch README.md
cd cmd 
touch main.go

Sample Go Programs

main.go

1
2
3
4
5
package main

func main () {
println ("Hello World!!!")
}

Run

1
2
cd $GOPATH/src/github.com/hello-world-go/cmd
go run main.go

Build Executable

1
2
3
cd $GOPATH/src/github.com/hello-world-go/cmd
go build main.go
./main

Format Go Code

1
2
cd $GOPATH/src/github.com/hello-world-go/cmd
go fmt main.go

api.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import (
    "encoding/json"
    "fmt"
    "github.com/gorilla/mux"
    "log"
    "net/http"
    time2 "time"
)

type Time struct {
    Now string `json:"now,omitempty"`
}

func GetTime(w http.ResponseWriter, r *http.Request) {

    time := Time{
        Now: time2.Now().String(),
    }

    fmt.Printf("Get request from %v", r.RemoteAddr)

    //w.WriteHeader(http.StatusOK)

    json.NewEncoder(w).Encode(time)
}

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", GetTime).Methods("GET")
    log.Fatal(http.ListenAndServe(":8000", router))
}

for.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import "fmt"

func main() {
    num := [3]int{1, 2, 3}

    for index, value := range num {
        fmt.Printf("%v %v\n", index, value)
    }

    for _, item := range num {
        fmt.Printf("%v\n", item)
    }
}