How I Learn Golang Goroutines in 1 Day

> Learn Golang Basics here

Goroutines & Concurrent

Goroutines

View day2.go file

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package main

import (
"fmt"
"time"
)

func main() {
chanChanChanChan()
bufferedChan()
synchronizeTask()
pingPongGame()
selectChannel()
outOfTime()
nonBlockingChannelWithSelect()
closeChannel()
rangeOverChannel()
doSomethingLater()
doInterval()
}

func chanChanChanChan() {
chan1 := make(chan string)
chan2 := make(chan string)

// By default sends and receives block until both the sender and receiver are ready.
go func() {
fmt.Println("[1] Passing chan2 !")
chan2 <- "Chan2"
fmt.Println("[1] Passed chan2 !")
}()

go func() {
fmt.Println("[1] Receiving chan2 !")
chan2Msg := <-chan2
fmt.Println("[1] Received chan2 !")

chan2Msg += " Chan1"

fmt.Println("[1] Passing chan1 !")
chan1 <- chan2Msg
fmt.Println("[1] Passed chan1 !")
}()

fmt.Println("[1] Waiting for chan1 message ...")
msg := <-chan1
fmt.Println("[1] Message from goroutines :", msg)
}

func bufferedChan() {
chan1 := make(chan string, 2) // second parameter is number of messages the channel will handle, it creates Buffered Channel

go func() {
fmt.Println("[2] Passing chan2 !")
chan1 <- "Chan2" // Buffered Chan doesn't need to wait concurrent receiving
fmt.Println("[2] Passed chan2 !")
}()

go func() {
fmt.Println("[2] Passing chan1 !")
chan1 <- "Chan1" // Buffered Chan doesn't need to wait concurrent receiving
fmt.Println("[2] Passed chan1 !")
}()

fmt.Println("[2] Waiting for chan1 message ...")
time.Sleep(time.Second * 3) // Wait 3 seconds to wait message passing to buff chan
msg := <-chan1
msg += <-chan1
fmt.Println("[2] Message from buffered chan :")
}

func synchronizeTask() {
done := make(chan bool)

go func(ok chan bool) {
fmt.Println("[3] Working ...")
time.Sleep(time.Second)
fmt.Println("[3] Done ...")

ok <- true
}(done)

<-done
fmt.Println("[3] Lets relax !")
}

// Channel direction
func ping(rchan chan<- string, msg string) {
rchan <- msg
}

func pong(rchan <-chan string, schan chan<- string) {
tmp := <-rchan
schan <- tmp
}

func pingPongGame() {
chan1 := make(chan string, 1)
chan2 := make(chan string, 1)

ping(chan1, "Game over !")
pong(chan1, chan2)
pingPongMsg := <-chan2
fmt.Println("[4] Ping pong message :", pingPongMsg)
}

func selectChannel() {
c1 := make(chan string)
c2 := make(chan string)

go func() {
time.Sleep(time.Second)
c1 <- "msg1"
}()

go func() {
time.Sleep(time.Second * 2)
c2 <- "msg2"
}()

// Wait multi channel, whole func take ~2 seconds because of sleeping concurrently
for i := 0; i < 2; i++ {
select {
case msg1 := <-c1:
fmt.Println("[5] Received :", msg1)
case msg2 := <-c2:
fmt.Println("[5] Received :", msg2)
}
}
}

func outOfTime() { // Timeout using select channel
chan1 := make(chan string)

go func() {
time.Sleep(time.Second * 2)
chan1 <- "here result after 2 seconds"
}()

select {
case msg := <-chan1:
fmt.Println("[6] Message from chan1", msg)
case <-time.After(time.Second):
fmt.Println("[6] Your time is out ! You only have 1 second !")
}
}

func nonBlockingChannelWithSelect() {
chan1 := make(chan string)

select {
case msg := <-chan1:
fmt.Println("[7] Ahh... got it !", msg)
default:
fmt.Println("[7] Nothing here !")
}
}

