-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathintro-golang.txt
312 lines (219 loc) · 7.6 KB
/
intro-golang.txt
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
Learning Go
Workshop: Building a Todo application in Go using Cobra
-Introduction to the Go Programming Language
-CLI application design
-Introduction to the Cobra CLI framework (used by Kubernetes, Docker, Hugo, etc)
-GOPATH
-The Go toolset uses an environment variable called GOPATH to find & store Go source code.
-You can set GOPATH to anything you want, but its easier if its set in your home directory.
GO ENV check
-go env
-Check for GOPATH="/Users/vic/go"
-env | grep "PATH="
-Check for PATH= (to include) ..:/Users/vic/go/bin:...
GoLand IDE
Windows
setx GOPATH %USERPROFILE%\go
-------------------------------------------------
Project Steps
-------------------------------------------------
1. Initialize a Go module
In the root of your project, run:
go mod init <module_name>
2.Install Cobra
go get -u -v github.com/spf13/cobra@latest
The go get command is used to download and install packages.
3. Using Cobra
import "github.com/spf13/cobra"
Example of Using Cobra
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func main() {
var rootCmd = &cobra.Command{
Use: "app",
Short: "My Cobra Application",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello, Cobra!")
},
}
rootCmd.Execute()
}
What is Cobra?
Cobra is a library in Go used for building CLI applications. It was originally developed as the basis for the "kubectl" command-line tool used in Kubernetes, and has since become one of the most popular tools for creating CLIs in Go.
With Cobra, developers can build apps that can process commands, flags, and arguments. Good for simple and complex CLI tools. Cobra works well with Go's 'flag' package but provides an easier and more scalable way to manage command-line tools.
-Commands: (can be nested) i.e. kubectl get pods
-Flags: i.e. kubectl get ds --all-namespaces
-Arguments: optional
Supports customizable error handling and exit codes for more graceful command failures.
You can add middleware that runs before or after commands, or even change how commands are parsed and executed.
Integrates with Viper for Configuration.
-can handle configuration files, environment variables, and flags all in one place.
Other Features
Hooks (PreRun and PostRun)
Command Auto-Completion
Command Aliases
Persistent Flags and Local Flags
Custom Help and Usage Output
Extensibility and Middleware
Example of Using Cobra
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func main() {
var rootCmd = &cobra.Command{
Use: "app",
Short: "A CLI tool for managing files and users",
}
var userCmd = &cobra.Command{
Use: "user",
Short: "Manage users",
}
var addUserCmd = &cobra.Command{
Use: "add",
Short: "Add a new user",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("User added!")
},
}
var fileCmd = &cobra.Command{
Use: "file",
Short: "Manage files",
}
var uploadFileCmd = &cobra.Command{
Use: "upload",
Short: "Upload a file",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("File uploaded!")
},
}
// Create root command and add subcommands
userCmd.AddCommand(addUserCmd)
fileCmd.AddCommand(uploadFileCmd)
rootCmd.AddCommand(userCmd, fileCmd)
// Execute the root command
rootCmd.Execute()
}
-------------------------------------------------
Our first program will print the classic “hello world” message. Here’s the full source code.
To run the program, put the code in hello-world.go and use go run.
Sometimes we’ll want to build our programs into binaries. We can do this using go build.
We can then execute the built binary directly.
Go has various value types including strings, integers, floats, booleans, etc. Here are a few basic examples.
Strings, which can be added together with +.
Integers and floats.
Booleans, with boolean operators as you’d expect.
In Go, variables are explicitly declared and used by the compiler to e.g. check type-correctness of function calls.
var declares 1 or more variables.
You can declare multiple variables at once.
Go will infer the type of initialized variables.
Variables declared without a corresponding initialization are zero-valued. For example, the zero value for an int is 0.
The := syntax is shorthand for declaring and initializing a variable, e.g. for var f string = "apple" in this case. This syntax is only available inside functions. f := "apple"
-------------------------------------------------
Go is a statically typed language
-You need to tell Go Compiler, the data type when declaring the variable
-Type Inference: But Go can infer the type when you assign a value
-More Robust, reduces the likelihood of errors
-Big advantage of Go is you get to discover mistakes at compile time, not just at runtime.
-To create a variable and assign it a value, without using var, you can use the := operator.
-This is called a short variable declaration.
-It is shorthand for declaring and initializing a variable, e.g. for var f string = "apple" in this case. This syntax is only available inside functions. f := "apple"
Data Types
-Strings
-Integer Types (can be signed or unsigned, with length of the integer)
* uint - positive whole numbers
* int - whole numbers (can be negative)
-uint8
-uint16
-uint32
-uint64
-int8
-int16
-int32
-int64
-Floating Types
* float - numbers that contain a decimal component (1.434, 421.6)
* complex - numbers that contain a real and imaginary part
-float32
-float64
-complex64
-complex128
-Arrays & Slices
In Go, you cannot directly push to an array since arrays have a fixed size. Instead, you can use a slice, which is a dynamically-sized array. Here is how you can modify your code to use a slice and append elements to it
-Maps
-Structs
-Booleans
More Topics
-Pointers
-Functions
In Go, functions that are intended to be exported (i.e., accessible from other packages) should start with an uppercase letter. Functions that are intended to be unexported (i.e., only accessible within the same package) should start with a lowercase letter. This follows the Go convention for visibility:
Exported function (accessible from other packages):
func ExportedFunction() {
// Function implementation
}
Unexported function (only accessible within the same package):
func unexportedFunction() {
// Function implementation
}
-Interfaces
-Errors
-Constants
-Variables
-Loops
-Conditionals
-Defer
-Panic
-Recover
-Go Routines
-Channels
-Select
-Range
-Timeouts
-Tickers
-Worker Pools
-WaitGroups
-Mutexes
-Atomic Counters
-Context
-Testing
-Reflection
-File I/O
-Reading Files
-Writing Files
-Deleting Files
-Working with Directories
-Working with Paths
-Command Line Arguments
-Command Line Flags
-Environment Variables
-HTTP Clients
-HTTP Servers
-JSON
-XML
-CSV
-Template
-Websockets
-Context
-Top Packages
-"fmt" package
-Different functions for:
-Formatted Input and Output (I/O)
-Print Messages
-Println
-Printf
-Print
-Collect User Input
-Scanln
-Scanf
-Scan
-Write into a File
-Read from a File
-------------------------------------------------
In Go, file names typically use snake_case, and variable names use camelCase. Here is an example:
File name: custom_worker.go
Variable name: customWorker
This convention helps maintain consistency and readability across Go projects.