├── .gitignore
├── .travis.yml
├── README.org
├── cheatsheet-golang-A4.pdf
├── code
├── example-frontend.go
├── example-goroutine.go
├── example-hashmap-arraykey.go
├── example-http.go
├── example-interface.go
├── example-json.go
├── example-procedue-pig.go
├── example-read-file.go
├── example-switch.go
├── example-write-file.go
├── helloworld.go
├── interface-conversion.go
└── pointer-array.go
└── misc
└── pages.json
/.gitignore:
--------------------------------------------------------------------------------
1 | *.tex
2 | README.pdf
3 | .DS_Store
4 | test.go
5 | *-A4.log
6 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | # This is a weird way of telling Travis to use the fast container-based test
2 | # runner instead of the slow VM-based runner.
3 | sudo: false
4 |
5 | language: go
6 |
7 | # Only the last two Go releases are supported by the Go team with security
8 | # updates. Any older versions be considered deprecated. Don't bother testing
9 | # with them.
10 | go:
11 | - 1.9.x
12 |
13 | # Only clone the most recent commit.
14 | git:
15 | depth: 1
16 |
17 | # Skip the install step. Don't `go get` dependencies. Only build with the code
18 | # in vendor/
19 | install: true
20 |
21 | # Don't email me the results of the test runs.
22 | notifications:
23 | email: false
24 |
25 | # Anything in before_script that returns a nonzero exit code will flunk the
26 | # build and immediately stop. It's sorta like having set -e enabled in bash.
27 | # Make sure golangci-lint is vendored by running
28 | # dep ensure -add github.com/golangci/golangci-lint/cmd/golangci-lint
29 | # ...and adding this to your Gopkg.toml file.
30 | # required = ["github.com/golangci/golangci-lint/cmd/golangci-lint"]
31 | before_script:
32 | - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b $GOPATH/bin v1.8.1
33 |
34 | # script always runs to completion (set +e). If we have linter issues AND a
35 | # failing test, we want to see both. Configure golangci-lint with a
36 | # .golangci.yml file at the top level of your repo.
37 | script:
38 | - golangci-lint run # run a bunch of code checkers/linters in parallel
39 | - go test -v -race ./... # Run all the tests with the race detector enabled
40 |
--------------------------------------------------------------------------------
/cheatsheet-golang-A4.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dennyzhang/cheatsheet-golang-A4/246ebfa4c5040e3739bab09d7a938717fb629a9e/cheatsheet-golang-A4.pdf
--------------------------------------------------------------------------------
/code/example-frontend.go:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------------
2 | // File: example_frontend.go
3 | // Description :
4 | // go run example_frontend.go
5 | // curl http://localhost:8080/view/
6 | // https://cheatsheet.dennyzhang.com/cheatsheet-golang-A4
7 | // --
8 | // Created : <2018-04-07>
9 | // Updated: Time-stamp: <2018-10-06 16:39:56>
10 | //-------------------------------------------------------------------
11 | // link: https://golang.org/doc/articles/wiki/part2.go
12 | // Copyright 2010 The Go Authors. All rights reserved.
13 | // Use of this source code is governed by a BSD-style
14 | // license that can be found in the LICENSE file.
15 |
16 | package main
17 |
18 | import (
19 | "fmt"
20 | "io/ioutil"
21 | "log"
22 | "net/http"
23 | )
24 |
25 | type Page struct {
26 | Title string
27 | Body []byte
28 | }
29 |
30 | func (p *Page) save() error {
31 | filename := p.Title + ".txt"
32 | return ioutil.WriteFile(filename, p.Body, 0600)
33 | }
34 |
35 | func loadPage(title string) (*Page, error) {
36 | filename := title + ".txt"
37 | body, err := ioutil.ReadFile(filename)
38 | if err != nil {
39 | return nil, err
40 | }
41 | return &Page{Title: title, Body: body}, nil
42 | }
43 |
44 | func viewHandler(w http.ResponseWriter, r *http.Request) {
45 | title := r.URL.Path[len("/view/"):]
46 | p, _ := loadPage(title)
47 | fmt.Fprintf(w, "
%s
%s
", p.Title, p.Body)
48 | }
49 |
50 | func main() {
51 | fmt.Printf("start webserver on http://localhost:8080\n")
52 | http.HandleFunc("/view/", viewHandler)
53 | log.Fatal(http.ListenAndServe(":8080", nil))
54 | }
55 | // File: example_frontend.go ends
56 |
--------------------------------------------------------------------------------
/code/example-goroutine.go:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------------
2 | // @copyright 2018 DennyZhang.com
3 | // Licensed under MIT
4 | // https://www.dennyzhang.com/wp-content/mit_license.txt
5 | //
6 | // File: example_goroutine.go
7 | // Author : Denny
8 | // Description : go run example_goroutine.go
9 | // https://cheatsheet.dennyzhang.com/cheatsheet-golang-A4
10 | // --
11 | // Created : <2018-04-07>
12 | // Updated: Time-stamp: <2018-10-06 16:40:26>
13 | //-------------------------------------------------------------------
14 | package main
15 |
16 | import (
17 | "fmt"
18 | "time"
19 | )
20 |
21 | func say(s string) {
22 | for i := 0; i < 5; i++ {
23 | time.Sleep(100 * time.Millisecond)
24 | fmt.Println(s)
25 | }
26 | }
27 |
28 | func main() {
29 | go say("world")
30 | say("hello")
31 | }
32 | // File: example_goroutine.go ends
33 |
--------------------------------------------------------------------------------
/code/example-hashmap-arraykey.go:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------------
2 | // @copyright 2018 DennyZhang.com
3 | // Licensed under MIT
4 | // https://www.dennyzhang.com/wp-content/mit_license.txt
5 | //
6 | // Author : Denny
7 | // Description :
8 | // https://cheatsheet.dennyzhang.com/cheatsheet-golang-A4
9 | // --
10 | // Created : <2018-04-07>
11 | // Updated: Time-stamp: <2019-10-09 10:00:28>
12 | //-------------------------------------------------------------------
13 | package main
14 |
15 | import (
16 | "fmt"
17 | )
18 |
19 | func main() {
20 | // use fixed size array as key, or define a type of struct
21 | m := map[[2]int]bool{}
22 | m[[2]int{2, 2}] = true
23 | fmt.Println("Hello, playground", m)
24 | }
25 |
--------------------------------------------------------------------------------
/code/example-http.go:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------------
2 | // @copyright 2018 DennyZhang.com
3 | // Licensed under MIT
4 | // https://www.dennyzhang.com/wp-content/mit_license.txt
5 | //
6 | // Author : Denny
7 | // Description :
8 | // https://cheatsheet.dennyzhang.com/cheatsheet-golang-A4
9 | // --
10 | // Created : <2018-04-07>
11 | // Updated: Time-stamp: <2020-01-16 16:55:58>
12 | //-------------------------------------------------------------------
13 | package main
14 |
15 | import (
16 | "crypto/tls"
17 | "fmt"
18 | "io/ioutil"
19 | "net/http"
20 | )
21 |
22 | func main() {
23 | // https://stackoverflow.com/questions/12122159/how-to-do-a-https-request-with-bad-certificate
24 | fmt.Println("Starting the application...")
25 | http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
26 | client := &http.Client{}
27 | req, _ := http.NewRequest("GET", "https://myserver.abc.com:9000/v1/clusters", nil)
28 | req.Header.Set("content-type", "application/json")
29 | req.Header.Set("Authorization", "Bearer eyJhbXXXX")
30 | response, err := client.Do(req)
31 | if err != nil {
32 | fmt.Printf("The HTTP request failed with error %s\n", err)
33 | } else {
34 | data, _ := ioutil.ReadAll(response.Body)
35 | fmt.Println(string(data))
36 | }
37 | fmt.Println("Terminating the application...")
38 | }
39 |
--------------------------------------------------------------------------------
/code/example-interface.go:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------------
2 | // @copyright 2018 DennyZhang.com
3 | // Licensed under MIT
4 | // https://www.dennyzhang.com/wp-content/mit_license.txt
5 | //
6 | // Author : Denny
7 | // Description :
8 | // https://cheatsheet.dennyzhang.com/cheatsheet-golang-A4
9 | // --
10 | // Created : <2018-04-07>
11 | // Updated: Time-stamp: <2018-12-16 11:07:38>
12 | //-------------------------------------------------------------------
13 | package main
14 |
15 | import (
16 | "fmt"
17 | )
18 |
19 | type Car interface {
20 | Drive() string
21 | }
22 |
23 | type Toyota struct {
24 | name string
25 | }
26 |
27 | type Honda struct {
28 | name string
29 | }
30 |
31 | func (p Toyota) Drive() string {
32 | return "110mph";
33 | }
34 |
35 | func (p Honda) Drive() string {
36 | return "120mph";
37 | }
38 |
39 | func main() {
40 | t := Toyota{name: "toyota"}
41 | fmt.Println(t.name+" "+t.Drive())
42 |
43 | h := Honda{name: "honda"}
44 | fmt.Println(h.name+" "+h.Drive())
45 | }
46 |
--------------------------------------------------------------------------------
/code/example-json.go:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------------
2 | // @copyright 2018 DennyZhang.com
3 | // Licensed under MIT
4 | // https://www.dennyzhang.com/wp-content/mit_license.txt
5 | //
6 | // File: example_json.go
7 | // Author : Denny
8 | // Description : go run example_json.go
9 | // Link: https://www.chazzuka.com/2015/03/load-parse-json-file-golang/
10 | // https://cheatsheet.dennyzhang.com/cheatsheet-golang-A4
11 | // --
12 | // Created : <2018-04-07>
13 | // Updated: Time-stamp: <2018-10-06 16:40:26>
14 | //-------------------------------------------------------------------
15 | package main
16 |
17 | import (
18 | "encoding/json"
19 | "fmt"
20 | "io/ioutil"
21 | "os"
22 | )
23 |
24 | type Page struct {
25 | ID int `json:"id"`
26 | Title string `json:"title"`
27 | Url string `json:"url"`
28 | }
29 |
30 | func (p Page) toString() string {
31 | return toJson(p)
32 | }
33 |
34 | func toJson(p interface{}) string {
35 | bytes, err := json.Marshal(p)
36 | if err != nil {
37 | fmt.Println(err.Error())
38 | os.Exit(1)
39 | }
40 |
41 | return string(bytes)
42 | }
43 |
44 | func main() {
45 |
46 | pages := getPages()
47 | for _, p := range pages {
48 | fmt.Println(p.toString())
49 | }
50 |
51 | fmt.Println(toJson(pages))
52 | }
53 |
54 | func getPages() []Page {
55 | raw, err := ioutil.ReadFile("./misc/pages.json")
56 | if err != nil {
57 | fmt.Println(err.Error())
58 | os.Exit(1)
59 | }
60 |
61 | var c []Page
62 | json.Unmarshal(raw, &c)
63 | return c
64 | }
65 | // File: example_json.go ends
66 |
--------------------------------------------------------------------------------
/code/example-procedue-pig.go:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------------
2 | // Copyright 2011 The Go Authors. All rights reserved.
3 | //
4 | // File: example_procedue_pig.go
5 | // Description : go run example_procedue_pig.go
6 | // https://golang.org/doc/codewalk/functions/
7 | //
8 | // https://cheatsheet.dennyzhang.com/cheatsheet-golang-A4
9 | // --
10 | // Created : <2018-04-07>
11 | // Updated: Time-stamp: <2018-10-06 16:40:26>
12 | //-------------------------------------------------------------------
13 | package main
14 |
15 | import (
16 | "fmt"
17 | "math/rand"
18 | )
19 |
20 | const (
21 | win = 100 // The winning score in a game of Pig
22 | gamesPerSeries = 10 // The number of games per series to simulate
23 | )
24 |
25 | // A score includes scores accumulated in previous turns for each player,
26 | // as well as the points scored by the current player in this turn.
27 | type score struct {
28 | player, opponent, thisTurn int
29 | }
30 |
31 | // An action transitions stochastically to a resulting score.
32 | type action func(current score) (result score, turnIsOver bool)
33 |
34 | // roll returns the (result, turnIsOver) outcome of simulating a die roll.
35 | // If the roll value is 1, then thisTurn score is abandoned, and the players'
36 | // roles swap. Otherwise, the roll value is added to thisTurn.
37 | func roll(s score) (score, bool) {
38 | outcome := rand.Intn(6) + 1 // A random int in [1, 6]
39 | if outcome == 1 {
40 | return score{s.opponent, s.player, 0}, true
41 | }
42 | return score{s.player, s.opponent, outcome + s.thisTurn}, false
43 | }
44 |
45 | // stay returns the (result, turnIsOver) outcome of staying.
46 | // thisTurn score is added to the player's score, and the players' roles swap.
47 | func stay(s score) (score, bool) {
48 | return score{s.opponent, s.player + s.thisTurn, 0}, true
49 | }
50 |
51 | // A strategy chooses an action for any given score.
52 | type strategy func(score) action
53 |
54 | // stayAtK returns a strategy that rolls until thisTurn is at least k, then stays.
55 | func stayAtK(k int) strategy {
56 | return func(s score) action {
57 | if s.thisTurn >= k {
58 | return stay
59 | }
60 | return roll
61 | }
62 | }
63 |
64 | // play simulates a Pig game and returns the winner (0 or 1).
65 | func play(strategy0, strategy1 strategy) int {
66 | strategies := []strategy{strategy0, strategy1}
67 | var s score
68 | var turnIsOver bool
69 | currentPlayer := rand.Intn(2) // Randomly decide who plays first
70 | for s.player+s.thisTurn < win {
71 | action := strategies[currentPlayer](s)
72 | s, turnIsOver = action(s)
73 | if turnIsOver {
74 | currentPlayer = (currentPlayer + 1) % 2
75 | }
76 | }
77 | return currentPlayer
78 | }
79 |
80 | // roundRobin simulates a series of games between every pair of strategies.
81 | func roundRobin(strategies []strategy) ([]int, int) {
82 | wins := make([]int, len(strategies))
83 | for i := 0; i < len(strategies); i++ {
84 | for j := i + 1; j < len(strategies); j++ {
85 | for k := 0; k < gamesPerSeries; k++ {
86 | winner := play(strategies[i], strategies[j])
87 | if winner == 0 {
88 | wins[i]++
89 | } else {
90 | wins[j]++
91 | }
92 | }
93 | }
94 | }
95 | gamesPerStrategy := gamesPerSeries * (len(strategies) - 1) // no self play
96 | return wins, gamesPerStrategy
97 | }
98 |
99 | // ratioString takes a list of integer values and returns a string that lists
100 | // each value and its percentage of the sum of all values.
101 | // e.g., ratios(1, 2, 3) = "1/6 (16.7%), 2/6 (33.3%), 3/6 (50.0%)"
102 | func ratioString(vals ...int) string {
103 | total := 0
104 | for _, val := range vals {
105 | total += val
106 | }
107 | s := ""
108 | for _, val := range vals {
109 | if s != "" {
110 | s += ", "
111 | }
112 | pct := 100 * float64(val) / float64(total)
113 | s += fmt.Sprintf("%d/%d (%0.1f%%)", val, total, pct)
114 | }
115 | return s
116 | }
117 |
118 | func main() {
119 | strategies := make([]strategy, win)
120 | for k := range strategies {
121 | strategies[k] = stayAtK(k + 1)
122 | }
123 | wins, games := roundRobin(strategies)
124 |
125 | for k := range strategies {
126 | fmt.Printf("Wins, losses staying at k =% 4d: %s\n",
127 | k+1, ratioString(wins[k], games-wins[k]))
128 | }
129 | }
130 | // File: example_procedue_pig.go ends
131 |
--------------------------------------------------------------------------------
/code/example-read-file.go:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------------
2 | // @copyright 2018 DennyZhang.com
3 | // Licensed under MIT
4 | // https://www.dennyzhang.com/wp-content/mit_license.txt
5 | //
6 | // File: example_file.go
7 | // Author : Denny
8 | // Description : go run example_file.go
9 | // Link: https://www.golang-book.com/books/intro/13
10 | // https://cheatsheet.dennyzhang.com/cheatsheet-golang-A4
11 | // --
12 | // Created : <2018-04-07>
13 | // Updated: Time-stamp: <2018-10-06 16:40:26>
14 | //-------------------------------------------------------------------
15 | package main
16 |
17 | import (
18 | "fmt"
19 | "os"
20 | )
21 |
22 | func main() {
23 | file, err := os.Open("test.txt")
24 | if err != nil {
25 | // handle the error here
26 | return
27 | }
28 | defer file.Close()
29 |
30 | // get the file size
31 | stat, err := file.Stat()
32 | if err != nil {
33 | return
34 | }
35 | // read the file
36 | bs := make([]byte, stat.Size())
37 | _, err = file.Read(bs)
38 | if err != nil {
39 | return
40 | }
41 |
42 | str := string(bs)
43 | fmt.Println(str)
44 | }
45 | // File: example_file.go ends
46 |
--------------------------------------------------------------------------------
/code/example-switch.go:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------------
2 | // @copyright 2018 DennyZhang.com
3 | // Licensed under MIT
4 | // https://www.dennyzhang.com/wp-content/mit_license.txt
5 | //
6 | // Author : Denny
7 | // Description :
8 | // https://cheatsheet.dennyzhang.com/cheatsheet-golang-A4
9 | // --
10 | // Created : <2018-04-07>
11 | // Updated: Time-stamp: <2018-11-17 11:54:31>
12 | //-------------------------------------------------------------------
13 | // https://tour.golang.org/flowcontrol/9
14 | package main
15 |
16 | import (
17 | "fmt"
18 | "runtime"
19 | )
20 |
21 | func example1()
22 | fmt.Print("Go runs on ")
23 | switch os := runtime.GOOS; os {
24 | case "darwin":
25 | fmt.Println("OS X.")
26 | case "linux":
27 | fmt.Println("Linux.")
28 | default:
29 | // freebsd, openbsd,
30 | // plan9, windows...
31 | fmt.Printf("%s.", os)
32 | }
33 | }
34 |
35 | // https://gobyexample.com/switch
36 | func example2() {
37 | t := time.Now()
38 | switch {
39 | case t.Hour() < 12:
40 | fmt.Println("It's before noon")
41 | default:
42 | fmt.Println("It's after noon")
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/code/example-write-file.go:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------------
2 | // @copyright 2018 DennyZhang.com
3 | // Licensed under MIT
4 | // https://www.dennyzhang.com/wp-content/mit_license.txt
5 | //
6 | // File: example_write_file.go
7 | // Author : Denny
8 | // Description : go run example_write_file.go
9 | // Link: https://www.golang-book.com/books/intro/13
10 | // https://cheatsheet.dennyzhang.com/cheatsheet-golang-A4
11 | // --
12 | // Created : <2018-04-07>
13 | // Updated: Time-stamp: <2018-10-06 16:40:26>
14 | //-------------------------------------------------------------------
15 | package main
16 |
17 | import (
18 | "fmt"
19 | "os"
20 | )
21 |
22 | func main() {
23 | // https://stackoverflow.com/questions/7151261/append-to-a-file-in-go
24 | file, err := os.OpenFile("/tmp/test.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
25 | if err != nil {
26 | // handle the error here
27 | fmt.Print("Cannot create file", err)
28 | return
29 | }
30 | defer file.Close()
31 | fmt.Fprintf(file, "hello: %s\n", "world")
32 | fmt.Fprint(file, "closing the file\n")
33 | }
34 | // File: example_write_file.go ends
35 |
--------------------------------------------------------------------------------
/code/helloworld.go:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------------
2 | // @copyright 2017 DennyZhang.com
3 | // Licensed under MIT
4 | // https://www.dennyzhang.com/wp-content/mit_license.txt
5 | //
6 | // File: helloworld.go
7 | // Author : Denny
8 | // Description :
9 | // https://cheatsheet.dennyzhang.com/cheatsheet-golang-A4
10 | // --
11 | // Created : <2018-04-07>
12 | // Updated: Time-stamp: <2018-10-06 16:40:26>
13 | //-------------------------------------------------------------------
14 | package main
15 |
16 | import (
17 | "fmt"
18 | )
19 |
20 | func main() {
21 | msg := "hello world\n";
22 | // print sample message
23 | fmt.Print(msg)
24 | }
25 | // File: helloworld.go ends
26 |
--------------------------------------------------------------------------------
/code/interface-conversion.go:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------------
2 | // @copyright 2018 DennyZhang.com
3 | // Licensed under MIT
4 | // https://www.dennyzhang.com/wp-content/mit_license.txt
5 | //
6 | // File: interface_conversion.go
7 | // Author : Denny
8 | // Description : go run interface_conversion.go
9 | // Link: https://www.golang-book.com/books/intro/13
10 | // https://cheatsheet.dennyzhang.com/cheatsheet-golang-A4
11 | // --
12 | // Created : <2018-04-07>
13 | // Updated: Time-stamp: <2018-10-06 16:40:25>
14 | //-------------------------------------------------------------------
15 | package main
16 |
17 | import (
18 | "fmt"
19 | )
20 |
21 | func main() {
22 | // https://stackoverflow.com/questions/26975880/convert-mapinterface-interface-to-mapstringstring
23 | m := make(map[interface{}]interface{})
24 | m["foo"] = "bar"
25 |
26 | m2 := make(map[string]string)
27 |
28 | for key, value := range m {
29 | switch key := key.(type) {
30 | case string:
31 | switch value := value.(type) {
32 | case string:
33 | m2[key] = value
34 | fmt.Println(key, ":", value)
35 | }
36 | }
37 | }
38 | }
39 | // File: interface_conversion.go ends
40 |
--------------------------------------------------------------------------------
/code/pointer-array.go:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------------
2 | // @copyright 2017 DennyZhang.com
3 | // Licensed under MIT
4 | // https://www.dennyzhang.com/wp-content/mit_license.txt
5 | //
6 | // File: helloworld.go
7 | // Author : Denny
8 | // Description :
9 | // https://cheatsheet.dennyzhang.com/cheatsheet-golang-A4
10 | // --
11 | // Created : <2018-04-07>
12 | // Updated: Time-stamp: <2018-10-06 16:40:15>
13 | //-------------------------------------------------------------------
14 | package main
15 |
16 | import (
17 | "fmt"
18 | )
19 |
20 | func main() {
21 | A := []int{1, 2, 3}
22 | B := &A
23 | fmt.Println((*B)[2])
24 | fmt.Println(B)
25 | }
26 |
--------------------------------------------------------------------------------
/misc/pages.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "id": 1,
4 | "title": "About Us",
5 | "url": "/about-us"
6 | },
7 | {
8 | "id": 2,
9 | "title": "Team",
10 | "url": "/team"
11 | },
12 | {
13 | "id": 3,
14 | "title": "Projects",
15 | "url": "/projects"
16 | },
17 | {
18 | "id": 4,
19 | "title": "Hire Us",
20 | "url": "/hire-us"
21 | }
22 | ]
--------------------------------------------------------------------------------