func closeChannel() {
jobs := make(chan string, 3)
done := make(chan bool)

go func() {
for {
j, more := <-jobs
if more {
fmt.Println("[8] received a job", j)
} else {
fmt.Println("[8] received all jobs")
done <- true
}
}
}()

for i := 0; i < 3; i++ {
jobs <- "hahaha"
fmt.Println("[8] sent a job")
}
close(jobs)
fmt.Println("[8] sent all jobs")

<-done
}

func rangeOverChannel() {
chan1 := make(chan string, 3)
chan1 <- "1"
chan1 <- "2"
chan1 <- "3"

close(chan1)
for msg := range chan1 {
fmt.Println("[9] range over :", msg)
}
}

func doSomethingLater() {
timer1 := time.NewTimer(time.Second * 2)

<-timer1.C
fmt.Println("[10] timer1 is expired")

timer2 := time.NewTicker(time.Second * 2)
go func() {
<-timer2.C
fmt.Println("[10] timer2 is expired")
}()
timer2.Stop()
fmt.Println("[10] timer2 is stopped")
}

func doInterval() {
ticker := time.NewTicker(time.Millisecond * 500)
go func() {
for t := range ticker.C {
fmt.Println("[11] do job interval at", t)
}
}()
time.Sleep(time.Second * 3)
ticker.Stop()
fmt.Println("[11] Ticker is stopped")
}

Ref:

  • Lesson structure by gobyexample(dot)com
  • Photo by tensor-programming(dot)com

How I Learn Golang Basics in 1 Day

golang

Structure is based on Learn Go in Y Minutes

Install Go

Follow this guide : https://golang.org/doc/install

Compile and Run go code every 1 second

1
$ watch -d -t -n 1 go run day1.go

Use VisualStudio Code

Basics

View day1.go file

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package main

import (
"fmt" // Formatting standard library
m "math" // Alias an imported lib
"strconv" // String conversion lib
"net/http"
"io/ioutil"
)

func main() {
fmt.Println("Hello World ! go go go")

moveIt()
}

func moveIt() {
var x float64 // Declare variable
x = 3 // Assign it to a value
y := 4. // Declare and assign in 1-line
fmt.Println(x, y, pythagore(x, y))

goToTypes()
followTheFlow()
hmmmLikeClosure()
doItTommorow()
smashInterfaces()
learnVariadicParams("hello", "khanhicetea", "a human")
oopsSomethingWrong()
goToWWW()

fmt.Println("\n-------- THE END --------\n")
}

func pythagore(a float64, b float64) (float64) { // func [function name]( ...paramers ) (return types)
return m.Sqrt(a * a + b * b)
}

func goToTypes() {
a1 := 1 // Int
a2 := 2.3 // Float
a3 := "ほげほげ !!!" // Japanese string, lol
a4 := 's' // Char, alias for int32, hold unicode code
a5 := `This is "quoted" string,
with new line and tab`
a6 := byte('\n') // ASCII char, uint8
fmt.Println(a1, a2, a3, a4, a5, a6)

// Arrays
var a7 [3]int // declare fixed array of 3 integer items
a7[0] = 12
a7[1] = 23
a7[2] = 34

a8 := [...]int{1,1,2,3,5,8,13} // no need count array length to declare
fmt.Println(a7, a8)

// Slices
a9 := []int{1,2,3}
a10 := make([]int, 3) // Allocate slide 3 ints, 0 intial value

var a11 [][]float64 // declare only
a12 := []byte("hello") // convert string to slice of chars

fmt.Println(a9, a10, a11, a12)

a9 = append(a9, 4, 5, 6) // append 3 items
fmt.Println(a9)

a13 := []int{10, 11}
a9 = append(a9, []int{7, 8, 9}...) // merge 2 slices with suffix ...
a9 = append(a9, a13...)
fmt.Println(a9)

a14 := "ignored value"
_ = a14 // Ignore by _ , unused variable cause error

a15 := map[string]int{
"one": 1,
"two": 2,
"there": 3,
}
a15["four"] = 4

fmt.Println(a15, a15["two"])

a16, a17 := memoryZoo()
fmt.Println(*a16, a17)
}

func memoryZoo() (a, b *int) {
s := make([]int, 5)
s[3] = 4
o := 123

a = &s[3] // can assign to returned var
b = &o // & is ref memory address, like a pointer in C

return // no need pass returned vars here
}

func followTheFlow() {
if 1 + 1 == 2 {
fmt.Println("Hmm .. it must me 10 ! Ya know ;)")
}

if 1 > 2 {
fmt.Println("Universe goes down !")
} else if 42 > 24 {
fmt.Println("node_modules size is heavier than backhole !")
} else {
fmt.Println("Okay, I'm drunk")
}

a18 := 3

switch a18 {
case 1:
case 2: // cases don't fall down like C-like lang
case 3:
fmt.Println("Three !!")
default:
}

for i := 0; i < 3; i++ {
fmt.Println(i)
}

numbers := map[string]int{
"a": 1,
"b": 2,
"c": 5,
}

for key, num := range numbers { // loop a map
fmt.Println(key, num)
}

for _, num := range numbers { // loop a map, no need key
fmt.Println(num)
}

if a14 := 3 * 4; a14 < 13 { // last statement is condition
fmt.Println("3 * 4 < 13")
}
}

func hmmmLikeClosure() {
a15 := add(15)
a16 := a15(5)
fmt.Println(a16)
}

func add(x int) func(y int) int {
return func (y int) int {
return x + y
}
}

func doItTommorow() {
a17 := testMyCode()
fmt.Println(a17)
}

func testMyCode() int {
defer fmt.Println("456") // defer : run before return
fmt.Println("0")
defer fmt.Println("789") // defer : run in LIFO order.
return 123
}

type Stringer interface {
String() string
}

type Point struct {
x, y int
}

func (p Point) String() string {
return fmt.Sprintf("(%d, %d)", p.x, p.y)
}

func smashInterfaces() {
p := Point{3, 4}
fmt.Println(p.String())

var i Stringer // Declare i as Stringer interface
i = p // Point implement Stringer interface
fmt.Println(i.String())
}

func learnVariadicParams(strings ...interface{}) {
// Iterate each value of the variadic.
for _, s := range strings {
fmt.Println("param :", s)
}

// Pass variadic value as a variadic parameter.
fmt.Println("params :", fmt.Sprintln(strings...))
}

func oopsSomethingWrong() {
numbers := map[string]int{
"a": 1,
"b": 2,
"c": 5,
}

if x, ok := numbers["d"]; !ok {
fmt.Println("Oops something went wrong !!!")
} else {
fmt.Println(x)
}

a18 := "1.2"
if _, err := strconv.ParseInt(a18, 10, 8); err != nil { // check if err
fmt.Println("true === false")
}
}

func goToWWW() {
go func() {
err:= http.ListenAndServe("127.0.0.1:8888", &WebServer{"KhanhIceTea server"})
fmt.Println(err)
}()

crawlWeb()
}

type WebServer struct {
name string
}

func (ws *WebServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello from "))
w.Write([]byte(ws.name))
}

func crawlWeb() {
resp, err := http.Get("http://127.0.0.1:8888")
fmt.Println(err)
defer resp.Body.Close() // Close body stream
body, err := ioutil.ReadAll(resp.Body)
fmt.Println("\nWebServer said : `%s`", string(body))
}

Please ! Teach me !

> Learn Golang Goroutines and Concurrent here

Learn TypeScript Basics in 2 days

Install TypeScript and TSLint

1
$ npm install -g typescript tslint

Compile ts files on changes

1
$ tsc -w

Use VisualStudioCode

Basics

View day2.ts file

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// Data types in TypeScript
let a: boolean = false;
let b: number = 42;
let c: string = "Helo";
let d: any = "this is anything but not `never`"
let e: never; // Can not assign to never type

// Function Interface
let f: Function = function f() {};

// Ommit data type (TypeScript auto detect it if it can)
let g = "YOLO, Who needs type ?"

// Array or Collections
let h: number[] = [1,2,3]; // Short syntax
let i: Array<number> = [4,5,6]; // Array type

// Emum
enum Gender { MALE, FEMALE } // Start from MALE = 0
let gender: Gender = Gender.FEMALE;
enum Ranking { FIRST = 1, SECOND, THIRD } // Specify a custom start number
let ranking: Ranking = Ranking.SECOND; // 2
enum OrderStatus { WAITING = "waiting", PROCESSING = "processing", COMPLETED = "completed"}
let orderStatus : OrderStatus = OrderStatus.PROCESSING; // processing

// Typehint on parameters and returned value
function sum(a: number, b: number): number {
return a + b;
}

// void : mean no returning a value
function hello(name: string): void {
console.log("Hello " + name);
}

// Fat arrow
let func1 = (x: number) => { return x * 2; } // return type inferred
let func2 = (x: number) : number => { return x * 2; } // explicit return type
let func3 = (x: number) => x * 2; // return type inferred without braces

// Interface : contract for properties, methods of class
interface Field {
name: string;
data_type: string;
}
interface Model {
name: string; // property
primary_key?: string; // ? marked for optional
fields: Array<Field>; // Nested another interface
save(): Model; // return itself
}

// Object implements interface
let userModel: Model = {
name: "user",
fields: [
{ name: "id", data_type: "number"},
{ name: "username", data_type: "string"},
{ name: "password", data_type: "string"},
],
save: function () {
return this;
}
}

// Interface for function
interface EasingFunction {
(currentTime: number, startValue: number, endValue: number, duration: number): number
}

let cubicEasing: EasingFunction;
cubicEasing = function(currentTime: number, startValue: number, endValue: number, duration: number): number {
const t = currentTime / duration;
const distance = endValue - startValue;
return distance*t*t*t + startValue;
}

// Short interface for function
let f5: (x: number) => void = (x: number) => { console.log(x) }
f5(123);
let f6 = (x: number) => { console.log(x) }
f6(456);
let f7 = () => { console.log('Inferred interface') }
f7();

// Classes
class Point {
// property
x: number;

constructor(x: number, public y: number = 0) { // can declare "y" in constructor
this.x = x;
}

// method
dist(): number { return Math.sqrt(this.x * this.x + this.y * this.y); }

// static
static origin = new Point(0, 0);
}

let p1: Point = new Point(1, 2); // (1; 2)
let p2: Point = new Point(10); // (10; 0)

class Point3D extends Point {
constructor(x: number, public y: number = 0, public z: number = 0) {
super(x, y); // overide constructor must use `super`
}

dist(): number {
const d = super.dist();
return Math.sqrt(d * d + this.z * this.z);
}

static origin = new Point3D(0, 0, 0);
}

// Module
module Database {
export class Connection {
user: string;
passwd: string;

constructor(
user: string,
passwd: string,
public host: string = "127.0.0.1",
public port: number = 3306
) {
this.user = user;
this.passwd = passwd;
}
connect(): void {
// do something to connect
}
}
}

const dbConnection = new Database.Connection("root", "hardtoguessme");
dbConnection.connect();

// Generics
class List<T> {
protected items: T[] = [];
push(item: T) {
this.items.push(item);
}
}

const listOfPoint = new List<Point>();
listOfPoint.push(new Point(1, 4));
listOfPoint.push(Point.origin);

// String Interpolation with Template Strings
let myName: string = "KhanhIceTea";
let helloString = `Hello ${myName},
how is it going ? :))`; // Multiline is supported
console.log(helloString);

// WELL DONE
console.log("Well done !!!! WELCOME TO TYPESCRIPT !!!");

Learn Webpack Basics in 2 days

Introduction

Learn from https://webpack.js.org/guides/getting-started/

Clone my repo to follow commit hash by section : https://github.com/khanhicetea/learn-n-earn

Day 1 , <51ede10>

webpack.config.js

1
2
3
4
5
6
7
8
9
const path = require('path');

module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};

Bash

1
$ ./node_modules/.bin/webpack --config webpack.config.js

Learned

  • entry : start point to dive in dependency graph.
  • output : output after pack the web modules
    • filename : bundle filename
    • path : dist path

Day 2

Import assets , <07591ed>

  • CSS file : use style-loader and css-loader
  • Image file : use file-loader
  • WebFont file : use file-loader
  • Data file use json-loader, xml-loader or csv-loader
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
],
},
{
test: /\.(png|jpe?g|gif|webp)$/,
use: [
'file-loader'
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader'
]
}
]
}

Dynamic output and entry ,

entry config can be a dictionary where key is entry name and value is entry file path
output.filename could use [name] in syntax to generate dynamic output filename

1
2
3
4
5
6
7
8
9
10
module.exports = {
entry: {
app: './src/index.js',
print: './src/print.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};

HtmlWebpackPlugin

HtmlWebpackPlugin by default will generate its own index.html file, even though we already have one in the dist/ folder

1
npm install html-webpack-plugin --save-dev

Cleaning /dist folder

To clean up dist folder automatically !

1
npm install clean-webpack-plugin --save-dev
1
2
3
4
5
6
const CleanWebpackPlugin = require('clean-webpack-plugin');

...
plugins: [
new HtmlWebpackPlugin(['dist']),
],

Development

Source map , <4eea0dc>

To enable source map for js and css file, use inline-source-map option in devtool config

1
2
3
4
5
...
devtool: 'inline-source-map',
plugins: [
...
],

ONLY USE THIS OPTION FOR DEVELOPMENT MODE

Development server (watch file changes) ,

  • watch mode : add option --watch to webpack cli run command
  • webpack-dev-server : use npm package webpack-dev-server and add devServer: { contentBase: './dist' } to webpack config, when start a dev server use another command instead webpack-dev-server --open
  • express webpack-dev-middleware : use webpack-dev-middleware as Express middleware

Ready for production , <1ddcee3>

Tree shaking

Tree shaking is a term commonly used in the JavaScript context for dead-code elimination. It relies on the static structure of ES2015 module syntax, i.e. import and export.

1
$ npm install --save-dev uglifyjs-webpack-plugin
1
2
3
4
5
6
7
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

...
plugins: [
...
new UglifyJSPlugin(),
]

ONLY USE IN PRODUCTION WEBPACK CONFIG

Setup multi environments ,

1
$ npm install --save-dev webpack-merge

webpack.common.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
entry: {
app: './src/index.js',
print: './src/print.js'
},
plugins: [
new HtmlWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Output Management'
}),
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};

webpack.dev.js

1
2
3
4
5
6
7
8
9
const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
devtool: 'inline-source-map',
devServer: {
contentBase: './dist'
}
});

webpack.prod.js

1
2
3
4
5
6
7
8
9
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = merge(common, {
plugins: [
new UglifyJSPlugin()
]
});

package.json

1
2
3
4
"scripts": {
"build": "webpack --config webpack.prod.js",
"dev": "webpack-dev-server --open --config webpack.dev.js"
}

Run command

  • npm run dev : running dev server with hot reload
  • npm run build : build production dist

Specify the Environment

Many libraries will key off the process.env.NODE_ENV variable to determine what should be included in the library. We can use webpack’s built in DefinePlugin to define this variable for all our dependencies

webpack.prod.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const webpack = require('webpack');
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = merge(common, {
plugins: [
new UglifyJSPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
]
});