├── README.md
├── scripts
├── arrays
│ └── arrays.go
├── channels
│ ├── bufchan.go
│ ├── close.go
│ ├── data
│ │ ├── f1.txt
│ │ └── f2.txt
│ ├── main.go
│ ├── patterns
│ │ ├── async.go
│ │ ├── fan-in.go
│ │ ├── fan-out.go
│ │ ├── pipeline.go
│ │ ├── throttle.go
│ │ └── workers.go
│ ├── select-chan.go
│ ├── send-recv.go
│ └── simple.go
├── closures
│ ├── go.mod
│ └── main.go
├── cmd-args
│ ├── flag.go
│ ├── flag_ref.go
│ ├── help.go
│ └── main.go
├── conditionals
│ ├── if_else.go
│ └── switch.go
├── date-time
│ ├── arithmetic.go
│ ├── duration.go
│ ├── main.go
│ ├── sleep.go
│ └── timezone.go
├── defer
│ └── defer.go
├── errors
│ ├── custom.go
│ ├── custom_error.go
│ ├── errors.go
│ ├── file-read.go
│ ├── main.go
│ └── web.go
├── files
│ ├── read
│ │ ├── char.go
│ │ ├── chunks.go
│ │ ├── config_files
│ │ │ ├── csv
│ │ │ │ ├── blog.csv
│ │ │ │ ├── csv.go
│ │ │ │ ├── go.mod
│ │ │ │ └── temp.csv
│ │ │ ├── go.mod
│ │ │ ├── go.sum
│ │ │ ├── json
│ │ │ │ ├── blog.json
│ │ │ │ ├── go.mod
│ │ │ │ └── json.go
│ │ │ ├── main.go
│ │ │ ├── toml
│ │ │ │ ├── blog.toml
│ │ │ │ ├── go.mod
│ │ │ │ ├── go.sum
│ │ │ │ └── toml.go
│ │ │ ├── xml
│ │ │ │ ├── rss.go
│ │ │ │ ├── rss.xml
│ │ │ │ └── xml.go
│ │ │ └── yaml
│ │ │ │ ├── blog.yaml
│ │ │ │ ├── go.mod
│ │ │ │ ├── go.sum
│ │ │ │ └── yaml.go
│ │ ├── delimeter.txt
│ │ ├── delimiter.go
│ │ ├── line.go
│ │ ├── main.go
│ │ ├── sample.txt
│ │ └── word.go
│ └── write
│ │ ├── abc.txt
│ │ ├── append.go
│ │ ├── delete.go
│ │ ├── format.go
│ │ ├── main.go
│ │ ├── replace.go
│ │ ├── temp.txt
│ │ └── test.txt
├── functions
│ ├── anonymous_functions.go
│ └── func.go
├── generics
│ ├── approximate.go
│ ├── constraints.go
│ ├── main.go
│ ├── map.go
│ ├── slice.go
│ ├── sort.go
│ └── struct-stack.go
├── go-routines
│ ├── data
│ │ ├── f1.txt
│ │ └── f2.txt
│ ├── file-rw.go
│ ├── mail.go
│ ├── main.go
│ ├── mutex.go
│ ├── no-mutex.go
│ ├── no-rwmutex.go
│ ├── rwmutex.go
│ └── wg.go
├── hello-world
│ ├── go.mod
│ └── script.go
├── im-mutable
│ ├── immutable.go
│ └── mutable.go
├── input
│ ├── scan.go
│ ├── scanf.go
│ └── scanln.go
├── interfaces
│ ├── declare.go
│ ├── main.go
│ ├── slice.go
│ └── switch_interface.go
├── loops
│ ├── for.go
│ ├── infinite.go
│ └── while.go
├── maps
│ └── map.go
├── math
│ ├── basic-functions
│ │ ├── constants.go
│ │ ├── expo_log.go
│ │ ├── main.go
│ │ ├── trignometric.go
│ │ └── type_casting.go
│ ├── bit.go
│ ├── complex.go
│ └── rand.go
├── operators
│ ├── arithmetic
│ │ └── main.go
│ ├── assignment
│ │ └── main.go
│ ├── bitwise
│ │ └── main.go
│ ├── comparison
│ │ └── main.go
│ └── logical
│ │ └── main.go
├── packages
│ ├── blank_import.go
│ ├── import.go
│ └── mux_demo
│ │ ├── go.mod
│ │ ├── go.sum
│ │ └── main.go
├── paths
│ ├── main.go
│ ├── rel_abs.go
│ ├── script.go
│ ├── walk.go
│ └── walk_anonymous.go
├── pointers
│ └── pointer.go
├── random-num
│ ├── main.go
│ ├── rand_source.go
│ └── shuffle.go
├── regex
│ ├── main.go
│ ├── pincode.txt
│ ├── replace.go
│ ├── submatch.go
│ ├── subtext.txt
│ ├── temp.go
│ └── temp.txt
├── slices
│ └── slices.go
├── strings
│ ├── comparison.go
│ ├── concatenate.go
│ ├── go.mod
│ ├── go.sum
│ └── utility.go
├── structs
│ ├── constructor.go
│ ├── methods.go
│ └── struct.go
└── variables
│ ├── bool.go
│ ├── byte.go
│ ├── complex.go
│ ├── float.go
│ ├── int.go
│ ├── max_value_int.go
│ ├── multivar.go
│ ├── rune.go
│ ├── string.go
│ └── walrus.go
└── web
├── README.md
├── methods
├── delete
│ └── simple.go
├── get
│ ├── body.go
│ ├── chunk.go
│ ├── decoder.go
│ ├── header.go
│ ├── main.go
│ ├── newreq.go
│ └── unmarshal.go
├── patch
│ ├── json-patch
│ │ ├── add.go
│ │ ├── copy.go
│ │ ├── move.go
│ │ ├── remove.go
│ │ └── test.go
│ ├── json_merge_patch.go
│ ├── json_patch.go
│ ├── main.go
│ ├── marshal.go
│ └── put.go
├── post
│ ├── file.go
│ ├── file_2.go
│ ├── form-data.go
│ ├── json.go
│ ├── newreq.go
│ ├── post-req.go
│ ├── request-json.go
│ ├── request-obj
│ │ ├── encode.go
│ │ └── marshal.go
│ ├── sample.csv
│ └── simple.go
└── put
│ ├── create.go
│ ├── json.go
│ ├── main.go
│ └── update.go
└── url-parsing
├── db.go
├── fragments.go
├── main.go
├── manual_parsing.go
├── path.go
├── query_params.go
└── str.go
/README.md:
--------------------------------------------------------------------------------
1 | ## 100 Days of Go lang
2 |
3 | Go lang is a programming language which is easier to write and even provides type and memory safety, garbage collection and structural typing. It is developed by the Google Team in 2009 and open sourced in 2012. It is a programming language made for Cloud native technologies and web applications. It is a general purpose programming lanugage and hence there are no restrictions on the type of programs you wish to make in it.
4 |
5 | - [Official Website](https://go.dev)
6 | - [GitHub repository](https://github.com/golang/go)
7 | - [Standaard Library](https://pkg.go.dev/std)
8 | - [Go packages](https://pkg.go.dev/)
9 | - [Awesome Go projects and frmaeworks](https://github.com/avelino/awesome-go)
10 |
11 | ## Resources to learn Golang
12 |
13 | - [Exercism - Go track](https://exercism.org/tracks/go)
14 | - [Go by example](https://gobyexample.com/)
15 | - [Go Time - Podcast](https://changelog.com/gotime)
16 | - [Boot.dev Golang Course](https://boot.dev/learn/learn-golang)
17 | - [Zetcode Blog](https://zetcode.com/all/#go)
18 | - [daily.dev Golang articles](https://app.daily.dev/search?q=golang)
19 |
20 | Some famous applications made with GO!
21 |
22 | |Web apps | DevOps tools | CLI tools |
23 | |---------|--------------|-----------|
24 | |[SoundCloud](https://developers.soundcloud.com/blog/go-at-soundcloud) - Music System|[Prometheus](https://github.com/prometheus/prometheus) - Monitoring system and time series database|[gh-cli](https://github.com/cli/cli) - Official Github CLI
25 | |[Uber](https://www.slideshare.net/RobSkillington/go-at-uber) - Ride Sharing/Cab booking Webapp|[Grafana](https://github.com/grafana/grafana) - Platform for monitoring and observability|[cockroach-db](https://github.com/cockroachdb/cockroach) - Cockroach DB CLI
26 | |[Allergo](https://github.com/allegro/marathon-consul/#marathon-consul) - E-Commerce Webaapp|[Terraform](https://github.com/hashicorp/terraform) - Building, Changing, and Versioning Infrastructure|[gtree](https://github.com/ddddddO/gtree) - File tree CLI
27 | ||[Minikube](https://github.com/kubernetes/minikube) - Run kubernetes locally| [jenkinscli](https://github.com/jenkins-zh/jenkins-cli) - Managing Jenkins from CLI
28 | ||[Kit](https://github.com/go-kit/kit) - standard library for microservices
29 |
30 | ---
31 |
32 | ## 100 Days of Golang Blog challenge
33 |
34 | | Day | Topic | Blog Link | Code Examples | Documentation Link |
35 | |-----|-------|-----------|---------------|--------------------|
36 | | 0 | Overview of Golang | [What and Why? Golang](https://www.meetgor.com/golang-intro/) | [README](https://github.com/Mr-Destructive/100-days-of-golang#readme) | [docs](https://go.dev/ref/spec) |
37 | | 1 | Setup and Installation | [Installation and Hello World: GO](https://www.meetgor.com/hello-golang/) | [hello](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/hello-world) | [installation docs](https://go.dev/learn/) |
38 | | 2 | Varaibles and Data Types | [Data Types in Golang](https://www.meetgor.com/golang-variables/) | [varaibles](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/variables) | [Varaibles](https://go.dev/ref/spec#Variables) and [Types](https://go.dev/ref/spec#Types) |
39 | | 3 | Conditionals and Loops | [Conditionals and Loops in Golang](https://www.meetgor.com/golang-conditionals-loops/) | [conditionals](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/conditionals) / [loops](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/loops) | [if else](https://go.dev/ref/spec#If_statements) |
40 | | 4 | Input | [Input in Golang](https://www.meetgor.com/golang-input/) | [input](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/input) | [Scan](https://pkg.go.dev/fmt@go1.19.1#Scan) |
41 | | 5 | Arrays | [Arrays in Golang](https://www.meetgor.com/golang-arrays/) | [arrays](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/arrays) | [Arrays](https://go.dev/ref/spec#Array_types) |
42 | | 6 | Slices | [Slices in Golang](https://www.meetgor.com/golang-slices/) | [slices](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/slices) | [Slices](https://go.dev/ref/spec#Slice_types) |
43 | | 7 | Maps | [Maps in Golang](https://www.meetgor.com/golang-maps/) | [maps](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/maps) | [Maps](https://go.dev/ref/spec#Map_types) |
44 | | 8 | Functions | [Functions in Golang](https://www.meetgor.com/golang-functions/) | [functions](https://github.com/Mr-Destructive/100-days-of-golang/blob/main/scripts/functions/func.go) | [Functions](https://go.dev/ref/spec#Function_types) |
45 | | 9 | Structs | [Structs in Golang](https://www.meetgor.com/golang-structs/) | [structs](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/structs) | [Structs](https://go.dev/ref/spec#Struct_types) |
46 | | 10 | Pointers | [Pointers in Golang](https://www.meetgor.com/golang-pointers/) | [pointers](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/pointers) | [Pointers](https://go.dev/ref/spec#Pointer_types) |
47 | | 11 | Packages | [Pacakges in Golang](https://www.meetgor.com/golang-packages/) | [packages](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/packages) | [Packages](https://go.dev/ref/spec#Packages) |
48 | | 12 | Math | [Math package in Golang](https://www.meetgor.com/golang-math/) | [math](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/math) | [Math package](https://pkg.go.dev/math@go1.19.1) |
49 | | 13 | Operators | [Operators in Golang](https://www.meetgor.com/golang-operators/) | [operators](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/operators) | [operators](https://go.dev/ref/spec#Operators) |
50 | | 14 | Mutables and Immutables | [Mutable and Immutable Data types in Golang](https://www.meetgor.com/golang-mutable-immutable/) | [im-mutables](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/im-mutable) | [Mutables and Immutables](https://go.dev/ref/spec#Types) |
51 | | 15 | String Manipulation | [Strings in Golang](https://www.meetgor.com/golang-strings/) | [strings](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/strings) | [strings package](https://pkg.go.dev/strings@go1.19.1) |
52 | | 16 | Defer | [Defer in Golang](https://www.meetgor.com/golang-defer/) | [defer](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/defer) | [defer keyword](https://go.dev/ref/spec#Defer_statements) |
53 | | 17 | Anonymous Functions | [Anonymous Functions in Golang](https://www.meetgor.com/golang-anonymous-functions/) | [anonymous_functions](https://github.com/Mr-Destructive/100-days-of-golang/blob/main/scripts/functions/anonymous_functions.go) | [anonymous function](https://go.dev/ref/spec#:~:text=27.50%2C%20%22B0%22%3A%2030.87%2C%0A%7D-,Function%20literals,-A%20function%20literal) |
54 | | 18 | Closures | [Closures in Golang](https://www.meetgor.com/golang-closures/) | [closures](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/closures) | [closures](https://go.dev/ref/spec#:~:text=Function%20literals%20are%20closures%3A%20they%20may%20refer%20to%20variables%20defined%20in%20a%20surrounding%20function.%20Those%20variables%20are%20then%20shared%20between%20the%20surrounding%20function%20and%20the%20function%20literal%2C%20and%20they%20survive%20as%20long%20as%20they%20are%20accessible.) |
55 | | 19 | Interfaces | [Interfaces in Golang](https://www.meetgor.com/golang-interfaces/) | [interfaces](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/interfaces) | [interfaces](https://go.dev/ref/spec#Interface_types) |
56 | | 20 | Error Handling | [Error Handling in Golang](https://www.meetgor.com/golang-error-handling) | [errors](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/errors) | [Error - Effective Go](https://go.dev/doc/effective_go#errors) |
57 | | 21 | Paths | [Working with Paths in Golang](https://www.meetgor.com/golang-paths/) | [paths](https://github.com/mr-destructive/100-days-of-golang/tree/main/scripts/paths) | [path](https://pkg.go.dev/path), [io](https://pkg.go.dev/io), [os](https://pkg.go.dev/os) |
58 | | 22 | File Read | [File Read in Golang](https://www.meetgor.com/golang-file-read/) | [files-read](https://github.com/mr-destructive/100-days-of-golang/tree/main/scripts/files/read) | [os](https://pkg.go.dev/os#ReadFile), [bufio](https://pkg.go.dev/bufio) |
59 | | 23 | Config File Read (JSON, YAML, TOML, XML) | [Config File Reading in Golang](https://www.meetgor.com/golang-config-file-read/) | [config-files](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/files/read/config_files) | [yaml](https://pkg.go.dev/gopkg.in/yaml.v3), [toml](https://pkg.go.dev/gopkg.in/yaml.v3), [encoding](https://pkg.go.dev/encoding) |
60 | | 24 | File Write | [File Write in Golang](https://www.meetgor.com/golang-file-write/) | [files-write](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/files/write) | [os file write function](https://pkg.go.dev/os#WriteFile), [os write file types](https://pkg.go.dev/os#File.Write) |
61 | | 25 | Command Line Args | [CMD Args in Golang](https://www.meetgor.com/golang-command-line-args/) | [cmd-args](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/cmd-args) | [os Args](https://pkg.go.dev/os#pkg-variables), [flag](https://pkg.go.dev/flag) |
62 | | 26 | Regex | [Regex in Golang](https://www.meetgor.com/golang-regex/) | [regex](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/regex) | [regexp](https://pkg.go.dev/regexp) |
63 | | 27 | Random Numbers | [Random Numbers in Golang](https://www.meetgor.com/golang-random-numbers/) | [random-numbers](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/random-num) | [math/rand](https://pkg.go.dev/math/rand), [crypto/rand](https://pkg.go.dev/crypto/rand), [math/big](https://pkg.go.dev/math/big) |
64 | | 28 | Date and Time | [Date and Time in Golang](https://www.meetgor.com/golang-date-time/) | [date-time](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/date-time) | [time](https://pkg.go.dev/time/) |
65 | | 29 | Generics | [Generics in Golang](https://www.meetgor.com/golang-generics/) | [generics](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/generics) | [generics tutorial](https://go.dev/doc/tutorial/generics) |
66 | | 30 | Go Routines | [Go Routines](https://www.meetgor.com/golang-go-routines/) | [go-routines](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/go-routines) | [sync](https://pkg.go.dev/sync) |
67 | | 31 | Channels | [Go Channels](https://www.meetgor.com/golang-channels/) | [channels](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/scripts/channels) | [chan](https://pkg.go.dev/sync) |
68 | | 32 | Web: URL Parsing | [Web: URL Parsing](https://www.meetgor.com/golang-web-url-parsing/) | [web/url-parsing](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/web/url-parsing) | [net/url](https://pkg.go.dev/net/url) |
69 | | 33 | Web: GET Method | [Web: GET Method](https://www.meetgor.com/golang-web-get-method/) | [web/get-method](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/web/methods/get) | [net/http](https://pkg.go.dev/net/http), [encoding/json](https://pkg.go.dev/encoding/json) |
70 | | 34 | Web: POST Method | [Web: POST Method](https://www.meetgor.com/golang-web-post-method/) | [web/post-method](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/web/methods/post) | [net/http](https://pkg.go.dev/net/http), [encoding/json](https://pkg.go.dev/encoding/json) |
71 | | 35 | Web: PUT Method | [Web: PUT Method](https://www.meetgor.com/golang-web-put-method/) | [web/put-method](https://github.com/Mr-Destructive/100-days-of-golang/tree/main/web/methods/put) | [net/http](https://pkg.go.dev/net/http), [encoding/json](https://pkg.go.dev/encoding/json) |
72 |
--------------------------------------------------------------------------------
/scripts/arrays/arrays.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | // Simple Array declaration
7 | var languages [4]string
8 | languages[0] = "Python"
9 | fmt.Println(languages)
10 |
11 | // Using Array literal for declaration
12 | lang_array := [4]string{"Python", "Go", "Javascript", "C++"}
13 | fmt.Println(lang_array)
14 |
15 | // Accessing Array elements
16 | marks := [6]int{85, 89, 75, 93, 98, 60}
17 | fmt.Println(marks[1])
18 | fmt.Println(marks[5])
19 | fmt.Println(marks[3])
20 |
21 | // Modifying array elements
22 | name := [5]byte{'f', 'u', 'z', 'z', 'y'}
23 | fmt.Printf("%s\n", name)
24 | name[0] = 'b'
25 | name[4] = 'z'
26 | fmt.Printf("%s\n", name)
27 |
28 | // Letting Compiler figure out the length
29 | cart := [...]string{"Bag", "Shirt", "Watch", "Book"}
30 | fmt.Printf("There are %d items in your cart\n", len(cart))
31 |
32 | // Using len function to find length of array
33 | code := [7]rune{'#', '5', 'g', 't', 'm', 'y', '6'}
34 | fmt.Println("The length of the array is :", len(code))
35 |
36 | // Three statement for loop iteration of array
37 | for i := 0; i < len(code); i++ {
38 | fmt.Printf("%c\n", code[i])
39 | }
40 |
41 | // range based for loop to iterate over array
42 | for _, s := range cart {
43 | fmt.Println(s)
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/scripts/channels/bufchan.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | func main() {
9 | // Create a buffered channel with a capacity of 2
10 | buffchan := make(chan int, 2)
11 |
12 | // WaitGroup to wait for goroutines to finish
13 | wg := sync.WaitGroup{}
14 | wg.Add(2)
15 |
16 | // Start two goroutines
17 | for i := 1; i <= 2; i++ {
18 | go func(n int) {
19 | // Send values to the buffered channel
20 | buffchan <- n
21 | wg.Done()
22 | }(i)
23 | }
24 |
25 | // Wait for all goroutines to finish
26 | wg.Wait()
27 |
28 | // Close the buffered channel since we are done sending values
29 | close(buffchan)
30 |
31 | // Read values from the buffered channel
32 | for c := range buffchan {
33 | fmt.Println(c)
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/scripts/channels/close.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main() {
8 | ch := make(chan int)
9 |
10 | go func() {
11 | for i := 1; i <= 50; i++ {
12 | ch <- i
13 | }
14 | close(ch)
15 | }()
16 |
17 | for num := range ch {
18 | fmt.Println("Received:", num)
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/scripts/channels/data/f1.txt:
--------------------------------------------------------------------------------
1 | This is from file 1
2 |
--------------------------------------------------------------------------------
/scripts/channels/data/f2.txt:
--------------------------------------------------------------------------------
1 | This is from file 2
2 |
--------------------------------------------------------------------------------
/scripts/channels/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main() {
8 | ch := make(chan string)
9 | defer close(ch)
10 |
11 | go func() {
12 | ch <- "Hello, Gophers!"
13 | }()
14 |
15 | fmt.Println(<-ch)
16 | fmt.Println(<-ch)
17 | // uncommenting the above will result in a deadlock
18 | }
19 |
--------------------------------------------------------------------------------
/scripts/channels/patterns/async.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | )
7 |
8 | func fetchURL(url string, ch chan<- http.Response) {
9 | go func() {
10 | res, err := http.Get(url)
11 | if err != nil {
12 | panic(err)
13 | }
14 | defer res.Body.Close()
15 | ch <- *res
16 | }()
17 | }
18 |
19 | func task(name string) {
20 | fmt.Println("Task", name)
21 | }
22 |
23 | func main() {
24 | fmt.Println("Start")
25 |
26 | url := "http://google.com"
27 |
28 | respCh := make(chan http.Response)
29 |
30 | fetchURL(url, respCh)
31 |
32 | task("A")
33 | task("B")
34 |
35 | response := <-respCh
36 | fmt.Println("Response Status:", response.Status)
37 |
38 | fmt.Println("Done")
39 | }
40 |
--------------------------------------------------------------------------------
/scripts/channels/patterns/fan-in.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "sync"
7 | )
8 |
9 | func readFile(file string, ch chan<- string) {
10 | content, _ := os.ReadFile(file)
11 | fmt.Println("Reading from", file, "as :: ", string(content))
12 | ch <- string(content)
13 | close(ch)
14 | }
15 |
16 | func merge(chs ...<-chan string) string {
17 | var wg sync.WaitGroup
18 | out := ""
19 |
20 | for _, ch := range chs {
21 | wg.Add(1)
22 | go func(c <-chan string) {
23 | for s := range c {
24 | out += s
25 | }
26 | wg.Done()
27 | }(ch)
28 | }
29 |
30 | wg.Wait()
31 | return out
32 | }
33 |
34 | func main() {
35 |
36 | ch1 := make(chan string)
37 | ch2 := make(chan string)
38 |
39 | go readFile("data/f1.txt", ch1)
40 | go readFile("data/f2.txt", ch2)
41 |
42 | merged := merge(ch1, ch2)
43 |
44 | fmt.Println(merged)
45 | }
46 |
--------------------------------------------------------------------------------
/scripts/channels/patterns/fan-out.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "sync"
7 | )
8 |
9 | func readFile(file string, ch chan<- string, wg *sync.WaitGroup) {
10 | defer wg.Done()
11 |
12 | content, err := os.ReadFile(file)
13 | if err != nil {
14 | fmt.Printf("Error reading from %s: %v\n", file, err)
15 | return
16 | }
17 |
18 | ch <- string(content)
19 | }
20 |
21 | func main() {
22 | files := []string{"data/f1.txt", "data/f2.txt"}
23 |
24 | var wg sync.WaitGroup
25 | ch := make(chan string)
26 |
27 | for _, f := range files {
28 | wg.Add(1)
29 | go readFile(f, ch, &wg)
30 | }
31 |
32 | go func() {
33 | wg.Wait()
34 | close(ch)
35 | }()
36 |
37 | var fileData []string
38 | for content := range ch {
39 | fileData = append(fileData, content)
40 | }
41 |
42 | fmt.Printf("Read %d files\n", len(fileData))
43 | fmt.Printf("Contents:\n%s", fileData)
44 | }
45 |
--------------------------------------------------------------------------------
/scripts/channels/patterns/pipeline.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | func generate(nums []int, out chan<- int, wg *sync.WaitGroup) {
9 | fmt.Println("Stage 1")
10 | for _, n := range nums {
11 | fmt.Println("Number:", n)
12 | out <- n
13 | }
14 | close(out)
15 | wg.Done()
16 | }
17 |
18 | func square(in <-chan int, out chan<- int, wg *sync.WaitGroup) {
19 | fmt.Println("Stage 2")
20 | for n := range in {
21 | sq := n * n
22 | fmt.Println("Square:", sq)
23 | out <- sq
24 | }
25 | close(out)
26 | wg.Done()
27 | }
28 |
29 | func print(in <-chan int, wg *sync.WaitGroup) {
30 | for n := range in {
31 | fmt.Println(n)
32 | }
33 | wg.Done()
34 | }
35 |
36 | func main() {
37 | input := []int{1, 2, 3, 4, 5}
38 |
39 | var wg sync.WaitGroup
40 | wg.Add(3)
41 |
42 | stage1 := make(chan int)
43 | stage2 := make(chan int)
44 |
45 | go generate(input, stage1, &wg)
46 |
47 | go square(stage1, stage2, &wg)
48 |
49 | go print(stage2, &wg)
50 |
51 | wg.Wait()
52 | }
53 |
--------------------------------------------------------------------------------
/scripts/channels/patterns/throttle.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func main() {
9 | jobs := make(chan int, 5)
10 | go func() {
11 | for i := 0; i < 100; i++ {
12 | jobs <- i
13 | }
14 | close(jobs)
15 | }()
16 |
17 | throttle := time.Tick(500 * time.Millisecond)
18 |
19 | for job := range jobs {
20 | <-throttle // limits to 5 jobs/sec
21 | go func(job int) {
22 | fmt.Println("Job:", job)
23 | }(job)
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/scripts/channels/patterns/workers.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func worker(id int, jobs <-chan int) {
9 | for job := range jobs {
10 | fmt.Printf("Worker %d: Processing Job %d\n", id, job)
11 | time.Sleep(100 * time.Millisecond) // Simulating work
12 | }
13 | }
14 |
15 | func main() {
16 | const numWorkers = 5
17 | const numJobs = 100
18 |
19 | jobs := make(chan int, numWorkers)
20 | for i := 0; i < numWorkers; i++ {
21 | go worker(i, jobs)
22 | }
23 |
24 | for i := 0; i < numJobs; i++ {
25 | jobs <- i
26 | }
27 |
28 | close(jobs)
29 |
30 | time.Sleep(2 * time.Second)
31 | }
32 |
--------------------------------------------------------------------------------
/scripts/channels/select-chan.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | "sync"
7 | )
8 |
9 | func pingGoogle(c chan string, wg *sync.WaitGroup) {
10 | defer wg.Done()
11 | res, _ := http.Get("http://google.com")
12 | c <- res.Status
13 | }
14 |
15 | func pingDuckDuckGo(c chan string, wg *sync.WaitGroup) {
16 | defer wg.Done()
17 | res, _ := http.Get("https://duckduckgo.com")
18 | c <- res.Status
19 | }
20 |
21 | func pingBraveSearch(c chan string, wg *sync.WaitGroup) {
22 | defer wg.Done()
23 | res, _ := http.Get("https://search.brave.com")
24 | c <- res.Status
25 | }
26 |
27 | func main() {
28 | gogChan := make(chan string)
29 | ddgChan := make(chan string)
30 | braveChan := make(chan string)
31 |
32 | var wg sync.WaitGroup
33 | wg.Add(3)
34 |
35 | go pingDuckDuckGo(ddgChan, &wg)
36 | go pingGoogle(gogChan, &wg)
37 | go pingBraveSearch(braveChan, &wg)
38 |
39 | openChannels := 3
40 |
41 | go func() {
42 | wg.Wait()
43 | close(gogChan)
44 | close(ddgChan)
45 | close(braveChan)
46 | }()
47 |
48 | for openChannels > 0 {
49 | select {
50 | case msg1, ok := <-gogChan:
51 | if !ok {
52 | openChannels--
53 | } else {
54 | fmt.Println("Google responded:", msg1)
55 | }
56 | case msg2, ok := <-ddgChan:
57 | if !ok {
58 | openChannels--
59 | } else {
60 | fmt.Println("DuckDuckGo responded:", msg2)
61 | }
62 | case msg3, ok := <-braveChan:
63 | if !ok {
64 | openChannels--
65 | } else {
66 | fmt.Println("BraveSearch responded:", msg3)
67 | }
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/scripts/channels/send-recv.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | func receiver(ch <-chan int, wg *sync.WaitGroup) {
9 | for i := range ch {
10 | fmt.Println("Received:", i)
11 | }
12 | wg.Done()
13 | }
14 |
15 | func sender(ch chan<- int, wg *sync.WaitGroup) {
16 | for i := 0; i < 10; i++ {
17 | fmt.Println("Sent:", i)
18 | ch <- i
19 | }
20 | close(ch)
21 | wg.Done()
22 | }
23 |
24 | func main() {
25 | ch := make(chan int)
26 | wg := sync.WaitGroup{}
27 | wg.Add(2)
28 | go receiver(ch, &wg)
29 | go sender(ch, &wg)
30 | wg.Wait()
31 | }
32 |
--------------------------------------------------------------------------------
/scripts/channels/simple.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | func sendMessage(ch chan string, message string, wg *sync.WaitGroup) {
9 | defer wg.Done()
10 | ch <- message
11 | }
12 |
13 | func main() {
14 | var wg sync.WaitGroup
15 |
16 | ch1 := make(chan string, 2)
17 | ch2 := make(chan string, 2)
18 | wg.Add(2)
19 |
20 | go sendMessage(ch1, "Hello, Gophers!", &wg)
21 | go sendMessage(ch2, "Hello, Hamsters!", &wg)
22 |
23 | go func() {
24 | defer wg.Done()
25 | wg.Wait()
26 | close(ch1)
27 | close(ch2)
28 | }()
29 | ch1 <- "new message to c1"
30 | ch2 <- "new message to c2"
31 |
32 | select {
33 | case <-ch1:
34 | fmt.Println("Received from ch1")
35 | case ch1 <- "new message to c1":
36 | fmt.Println("Sent to ch1")
37 | case <-ch2:
38 | fmt.Println("Received from ch2")
39 | case ch2 <- "new message to c2":
40 | fmt.Println("Sent to ch2")
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/scripts/closures/go.mod:
--------------------------------------------------------------------------------
1 | module closures
2 |
3 | go 1.18
4 |
--------------------------------------------------------------------------------
/scripts/closures/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func gophy() func() string{
6 | return func() string{
7 | return "Hello, Gophers!"
8 | }
9 | }
10 |
11 | func inrementer() func() int{
12 | counter := 0
13 | return func() int{
14 | counter += 1
15 | return counter
16 | }
17 | }
18 |
19 | func factorial() func() int{
20 | fact, n := 1, 1
21 | return func() int{
22 | fact = fact * n
23 | n += 1
24 | return fact
25 | }
26 | }
27 |
28 | func main() {
29 | // s := "Hello, Gophers!"
30 | // long form of declaring s
31 | // using clousure/anonymous function to return a value
32 | // that value can be assigned to the variable
33 | s := func() string {
34 | return "Hello, World!"
35 | }()
36 | fmt.Println(s)
37 | g := gophy()
38 | fmt.Println(g())
39 |
40 | c := inrementer()
41 | fmt.Println(c())
42 | fmt.Println(c())
43 | fmt.Println(c())
44 |
45 | c1 := inrementer()
46 | fmt.Println(c1())
47 | fmt.Println(c1())
48 | fmt.Println(c1())
49 |
50 |
51 | f1 := factorial()
52 | fmt.Println(f1())
53 | fmt.Println(f1())
54 | fmt.Println(f1())
55 | }
56 |
--------------------------------------------------------------------------------
/scripts/cmd-args/flag.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 | )
7 |
8 | func main() {
9 | var port int
10 | var dir string
11 | var publish bool
12 | var help bool
13 | flag.IntVar(&port, "p", 8000, "Provide a port number")
14 | flag.StringVar(&dir, "dir", "output_dir", "Directory")
15 | flag.BoolVar(&publish, "publish", false, "Publish the article")
16 | flag.BoolVar(&help, "help", false, "Help")
17 | flag.Parse()
18 | if help {
19 | flag.PrintDefaults()
20 | } else {
21 | fmt.Println(port)
22 | fmt.Println(dir)
23 | flag.Set("dir", "dumps")
24 | fmt.Println(dir)
25 | fmt.Println(flag.NFlag())
26 | fmt.Println(flag.NArg())
27 | fmt.Println(publish)
28 | if publish {
29 | fmt.Println("Publishing article...")
30 | } else {
31 | fmt.Println("Article saved as Draft!")
32 | }
33 | vals := flag.Args()
34 | fmt.Println(vals)
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/scripts/cmd-args/flag_ref.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 | )
7 |
8 | func main() {
9 | port := flag.Int("p", 8000, "Provide a port number")
10 | dir := flag.String("dir", "output_dir", "Directory")
11 | publish := flag.Bool("publish", false, "Publish the article")
12 | help := flag.Bool("help", false, "Help")
13 | if *help {
14 | flag.PrintDefaults()
15 | } else {
16 | fmt.Println(*port)
17 | fmt.Println(*dir)
18 | flag.Set("dir", "dumps")
19 | fmt.Println(*dir)
20 | fmt.Println(flag.NFlag())
21 | fmt.Println(flag.NArg())
22 | fmt.Println(*publish)
23 | if *publish {
24 | fmt.Println("Publishing article...")
25 | } else {
26 | fmt.Println("Article saved as Draft!")
27 | }
28 | vals := flag.Args()
29 | fmt.Println(vals)
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/scripts/cmd-args/help.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 | )
7 |
8 | func main() {
9 | var port int
10 | var help bool
11 | flag.IntVar(&port, "p", 8000, "Provide a port number")
12 | flag.BoolVar(&help, "help", false, "Help")
13 | flag.Parse()
14 | if help {
15 | flag.PrintDefaults()
16 | } else {
17 | fmt.Println(port)
18 | vals := flag.Args()
19 | fmt.Println(vals)
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/scripts/cmd-args/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "strconv"
7 | )
8 |
9 | func main() {
10 | args := os.Args
11 | fmt.Printf("Type of Args = %T\n", args)
12 | //fmt.Println(args[0], args[1])
13 |
14 | //total_args := len(os.Args[1:])
15 | //fmt.Println(total_args)
16 |
17 | for n, args := range os.Args {
18 | fmt.Println("Arg:", n, "->", args)
19 | }
20 | /*
21 | // for excluding the 0th argument
22 | for n, args := range os.Args[1:] {
23 | fmt.Println("Arg:", n, "->", args)
24 | }
25 | */
26 | var port int
27 | var err error
28 | if len(os.Args) > 1 {
29 | port, err = strconv.Atoi(args[1])
30 | if err != nil {
31 | panic(err)
32 | }
33 | } else {
34 | port = 8000
35 | }
36 | fmt.Println(port)
37 | }
38 |
--------------------------------------------------------------------------------
/scripts/conditionals/if_else.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 |
7 | // basic if-else
8 | age := 16
9 | if age < 13 {
10 | fmt.Println("Kid")
11 | } else {
12 | fmt.Println("Teenager")
13 | }
14 |
15 | // else-if
16 | year := 2
17 | if year < 1 {
18 | fmt.Println("Freshman")
19 | } else if year == 2 {
20 | fmt.Println("Sophomore")
21 | } else if year == 3 {
22 | fmt.Println("Junior")
23 | } else if year == 4 {
24 | fmt.Println("Senior")
25 | } else {
26 | fmt.Println("Probably a Graduate")
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/scripts/conditionals/switch.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 |
7 | //basic switch statement
8 | age := 11
9 | var result string
10 | switch {
11 | case age < 13:
12 | result = "Kid"
13 | case age < 20:
14 | result = "Teenager"
15 | case age < 25:
16 | result = "Adult"
17 | case age < 35:
18 | result = "Senior"
19 | }
20 | fmt.Printf("The person is a %s with age %d.\n", result, age)
21 |
22 | //default case
23 | language := "go"
24 | var devs string
25 | switch language {
26 | case "go":
27 | devs = "gopher"
28 | case "rust":
29 | devs = "rustacean"
30 | case "python":
31 | devs = "pythonista"
32 | case "java":
33 | devs = "Duke"
34 | default:
35 | language = "javascript"
36 | devs = "developer"
37 | }
38 | fmt.Println("A person who codes in", language, "is called a", devs)
39 |
40 | // fallthrough
41 |
42 | character := 'a'
43 | fmt.Printf("The input character is = %c\n", character)
44 | switch {
45 | case character == 97:
46 | fmt.Printf("Its %c\n", character)
47 | fallthrough
48 | case character < 107 && character > 97:
49 | fmt.Println("It's between a and k")
50 | fallthrough
51 | case character < 117 && character > 97:
52 | fmt.Println("It's between a and t")
53 | fallthrough
54 | case character < 122 && character > 97:
55 | fmt.Println("It's between a and u")
56 | default:
57 | fmt.Println("Its not a lowercase alphabet")
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/scripts/date-time/arithmetic.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func main() {
9 | t := time.Now()
10 | fmt.Println(t)
11 |
12 | afterOneHour := t.Add(time.Hour * 1)
13 | fmt.Println(afterOneHour)
14 |
15 | afterOneDayTwoHours30minutes := t.AddDate(0, 0, 1).Add(time.Hour * 3).Add(time.Minute * 30)
16 | fmt.Println(afterOneDayTwoHours30minutes)
17 |
18 | afterThreeMonths15days := t.AddDate(0, 3, 15)
19 | fmt.Println(afterThreeMonths15days)
20 |
21 | beforeOneHour := t.Add(time.Hour * -1)
22 | fmt.Println(beforeOneHour)
23 |
24 | beforeOneYearTwoMonths := t.AddDate(-1, -2, 0)
25 | fmt.Println(beforeOneYearTwoMonths)
26 |
27 | isNowAfter := t.After(afterOneHour)
28 | isOneAfter := afterOneHour.After(t)
29 | fmt.Println(isNowAfter)
30 | fmt.Println(isOneAfter)
31 |
32 | isNowBefore := t.Before(afterOneHour)
33 | isOneBefore := afterOneHour.Before(t)
34 | fmt.Println(isNowBefore)
35 | fmt.Println(isOneBefore)
36 |
37 | isNowEqual := t.Equal(afterOneHour)
38 | isEqual := time.Now().Equal(t)
39 | fmt.Println(isNowEqual)
40 | fmt.Println(isEqual)
41 |
42 | londonTimeZone, err := time.LoadLocation("Europe/London")
43 | if err != nil {
44 | fmt.Println(err)
45 | }
46 | londonTime := t.In(londonTimeZone)
47 |
48 | fmt.Println(t)
49 | fmt.Println(londonTime)
50 | fmt.Println(t.Equal(londonTime))
51 | }
52 |
--------------------------------------------------------------------------------
/scripts/date-time/duration.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func main() {
9 | screentime, err := time.ParseDuration("6h30m")
10 | if err != nil {
11 | fmt.Println(err)
12 | return
13 | }
14 | fmt.Printf("%T\n", screentime)
15 | fmt.Println(screentime.Hours())
16 | fmt.Println(screentime.Minutes())
17 |
18 | newYear := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
19 | fmt.Println(time.Now().UTC())
20 | fmt.Println(time.Since(newYear).Hours())
21 |
22 | nextNewYear := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
23 | fmt.Println(nextNewYear.Sub(newYear).Hours())
24 | fmt.Println(nextNewYear.Sub(newYear).String())
25 |
26 | day := time.Hour * 24
27 | fmt.Println(day)
28 | week := time.Hour * 24 * 7
29 | fmt.Println(week)
30 | month := time.Hour * 30 * 24 * 7
31 | fmt.Println(month)
32 |
33 | fifteenDays := day * 15
34 | fmt.Println(fifteenDays)
35 | }
36 |
--------------------------------------------------------------------------------
/scripts/date-time/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func main() {
9 | now := time.Now()
10 | fmt.Printf("%T\n", now)
11 | fmt.Println(now)
12 |
13 | fmt.Println(now.UTC())
14 |
15 | somedate := time.Date(2020, 03, 25, 8, 5, 0, 0, time.FixedZone("UTC", 5))
16 | fmt.Println(somedate)
17 |
18 | today := somedate.Day()
19 | fmt.Println(today)
20 |
21 | year := somedate.Year()
22 | fmt.Println(year)
23 |
24 | month := somedate.Month()
25 | fmt.Println(month)
26 |
27 | date := somedate.Day()
28 | fmt.Println(date)
29 |
30 | weekday := somedate.Weekday()
31 | fmt.Println(weekday)
32 |
33 | yearDay := somedate.YearDay()
34 | fmt.Println(yearDay)
35 |
36 |
37 | year, month, date = now.Date()
38 |
39 | fmt.Println(year, month, date)
40 |
41 | fmt.Println(now.Format("Monday 01 January 2006 15:04:05"))
42 |
43 | // day month date hour:minutes:second timezone year
44 | fmt.Println(now.Format(time.UnixDate))
45 |
46 | // day month date hour:minutes:second year
47 | fmt.Println(now.Format(time.ANSIC))
48 |
49 | // day month date hour:minutes:second
50 | fmt.Println(now.Format(time.Stamp))
51 |
52 | // day month date hour:minutes:second.milisecond
53 | fmt.Println(now.Format(time.StampMilli))
54 |
55 | // day month date hour:minutes:second.microsecond
56 | fmt.Println(now.Format(time.StampMicro))
57 |
58 | // day month date hour:minutes:second.nanosecond
59 | fmt.Println(now.Format(time.StampNano))
60 |
61 | // day, date month year hour:minutes:second timezone
62 | fmt.Println(now.Format(time.RFC1123))
63 |
64 | // day, date month year hour:minutes:second offset
65 | fmt.Println(now.Format(time.RFC1123Z))
66 |
67 | // year-month-dayThour:minutes:second+-offset
68 | fmt.Println(now.Format(time.RFC3339))
69 |
70 | // year-month-dayThour:minutes.nanosecond:second
71 | fmt.Println(now.Format(time.RFC3339Nano))
72 |
73 | // date month year hour:minutes timezone
74 | fmt.Println(now.Format(time.RFC822))
75 |
76 | // hour:minuteAM/PM
77 | fmt.Println(now.Format(time.Kitchen))
78 | customDate := "2023-0426"
79 | t, err := time.Parse("2006-01-02", customDate)
80 | if err != nil {
81 | fmt.Println(err)
82 | }
83 | fmt.Println(t)
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/scripts/date-time/sleep.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func main() {
9 | t1 := time.Now()
10 | time.Sleep(time.Second * 3)
11 | t2 := time.Now()
12 | duration := t2.Sub(t1)
13 | fmt.Println(duration)
14 |
15 | ticker := time.NewTicker(time.Second * 2)
16 | counter := 0
17 | for {
18 | select {
19 | case <-ticker.C:
20 | // api calls, call to database after specific time intervals
21 | counter++
22 | fmt.Println("Tick", counter)
23 | }
24 | if counter == 5 {
25 | ticker.Stop()
26 | return
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/scripts/date-time/timezone.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func main() {
9 | t := time.Now()
10 | fmt.Println(t)
11 | fmt.Println(t.Location())
12 |
13 | newYorkTimeZone, err := time.LoadLocation("America/New_York")
14 | if err != nil {
15 | fmt.Println(err)
16 | }
17 | londonTimeZone, err := time.LoadLocation("Europe/London")
18 | if err != nil {
19 | fmt.Println(err)
20 | }
21 | newYorkTime := t.In(newYorkTimeZone)
22 | londonTime := t.In(londonTimeZone)
23 |
24 | //local time
25 | fmt.Println(t)
26 |
27 | // london time
28 | fmt.Println(londonTimeZone)
29 | fmt.Println(londonTime)
30 |
31 | // new york time
32 | fmt.Println(newYorkTimeZone)
33 | fmt.Println(newYorkTime)
34 |
35 | offset := int((4*time.Hour + 30*time.Minute + 30*time.Second).Seconds())
36 | // (4*60 + 30*1 + 30*0.166) * 60
37 | // (270 + 0.5) * 60 = 16230
38 | fmt.Println(offset)
39 | fmt.Println(t.UTC())
40 | customTimeZone := time.FixedZone("SOMETZ", offset)
41 | fmt.Println(customTimeZone)
42 | fmt.Println(t.In(customTimeZone))
43 | }
44 |
--------------------------------------------------------------------------------
/scripts/defer/defer.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func square(x int) int {
6 | fmt.Println(x * x)
7 | return x * x
8 | }
9 |
10 | func main() {
11 |
12 | // simple defer example
13 | fmt.Println("First")
14 | defer fmt.Println("Second Ahhh..")
15 | fmt.Println("Third")
16 |
17 | // multiple defer statements
18 | fmt.Println("bag")
19 | defer fmt.Println("book")
20 | defer fmt.Println("cap")
21 | fmt.Println("laptop")
22 | defer fmt.Println("wallet")
23 | fmt.Println("headphones")
24 |
25 | // defer keyword in function
26 | defer square(12)
27 | defer square(10)
28 | square(15)
29 | }
30 |
--------------------------------------------------------------------------------
/scripts/errors/custom.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | "net/url"
7 | )
8 |
9 | type Invalid_URL_Error struct {
10 | m string
11 | }
12 |
13 | func (e Invalid_URL_Error) Error() string {
14 | return "Invalid URL : " + e.m
15 | }
16 |
17 | func get_resp(url_link string) (http.Response, error) {
18 | _, err := url.ParseRequestURI(url_link)
19 | if err != nil {
20 | return http.Response{}, &Invalid_URL_Error{err.Error()}
21 | }
22 | resp, err := http.Get(url_link)
23 | if err != nil {
24 | return http.Response{}, &Invalid_URL_Error{err.Error()}
25 | } else {
26 | defer resp.Body.Close()
27 | return *resp, nil
28 | }
29 |
30 | }
31 |
32 | func main() {
33 | url := "https://.com"
34 | resp, err := get_resp(url)
35 | if err != nil {
36 | fmt.Println(err)
37 | } else {
38 | fmt.Println(resp)
39 | }
40 | url = "htt://meetgor.com"
41 | response, er := http.Get(url)
42 | if err != nil {
43 | fmt.Println(Invalid_URL_Error{er.Error()})
44 | } else {
45 | fmt.Println(response)
46 | defer response.Body.Close()
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/scripts/errors/custom_error.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | )
7 |
8 | type Invalid_URL_Error struct {
9 | message string
10 | }
11 |
12 | func (e Invalid_URL_Error) Error() string {
13 | return "Invalid URL : " + e.message
14 | }
15 |
16 | func get_resp(url_link string) (http.Response, error) {
17 |
18 | resp, err := http.Get(url_link)
19 |
20 | if err != nil {
21 | return http.Response{}, &Invalid_URL_Error{err.Error()}
22 | } else {
23 | defer resp.Body.Close()
24 | return *resp, nil
25 | }
26 |
27 | }
28 |
29 | func main() {
30 |
31 | url := "htts://meetgor.com"
32 | resp, err := get_resp(url)
33 | if err != nil {
34 | fmt.Println(err)
35 | } else {
36 | fmt.Println(resp)
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/scripts/errors/errors.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | )
7 |
8 | type Invalid_URL_Error struct {
9 | message string
10 | }
11 |
12 | func (e Invalid_URL_Error) Error() string {
13 | return "Invalid URL"
14 | }
15 |
16 | func get_resp(url_link string) (http.Response, error) {
17 |
18 | resp, err := http.Get(url_link)
19 |
20 | if err != nil {
21 | return http.Response{}, &Invalid_URL_Error{}
22 | } else {
23 | defer resp.Body.Close()
24 | return *resp, nil
25 | }
26 |
27 | }
28 |
29 | func main() {
30 |
31 | url := "https://meetgor.com"
32 | resp, err := get_resp(url)
33 | if err != nil {
34 | fmt.Println(err)
35 | } else {
36 | fmt.Println(resp)
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/scripts/errors/file-read.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | )
7 |
8 | func main() {
9 | file_name := "hello.txt"
10 | file, err := os.Open(file_name)
11 | if err != nil {
12 | fmt.Println("Error: ", err)
13 | //_, err := os.Create(file_name)
14 | //if err != nil {
15 | // fmt.Println(err)
16 | //}
17 | //fmt.Println("Created File", file_name)
18 | //file, _ = os.Open(file_name)
19 | }
20 | fmt.Println(file.Stat())
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/scripts/errors/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main() {
8 | var s string
9 | n, err := fmt.Scanf("%s", &s)
10 | if err != nil {
11 | fmt.Println(err)
12 | //panic(err)
13 | } else {
14 | fmt.Println(n)
15 | if s[0] == 'a' {
16 | fmt.Println(s)
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/scripts/errors/web.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | )
7 |
8 | func main() {
9 | url := "htts://meetgor.com/"
10 | resp, err := http.Get(url)
11 | fmt.Println("URL:", url)
12 | if err != nil {
13 | fmt.Println(err)
14 | panic(err)
15 | } else {
16 | fmt.Println(resp.StatusCode)
17 | }
18 | }
19 |
20 | /*
21 | if resp, err := http.Get(url); err != nil {
22 | fmt.Println(err)
23 | panic(err)
24 | } else {
25 | fmt.Println(resp.StatusCode)
26 | }
27 | */
28 |
--------------------------------------------------------------------------------
/scripts/files/read/char.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bufio"
5 | "log"
6 | "os"
7 | )
8 |
9 | func main() {
10 | f, err := os.Open("sample.txt")
11 | if err != nil {
12 | log.Fatal(err)
13 | }
14 | defer f.Close()
15 |
16 | scanner := bufio.NewScanner(f)
17 | scanner.Split(bufio.ScanRunes)
18 |
19 | if err := scanner.Err(); err != nil {
20 | log.Fatal(err)
21 | }
22 |
23 | charlist := []byte{}
24 | for scanner.Scan() {
25 | char := byte(scanner.Text()[0])
26 | charlist = append(charlist, char)
27 | }
28 | log.Println(charlist)
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/scripts/files/read/chunks.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bufio"
5 | "io"
6 | "log"
7 | "os"
8 | )
9 |
10 | func main() {
11 |
12 | f, err := os.Open("sample.txt")
13 |
14 | if err != nil {
15 | log.Fatal(err)
16 | }
17 |
18 | defer f.Close()
19 |
20 | reader := bufio.NewReader(f)
21 | chunk_size := 16
22 | chunk_list := []string{}
23 | buf := make([]byte, chunk_size)
24 |
25 | for {
26 | n, err := reader.Read(buf)
27 |
28 | if err != nil {
29 | if err != io.EOF {
30 | log.Fatal(err)
31 | }
32 | break
33 | }
34 | chunk_list = append(chunk_list, string(buf[0:n]))
35 | }
36 | for _, chunk := range chunk_list {
37 | log.Print(chunk)
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/csv/blog.csv:
--------------------------------------------------------------------------------
1 | id,name,posts,exp
2 | 21,jim,23,2
3 | 33,kevin,39,1
4 | 45,james,70,2
5 | 56,chris,89,3
6 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/csv/csv.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/csv"
5 | "log"
6 | "net/http"
7 | )
8 |
9 | func main() {
10 |
11 | url := "https://github.com/woocommerce/woocommerce/raw/master/sample-data/sample_products.csv"
12 | response, err := http.Get(url)
13 |
14 | if err != nil {
15 | log.Println(err)
16 | return
17 | }
18 |
19 | defer response.Body.Close()
20 | reader := csv.NewReader(response.Body)
21 | n, err := reader.ReadAll()
22 | if err != nil {
23 | log.Println(err)
24 | return
25 | }
26 | for _, line := range n {
27 | for _, text := range line {
28 | log.Println(text)
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/csv/go.mod:
--------------------------------------------------------------------------------
1 | module csv-read
2 |
3 | go 1.18
4 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/csv/temp.csv:
--------------------------------------------------------------------------------
1 | period,status,natural_increase,net_migration,population_change,percent_population_change,population
2 | 2008-06-30,F,8500,-3200,4200,0.1,4259800
3 | 2008-09-30,F,8100,2900,9800,0.23,4269600
4 | 2008-12-31,F,9200,2700,10700,0.25,4280300
5 | 2009-03-31,F,9300,5100,13200,0.31,4293500
6 | 2009-06-30,F,8400,1900,9100,0.21,4302600
7 | 2009-09-30,F,8500,7400,14700,0.34,4317300
8 | 2009-12-31,F,9100,6900,14800,0.34,4332100
9 | 2010-03-31,F,9900,4800,13500,0.31,4345700
10 | 2010-06-30,F,8700,-2600 ,5000,0.11,4350700
11 | 2010-09-30,F,8400,4800,12000,0.28,4362700
12 | 2010-12-31,F,8900,3400,11200,0.26,4373900
13 | 2011-03-31,F,8800,900,8600,0.2,4382500
14 | 2011-06-30,F,7900,-5300,1500,0.03,4384000
15 | 2011-09-30,F,7500,1700,8100,0.18,4392000
16 | 2011-12-31,F,7800,800,7400,0.17,4399400
17 | 2012-03-31,F,8800,-600,7000,0.16,4406500
18 | 2012-06-30,F,7800,-5100,1600,0.04,4408100
19 | 2012-09-30,F,7100,1600,7600,0.17,4415600
20 | 2012-12-31,F,8500,2900,10200,0.23,4425900
21 | 2013-03-31,F,8200,3100,10100,0.23,4436000
22 | 2013-06-30,F,7000,300,6100,0.14,4442100
23 | 2013-09-30,F,6700,8900,15600,0.35,4457700
24 | 2013-12-31,F,7900,10200,18100,0.41,4475800
25 | 2014-03-31,F,7600,12500,20200,0.45,4496000
26 | 2014-06-30,F,7100,6700,13800,0.31,4509700
27 | 2014-09-30,F,5900,16000,21800,0.48,4531600
28 | 2014-12-31,F,7300,15700,23000,0.51,4554600
29 | 2015-03-31,F,7600,17900,25500,0.56,4580000
30 | 2015-06-30,F,7000,8700,15700,0.34,4595700
31 | 2015-09-30,F,5900,18900,24900,0.54,4620600
32 | 2015-12-31,F,7300,19400,26700,0.58,4647300
33 | 2016-03-31,F,8000,20600,28500,0.61,4675900
34 | 2016-06-30,F,7200,10200,17400,0.37,4693200
35 | 2016-09-30,F,6800,19800,26600,0.57,4719800
36 | 2016-12-31,F,7400,20000,27400,0.58,4747200
37 | 2017-03-31,F,7400,21900,29400,0.62,4776500
38 | 2017-06-30,F,6800,10500,17300,0.36,4793900
39 | 2017-09-30,F,5500,18500,24000,0.5,4817800
40 | 2017-12-31,F,7500,19100,26600,0.55,4844400
41 | 2018-03-31,F,7300,19900,27200,0.56,4871600
42 | 2018-06-30,P,6200,7500,13700,0.28,4885300
43 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/go.mod:
--------------------------------------------------------------------------------
1 | module file-read
2 |
3 | go 1.18
4 |
5 | require (
6 | github.com/pelletier/go-toml v1.9.5 // indirect
7 | gopkg.in/yaml.v3 v3.0.1 // indirect
8 | )
9 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/go.sum:
--------------------------------------------------------------------------------
1 | github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=
2 | github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
3 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
4 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
5 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
6 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/json/blog.json:
--------------------------------------------------------------------------------
1 | {
2 | "title": "Golang Blog Series",
3 | "date": "22nd October 2022",
4 | "tags": ["go", "files"],
5 | "words": 1500,
6 | "published": true
7 | }
8 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/json/go.mod:
--------------------------------------------------------------------------------
1 | module json_read
2 |
3 | go 1.18
4 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/json/json.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "log"
7 | "os"
8 | )
9 |
10 | func main() {
11 |
12 | f, err := os.ReadFile("blog.json")
13 | if err != nil {
14 | log.Println(err)
15 | }
16 | var result map[string]interface{}
17 | json.Unmarshal([]byte(f), &result)
18 |
19 | log.Println(result)
20 | for k, v := range result {
21 | fmt.Println(k, ":", v)
22 | fmt.Printf("%T\n", v)
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/csv"
5 | "encoding/json"
6 | toml "github.com/pelletier/go-toml"
7 | yaml "gopkg.in/yaml.v3"
8 | "log"
9 | "os"
10 | )
11 |
12 | func check_error(err error) {
13 | if err != nil {
14 | log.Fatal(err)
15 | }
16 | }
17 |
18 | func read_json(file string) {
19 | f, err := os.ReadFile(file)
20 | check_error(err)
21 | var result map[string]interface{}
22 | json.Unmarshal([]byte(f), &result)
23 |
24 | log.Println(result)
25 | for k, v := range result {
26 | log.Println(k, ":", v)
27 | log.Printf("%T\n", v)
28 | }
29 | }
30 |
31 | func read_csv(file string) {
32 | f, err := os.Open(file)
33 | check_error(err)
34 |
35 | reader := csv.NewReader(f)
36 |
37 | n, err := reader.ReadAll()
38 | check_error(err)
39 | for _, line := range n {
40 | for _, text := range line {
41 | log.Println(text)
42 | }
43 | }
44 | }
45 |
46 | func read_yaml(file string) {
47 | f, err := os.ReadFile(file)
48 | check_error(err)
49 | var data map[string]interface{}
50 |
51 | err = yaml.Unmarshal(f, &data)
52 | check_error(err)
53 | log.Println(data)
54 | for k, v := range data {
55 | log.Println(k, ":", v)
56 | log.Printf("%T", v)
57 | }
58 | }
59 |
60 | func read_toml(file string) {
61 | f, err := os.ReadFile(file)
62 |
63 | check_error(err)
64 |
65 | var data map[interface{}]interface{}
66 |
67 | err = toml.Unmarshal(f, &data)
68 | log.Println(data)
69 |
70 | check_error(err)
71 |
72 | for k, v := range data {
73 | log.Println(k, ":", v)
74 | switch t := v.(type) {
75 | case map[string]interface{}:
76 | for a, b := range t {
77 | log.Println(a, ":", b)
78 | log.Printf("%T\n", b)
79 | }
80 | }
81 | }
82 | }
83 |
84 | func main() {
85 | read_json("json/blog.json")
86 | read_csv("csv/blog.csv")
87 | read_toml("toml/blog.toml")
88 | read_yaml("yaml/blog.yaml")
89 | }
90 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/toml/blog.toml:
--------------------------------------------------------------------------------
1 |
2 | [blog]
3 | name='techstructive-blog'
4 | tags=['go','django','vim']
5 | author='meet gor'
6 | active=true
7 |
8 | [author]
9 | name='Meet Gor'
10 | github='mr-destructive'
11 | twitter='meetgor21'
12 | posts=80
13 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/toml/go.mod:
--------------------------------------------------------------------------------
1 | module toml-read
2 |
3 | go 1.18
4 |
5 | require (
6 | github.com/pelletier/go-toml v1.9.5 // indirect
7 | )
8 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/toml/go.sum:
--------------------------------------------------------------------------------
1 | github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=
2 | github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
3 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/toml/toml.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "os"
6 |
7 | toml "github.com/pelletier/go-toml"
8 | )
9 |
10 | func main() {
11 |
12 | f, err := os.ReadFile("blog.toml")
13 |
14 | if err != nil {
15 | log.Fatal(err)
16 | }
17 |
18 | var data map[interface{}]interface{}
19 |
20 | err = toml.Unmarshal(f, &data)
21 | log.Println(data)
22 |
23 | if err != nil {
24 | log.Fatal(err)
25 | }
26 |
27 | for k, v := range data {
28 | log.Println(k, ":", v)
29 | switch t := v.(type) {
30 | case map[string]interface{}:
31 | for a, b := range t {
32 | log.Println(a, ":", b)
33 | }
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/xml/rss.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/xml"
5 | "io"
6 | "log"
7 | "net/http"
8 | )
9 |
10 | type Rss struct {
11 | XMLName xml.Name `xml:"rss"`
12 | Channel Channel `xml:"channel"`
13 | }
14 |
15 | type Channel struct {
16 | XMLName xml.Name `xml:"channel"`
17 | Title string `xml:"title"`
18 | Description string `xml:"description"`
19 | Item []Item `xml:"item"`
20 | }
21 |
22 | type Item struct {
23 | XMLName xml.Name `xml:"item"`
24 | Title string `xml:"title"`
25 | Link string `xml:"link"`
26 | }
27 |
28 | func check_error(err error) {
29 | if err != nil {
30 | log.Fatal(err)
31 | }
32 | }
33 |
34 | func main() {
35 |
36 | url := "https://meetgor.com/rss.xml"
37 | response, err := http.Get(url)
38 |
39 | check_error(err)
40 |
41 | defer response.Body.Close()
42 | data, err := io.ReadAll(response.Body)
43 |
44 | check_error(err)
45 |
46 | d := Rss{}
47 | err = xml.Unmarshal(data, &d)
48 |
49 | check_error(err)
50 |
51 | for _, item := range d.Channel.Item {
52 | log.Println(item.Title)
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/xml/rss.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Meet Gor
4 | Techstructive Blog Feed
5 | -
6 | Why and How to make and use Vim as a text editor and customizable IDE
7 | https://www.meetgor.com/vim-text-editor-ide
8 |
9 | -
10 | Setting up Vim for Python
11 | https://www.meetgor.com/vim-for-python
12 |
13 |
14 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/xml/xml.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/xml"
5 | "log"
6 | "os"
7 | )
8 |
9 | type Channel struct {
10 | XMLName xml.Name `xml:"channel"`
11 | Title string `xml:"title"`
12 | Description string `xml:"description"`
13 | Item []Item `xml:"item"`
14 | }
15 |
16 | type Item struct {
17 | XMLName xml.Name `xml:"item"`
18 | Title string `xml:"title"`
19 | Link string `xml:"link"`
20 | }
21 |
22 | func main() {
23 |
24 | //f, err := os.Open("rss.xml")
25 | //if err != nil {
26 | // log.Fatal(err)
27 | //}
28 | //defer f.Close()
29 | //log.Printf("%T\n", f)
30 | //data, err := ioutil.ReadAll(f)
31 | //if err != nil {
32 | // log.Fatal(err)
33 | //}
34 | f, err := os.ReadFile("rss.xml")
35 | d := Channel{}
36 | err = xml.Unmarshal(f, &d)
37 | log.Println(d)
38 | if err != nil {
39 | log.Printf("error: %v", err)
40 | }
41 | for _, item := range d.Item {
42 | log.Println(item.Title)
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/yaml/blog.yaml:
--------------------------------------------------------------------------------
1 | title: "Golang Blog Series"
2 | date: "22nd October 2022"
3 | tags: ["go", "files"]
4 | published: false
5 | words: 1500
6 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/yaml/go.mod:
--------------------------------------------------------------------------------
1 | module file-read
2 |
3 | go 1.18
4 |
5 | require (
6 | gopkg.in/yaml.v3 v3.0.1 // indirect
7 | )
8 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/yaml/go.sum:
--------------------------------------------------------------------------------
1 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
2 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
3 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
4 |
--------------------------------------------------------------------------------
/scripts/files/read/config_files/yaml/yaml.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "os"
6 |
7 | yaml "gopkg.in/yaml.v3"
8 | )
9 |
10 | func main() {
11 |
12 | f, err := os.ReadFile("blog.yaml")
13 |
14 | if err != nil {
15 | log.Fatal(err)
16 | }
17 |
18 | var data map[interface{}]interface{}
19 |
20 | err = yaml.Unmarshal(f, &data)
21 | log.Println(data)
22 |
23 | if err != nil {
24 |
25 | log.Fatal(err)
26 | }
27 |
28 | for k, v := range data {
29 | log.Println(k, ":", v)
30 | log.Printf("%T", v)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/scripts/files/read/delimeter.txt:
--------------------------------------------------------------------------------
1 | 10:22:2022
2 | golang:21:read
3 |
4 |
--------------------------------------------------------------------------------
/scripts/files/read/delimiter.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/csv"
5 | "log"
6 | "os"
7 | )
8 |
9 | func main() {
10 |
11 | f, err := os.Open("delimeter.txt")
12 |
13 | if err != nil {
14 | log.Fatal(err)
15 | }
16 | defer f.Close()
17 | reader := csv.NewReader(f)
18 | reader.Comma = ':'
19 | data, err := reader.ReadAll()
20 | if err != nil {
21 |
22 | log.Fatal(err)
23 | }
24 | log.Println(data)
25 | }
26 |
--------------------------------------------------------------------------------
/scripts/files/read/line.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bufio"
5 | "log"
6 | "os"
7 | )
8 |
9 | func main() {
10 |
11 | f, err := os.Open("sample.txt")
12 |
13 | if err != nil {
14 | log.Fatal(err)
15 | }
16 | line_list := []string{}
17 |
18 | defer f.Close()
19 | scanner := bufio.NewScanner(f)
20 | for scanner.Scan() {
21 | line := scanner.Text()
22 | line_list = append(line_list, line)
23 | }
24 | if err := scanner.Err(); err != nil {
25 | log.Fatal(err)
26 | }
27 | for _, line := range line_list {
28 | log.Println(line)
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/scripts/files/read/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "os"
6 | )
7 |
8 | func main() {
9 |
10 | text, err := os.ReadFile("sample.txt")
11 |
12 | if err != nil {
13 | log.Fatal(err)
14 | }
15 |
16 | log.Println(string(text))
17 | }
18 |
--------------------------------------------------------------------------------
/scripts/files/read/sample.txt:
--------------------------------------------------------------------------------
1 | Golang is a programming language.
2 | created: 2007
3 | type:static
4 |
--------------------------------------------------------------------------------
/scripts/files/read/word.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bufio"
5 | "log"
6 | "os"
7 | )
8 |
9 | func main() {
10 | f, err := os.Open("sample.txt")
11 | if err != nil {
12 | log.Fatal(err)
13 | }
14 | defer f.Close()
15 |
16 | scanner := bufio.NewScanner(f)
17 | scanner.Split(bufio.ScanWords)
18 |
19 | if err := scanner.Err(); err != nil {
20 | log.Fatal(err)
21 | }
22 |
23 | wordlist := []string{}
24 | for scanner.Scan() {
25 | word := scanner.Text()
26 | wordlist = append(wordlist, word)
27 | log.Println(word)
28 | }
29 | log.Println(wordlist)
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/scripts/files/write/abc.txt:
--------------------------------------------------------------------------------
1 | Hi, I am a gopher!
2 | golang
3 | python
4 | rust
5 | javascript
6 | ruby
7 |
--------------------------------------------------------------------------------
/scripts/files/write/append.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bufio"
5 | "bytes"
6 | "log"
7 | "os"
8 | )
9 |
10 | func HandleError(err error) {
11 | if err != nil {
12 | log.Fatal(err)
13 | }
14 | }
15 |
16 | func main() {
17 | f, err := os.OpenFile("test.txt", os.O_RDWR, 0660)
18 | /* test.txt
19 | Hi
20 | Hello
21 | World
22 | Gophers
23 | */
24 | HandleError(err)
25 | m := bufio.NewScanner(f)
26 | bytes_till := 0
27 | //lines := []string{}
28 | // line to be appended
29 | lines_till := 2
30 | var lines_after string
31 | var line_till string
32 | i := 0
33 | for m.Scan() {
34 | line := m.Text()
35 | //lines = append(lines, line)
36 | if i < lines_till {
37 | bytes_till += bytes.Count([]byte(line), []byte{})
38 | if i > 0 {
39 | line_till += "\n"
40 | }
41 | line_till += line
42 | } else {
43 | lines_after += "\n" + line
44 | }
45 | i += 1
46 | }
47 | HandleError(m.Err())
48 | insert_text := line_till + "\nInserted content"
49 | insert_text_bytes := bytes.Count([]byte(insert_text), []byte{})
50 | lines_after_bytes := bytes.Count([]byte(lines_after), []byte{})
51 |
52 | err = os.WriteFile("test.txt", []byte(insert_text), 0660)
53 | HandleError(err)
54 | _, err = f.WriteAt([]byte(lines_after), int64(lines_after_bytes)+int64(insert_text_bytes))
55 | HandleError(err)
56 | defer f.Close()
57 | }
58 |
--------------------------------------------------------------------------------
/scripts/files/write/delete.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "os"
6 | )
7 |
8 | func main() {
9 | /*
10 | Hi
11 | Hello
12 | World
13 | Gophers
14 | */
15 | // set only the first 6 bytes of the file
16 | // delete the rest
17 | err := os.Truncate("test.txt", 6)
18 | if err != nil {
19 | log.Fatal(err)
20 | }
21 | // Delete all the contents
22 | //err = os.Truncate("test.txt", 0)
23 | if err != nil {
24 | log.Fatal(err)
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/scripts/files/write/format.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "os"
7 | )
8 |
9 | func HandleErr(err error) {
10 | if err != nil {
11 | log.Fatal(err)
12 | }
13 | }
14 | func main() {
15 | f, err := os.Create("temp.txt")
16 | HandleErr(err)
17 | name, lang, exp := "John", "go", 2
18 | _, err = fmt.Fprint(f, "Hi, I am ", name, "\n")
19 | HandleErr(err)
20 | _, err = fmt.Fprintf(f, "Language of choice: %s.\n", lang)
21 | HandleErr(err)
22 | _, err = fmt.Fprintln(f, "Having", exp, "years of experience.")
23 | HandleErr(err)
24 | defer f.Close()
25 | }
26 |
--------------------------------------------------------------------------------
/scripts/files/write/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "os"
6 | )
7 |
8 | func HandleError(err error) {
9 | if err != nil {
10 | log.Fatal(err)
11 | }
12 | }
13 |
14 | func main() {
15 | // Write
16 | str := "Hi, I am a gopher!\n"
17 | f, err := os.OpenFile("abc.txt", os.O_WRONLY, 0660)
18 | //f, err := os.Create("abc.txt")
19 | HandleError(err)
20 | _, err = f.Write([]byte(str))
21 | HandleError(err)
22 | langs := []string{"golang", "python", "rust", "javascript", "ruby"}
23 | for _, lang := range langs {
24 | _, err := f.WriteString(lang + "\n")
25 | HandleError(err)
26 | }
27 | defer f.Close()
28 |
29 | // Overwrite the pervious content in the file
30 | data := []byte{115, 111, 109, 101, 65}
31 | err = os.WriteFile("test.txt", data, 0660)
32 | HandleError(err)
33 |
34 | s := "Hello"
35 | err = os.WriteFile("test.txt", []byte(s), 0660)
36 | HandleError(err)
37 |
38 | // Append
39 | s = "\nHi\nWorld\nGophers"
40 | // open the file for writing/appending content
41 | f, err = os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY, 0660)
42 | HandleError(err)
43 | _, err = f.WriteString(s)
44 | HandleError(err)
45 | defer f.Close()
46 |
47 | // Append at a specific line
48 | // check out the file append.go
49 |
50 | //Delete conent from a file
51 | err = os.Truncate("test.txt", 5)
52 | HandleError(err)
53 | }
54 |
--------------------------------------------------------------------------------
/scripts/files/write/replace.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "log"
6 | "os"
7 | )
8 |
9 | func HandleError(err error) {
10 | if err != nil {
11 | log.Fatal(err)
12 | }
13 | }
14 |
15 | func main() {
16 | filename := "test.txt"
17 | file, err := os.ReadFile(filename)
18 | HandleError(err)
19 | old_text := "e"
20 | new_text := "E"
21 | new_content := bytes.Replace(file, []byte(old_text), []byte(new_text), 2)
22 | err = os.WriteFile(filename, new_content, 0660)
23 | HandleError(err)
24 | }
25 |
--------------------------------------------------------------------------------
/scripts/files/write/temp.txt:
--------------------------------------------------------------------------------
1 | Hi, I am John
2 | Language of choice: go.
3 | Having 2 years of experience.
4 |
--------------------------------------------------------------------------------
/scripts/files/write/test.txt:
--------------------------------------------------------------------------------
1 | Hello
--------------------------------------------------------------------------------
/scripts/functions/anonymous_functions.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 | import "strings"
5 |
6 | func get_csv(index int, str string, t func(csv string)[]string) [][]string{
7 | s := t(str)
8 | var res [][]string
9 | for i := 1; i arr[j] {
15 | arr[i], arr[j] = arr[j], arr[i]
16 | }
17 | }
18 | }
19 | }
20 |
21 | func main() {
22 | arr := []int{10, 28, 57, 96, 76, 8, 97, 10}
23 | sort(arr)
24 | fmt.Println(arr)
25 | strarr := []string{"b", "e", "a"}
26 | sort(strarr)
27 | fmt.Println(strarr)
28 | }
29 |
--------------------------------------------------------------------------------
/scripts/generics/struct-stack.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | type Stack[T any] struct {
8 | items []T
9 | }
10 |
11 | // it is not needed, but handy and a good practise to create one
12 | func NewStack[T any]() *Stack[T] {
13 | return &Stack[T]{}
14 | }
15 |
16 | func (s *Stack[T]) Push(item T) {
17 | s.items = append(s.items, item)
18 | }
19 |
20 | func (s *Stack[T]) Pop() T {
21 | if len(s.items) == 0 {
22 | panic("Stack is empty")
23 | }
24 | index := len(s.items) - 1
25 | item := s.items[index]
26 | s.items = s.items[:index]
27 | return item
28 | }
29 |
30 | func main() {
31 | intStack := NewStack[int]()
32 | intStack.Push(10)
33 | intStack.Push(20)
34 | intStack.Push(30)
35 | fmt.Println("Integer Stack")
36 | fmt.Println(intStack)
37 | intStack.Pop()
38 | intStack.Pop()
39 | fmt.Println(intStack)
40 |
41 | // without the NewStack method
42 | strStack := Stack[string]{}
43 | strStack.Push("c")
44 | strStack.Push("python")
45 | strStack.Push("mojo")
46 | fmt.Println("String Stack:")
47 | fmt.Println(strStack)
48 | strStack.Pop()
49 | fmt.Println(strStack)
50 | }
51 |
--------------------------------------------------------------------------------
/scripts/go-routines/data/f1.txt:
--------------------------------------------------------------------------------
1 | Welcome to Goworld!
2 | Hello Gophers!
3 | Hello Gophers!
4 | Welcome to Goworld!
5 |
--------------------------------------------------------------------------------
/scripts/go-routines/data/f2.txt:
--------------------------------------------------------------------------------
1 | line 1.
2 |
--------------------------------------------------------------------------------
/scripts/go-routines/file-rw.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io/ioutil"
6 | "os"
7 | "sync"
8 | )
9 |
10 | func reader(id int, filename string, wg *sync.WaitGroup, mutex *sync.RWMutex) {
11 | defer wg.Done()
12 | if !mutex.TryRLock() {
13 | fmt.Printf("Reader %d blocked!\n", id)
14 | return
15 | }
16 | defer mutex.RUnlock()
17 | f, err := os.OpenFile(filename, os.O_RDONLY, 0644)
18 | defer f.Close()
19 | if err != nil {
20 | fmt.Println(err)
21 | }
22 | bytes, err := ioutil.ReadAll(f)
23 | if err != nil {
24 | fmt.Println(err)
25 | return
26 | }
27 | fmt.Printf("Reader %d read: %s\n", id, string(bytes))
28 | }
29 |
30 | func writer(id int, filename, content string, wg *sync.WaitGroup, mutex *sync.RWMutex) {
31 |
32 | defer wg.Done()
33 | mutex.Lock()
34 | defer mutex.Unlock()
35 | f, err := os.OpenFile(filename, os.O_WRONLY, 0644)
36 | defer f.Close()
37 | if err != nil {
38 | fmt.Println(err)
39 | }
40 | f.WriteString(content)
41 | fmt.Printf("Writer %d: wrote -> %s\n", id, content)
42 | }
43 |
44 | func main() {
45 |
46 | var wg sync.WaitGroup
47 | var mutex sync.RWMutex
48 | wg.Add(5)
49 | for i := 0; i < 5; i++ {
50 | go reader(i, "data/f2.txt", &wg, &mutex)
51 | }
52 |
53 | wg.Add(2)
54 | for i := 0; i < 2; i++ {
55 | content := fmt.Sprintf("line %d.\n", i)
56 | go writer(i, "data/f2.txt", content, &wg, &mutex)
57 | }
58 |
59 | wg.Wait()
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/scripts/go-routines/mail.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | func sendMail(address string) {
9 | fmt.Println("Sending mail to", address)
10 | }
11 |
12 | func main() {
13 | emails := []string{
14 | "recipient1@example.com",
15 | "recipient2@example.com",
16 | "xyz@example.com",
17 | }
18 | wg := sync.WaitGroup{}
19 | wg.Add(len(emails))
20 |
21 | for _, email := range emails {
22 | mail := email
23 | go func(m string) {
24 | sendMail(m)
25 | wg.Done()
26 | }(mail)
27 | }
28 | wg.Wait()
29 | fmt.Println("All emails queued for sending")
30 | // Do other stuff
31 | }
32 |
--------------------------------------------------------------------------------
/scripts/go-routines/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func process() {
9 | time.Sleep(time.Second)
10 | fmt.Println("Hello World!")
11 | }
12 |
13 | func main() {
14 | start := time.Now()
15 | go process()
16 | go process()
17 | end := time.Now()
18 | duration := end.Sub(start)
19 | time.Sleep(time.Second)
20 | fmt.Println(duration)
21 | }
22 |
--------------------------------------------------------------------------------
/scripts/go-routines/mutex.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "sync"
7 | )
8 |
9 | func WriteToFile(filename string, contents string, buffer *[]byte, wg *sync.WaitGroup, mutex *sync.Mutex) {
10 | defer wg.Done()
11 | contentBytes := []byte(contents)
12 |
13 | mutex.Lock()
14 | *buffer = append(*buffer, contentBytes...)
15 |
16 | f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0644)
17 | if err != nil {
18 | fmt.Println(err)
19 | }
20 | defer f.Close()
21 | _, err = f.Write(contentBytes)
22 | if err != nil {
23 | fmt.Println(err)
24 | }
25 | mutex.Unlock()
26 | }
27 |
28 | func main() {
29 | var wg sync.WaitGroup
30 | var mut sync.Mutex
31 | var sharedBuffer []byte
32 |
33 | wg.Add(2)
34 | go WriteToFile("data/f1.txt", "Hello Gophers!\n", &sharedBuffer, &wg, &mut)
35 | go WriteToFile("data/f1.txt", "Welcome to Goworld!\n", &sharedBuffer, &wg, &mut)
36 | wg.Wait()
37 |
38 | fmt.Println(string(sharedBuffer))
39 | }
40 |
--------------------------------------------------------------------------------
/scripts/go-routines/no-mutex.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "sync"
7 | )
8 |
9 | func WriteToFile(filename string, contents string, buffer *[]byte, wg *sync.WaitGroup) {
10 | defer wg.Done()
11 | contentsBytes := []byte(contents)
12 | *buffer = append(*buffer, contentsBytes...)
13 | err := os.WriteFile(filename, contentsBytes, 0644)
14 | if err != nil {
15 | fmt.Println(err)
16 | }
17 | }
18 |
19 | func main() {
20 | var wg sync.WaitGroup
21 | var sharedBuffer []byte
22 |
23 | wg.Add(2)
24 | go WriteToFile("data/f1.txt", "Hello\n", &sharedBuffer, &wg)
25 | go WriteToFile("data/f1.txt", "World!\n", &sharedBuffer, &wg)
26 | wg.Wait()
27 |
28 | fmt.Println(string(sharedBuffer))
29 | }
30 |
--------------------------------------------------------------------------------
/scripts/go-routines/no-rwmutex.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | "time"
7 | )
8 |
9 | func reader(id int, count *int, wg *sync.WaitGroup, mutex *sync.Mutex) {
10 | defer wg.Done()
11 | if !mutex.TryLock() {
12 | fmt.Printf("Reader %d blocked!\n", id)
13 | return
14 | }
15 | defer mutex.Unlock()
16 | fmt.Printf("Reader %d: read count %d\n", id, *count)
17 |
18 | }
19 | func writer(id, increment int, count *int, wg *sync.WaitGroup, mutex *sync.Mutex) {
20 |
21 | defer wg.Done()
22 | mutex.Lock()
23 | defer mutex.Unlock()
24 | *count += increment
25 | time.Sleep(5 * time.Millisecond)
26 | fmt.Printf("Writer %d: wrote count %d\n", id, *count)
27 | }
28 |
29 | func main() {
30 |
31 | count := 1
32 | var wg sync.WaitGroup
33 | var mutex sync.Mutex
34 | readers := 5
35 | writers := 3
36 |
37 | wg.Add(readers)
38 | for i := 0; i < readers; i++ {
39 | go reader(i, &count, &wg, &mutex)
40 | }
41 |
42 | wg.Add(writers)
43 | for i := 0; i < writers; i++ {
44 | go writer(i, 1, &count, &wg, &mutex)
45 | }
46 | wg.Wait()
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/scripts/go-routines/rwmutex.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | "time"
7 | )
8 |
9 | func reader(id int, count *int, wg *sync.WaitGroup, mutex *sync.RWMutex) {
10 | defer wg.Done()
11 | if !mutex.TryRLock() {
12 | fmt.Printf("Reader %d blocked!\n", id)
13 | return
14 | }
15 | defer mutex.RUnlock()
16 | fmt.Printf("Reader %d: read count %d\n", id, *count)
17 |
18 | }
19 | func writer(id, increment int, count *int, wg *sync.WaitGroup, mutex *sync.RWMutex) {
20 |
21 | defer wg.Done()
22 | mutex.Lock()
23 | defer mutex.Unlock()
24 | *count += increment
25 | time.Sleep(5 * time.Millisecond)
26 | fmt.Printf("Writer %d: wrote count %d\n", id, *count)
27 | }
28 |
29 | func main() {
30 |
31 | count := 1
32 | var wg sync.WaitGroup
33 | var mutex sync.RWMutex
34 | readers := 5
35 | writers := 3
36 |
37 | wg.Add(readers)
38 | for i := 0; i < readers; i++ {
39 | go reader(i, &count, &wg, &mutex)
40 | }
41 |
42 | wg.Add(writers)
43 | for i := 0; i < writers; i++ {
44 | go writer(i, 1, &count, &wg, &mutex)
45 | }
46 | wg.Wait()
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/scripts/go-routines/wg.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | "time"
7 | )
8 |
9 | func process(pid int, wg *sync.WaitGroup) {
10 | fmt.Printf("Started process %d\n", pid)
11 | time.Sleep(1 * time.Second)
12 | fmt.Printf("Completed process %d\n", pid)
13 | defer wg.Done()
14 | }
15 |
16 | func main() {
17 |
18 | now := time.Now()
19 | var wg sync.WaitGroup
20 |
21 | for i := 0; i < 10; i++ {
22 | wg.Add(1)
23 | go process(i, &wg)
24 | }
25 | wg.Wait()
26 | fmt.Println("All processes completed")
27 | end := time.Now()
28 | fmt.Println(end.Sub(now))
29 | }
30 |
--------------------------------------------------------------------------------
/scripts/hello-world/go.mod:
--------------------------------------------------------------------------------
1 | module script.go
2 |
3 | go 1.17
4 |
--------------------------------------------------------------------------------
/scripts/hello-world/script.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main() {
8 | fmt.Println("Hello,Gophers!")
9 | }
10 |
--------------------------------------------------------------------------------
/scripts/im-mutable/immutable.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 |
7 | // Data types which are Immutable
8 | // String
9 | str := "gopher"
10 | str_copy := str
11 | str_copy = "cooper"
12 | fmt.Println("str = ", str)
13 | fmt.Println("str_copy = ", str_copy)
14 |
15 | // Character at index cannot be changed in string
16 |
17 | s := "StarWars"
18 | s[4] = 'C'
19 | // s[4] = "C"
20 | // also won't work
21 | fmt.Println(s)
22 |
23 | // bool
24 | boolean := true
25 | b := boolean
26 | b = false
27 | fmt.Println("boolean = ", boolean)
28 | fmt.Println("b = ", b)
29 |
30 | // pointer, function pointers
31 | n := 567
32 | t := 123
33 | ptr := &n
34 | ptr_new := ptr
35 | fmt.Println("ptr = ", ptr)
36 | fmt.Println("ptr_new = ", ptr_new)
37 |
38 | ptr_new = &t
39 |
40 | fmt.Println("ptr = ", ptr)
41 | fmt.Println("ptr_new = ", ptr_new)
42 |
43 | // Interface
44 | // TODO Learn
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/scripts/im-mutable/mutable.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 |
7 | // Data types which are Mutable
8 | // Mutable Type allow us to modify the underlying value of a memory address pointed by a variable
9 | // Slice
10 | s := []int{1, 2, 3}
11 | fmt.Printf("S[1] -> %p\n", &s[1])
12 | p := s
13 | p[1] = 4
14 | fmt.Printf("S[1] -> %p\n", &s[1])
15 |
16 | fmt.Println("s =", s)
17 | fmt.Println("p =", p)
18 |
19 | // Array
20 | a := [3]int{10, 20, 30}
21 | fmt.Printf("A[1] -> %p\n", &a[1])
22 | b := a
23 | b[1] = 40
24 | fmt.Printf("A[1] -> %p\n", &a[1])
25 |
26 | fmt.Println("a =", a)
27 | fmt.Println("b =", b)
28 |
29 | // Map
30 | m := map[string]int{"level": 5, "health": 9}
31 | fmt.Println(m)
32 | n := m
33 | n["food"] = 12
34 |
35 | fmt.Println("m =", m)
36 | fmt.Println("n =", n)
37 |
38 | // Channel
39 | // TODO Learn
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/scripts/input/scan.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | // Basic input with Scan
7 | var pname string
8 | fmt.Println("Enter your favourite programming language: ")
9 | fmt.Scan(&pname)
10 | fmt.Println("So, your favourite programming language is", pname)
11 |
12 | // Multiple inputs with Scan
13 | var (
14 | name string
15 | age int
16 | gender rune
17 | )
18 | fmt.Println("Enter your name age and gender: ")
19 | fmt.Scan(&name, &age, &gender)
20 | fmt.Printf("Hello %s, you are a %c and %d years old", name, gender, age)
21 | }
22 |
--------------------------------------------------------------------------------
/scripts/input/scanf.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | // Scanf for formatted input
7 | var (
8 | name string
9 | age int
10 | gender rune
11 | )
12 | fmt.Println("Enter your name age and gender: ")
13 | fmt.Scanf("%s \n %d %c", &name, &age, &gender)
14 | // for single input with Scanf
15 | // fmt.Scanf("%s", &name)
16 | fmt.Printf("Hello %s, you are a %c and %d years old", name, gender, age)
17 | }
18 |
--------------------------------------------------------------------------------
/scripts/input/scanln.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | // Scanln for input only beofre line break
7 | var s string
8 | fmt.Println("Enter a string: ")
9 | fmt.Scanln(&s)
10 | fmt.Println("Inputted string : ", s)
11 | }
12 |
--------------------------------------------------------------------------------
/scripts/interfaces/declare.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type Player struct {
6 | name string
7 | health int
8 | }
9 |
10 | type Mob struct {
11 | name string
12 | health int
13 | is_passive bool
14 | }
15 |
16 | type Creature interface {
17 | intro() string
18 | //attack() int
19 | //heal() int
20 | }
21 |
22 | func main() {
23 | player := Player{name: "Steve"}
24 | mob := Mob{name: "Zombie"}
25 | fmt.Println(player)
26 | fmt.Println(mob)
27 | }
28 |
--------------------------------------------------------------------------------
/scripts/interfaces/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "strconv"
6 | )
7 |
8 | type Creature interface {
9 | intro() string
10 | attack(*int) int
11 | //heal() int
12 | }
13 |
14 | type Player struct {
15 | name string
16 | health int
17 | }
18 |
19 | type Mob struct {
20 | name string
21 | health int
22 | category bool
23 | }
24 |
25 | func (p Player) intro() string {
26 | fmt.Println("Player has spawned")
27 | return p.name
28 | }
29 |
30 | func (p Player) attack(m_health *int) int {
31 | fmt.Println("Player has attacked!")
32 | *m_health = *m_health - 50
33 | return *m_health
34 | }
35 |
36 | func (m Mob) intro() string {
37 | var name string
38 | if m.name != "" {
39 | name = m.name
40 | } else {
41 | name = "Mob"
42 | }
43 | fmt.Printf("A wild %s has appeared!\n", name)
44 | return m.name
45 | }
46 |
47 | func (m Mob) attack(p_health *int) int {
48 | fmt.Printf("%s has attacked you! -%d\n", m.name, 30)
49 | *p_health = *p_health - 30
50 | return *p_health
51 | }
52 |
53 | func parse_int(n interface{}) int {
54 | switch n.(type) {
55 | case int:
56 | return (n).(int) * (n).(int)
57 | case string:
58 | s, _ := strconv.Atoi(n.(string))
59 | return s
60 | case float64:
61 | return int(n.(float64))
62 | default:
63 | return n.(int)
64 | }
65 | }
66 |
67 | func main() {
68 | player := Player{name: "Steve", health: 100}
69 | mob := Mob{name: "Zombie", health: 140}
70 | fmt.Println(player.intro())
71 | fmt.Println(mob.intro())
72 | fmt.Println(mob)
73 | fmt.Println(player)
74 | fmt.Println(player.attack(&mob.health))
75 | fmt.Println(mob.attack(&player.health))
76 | fmt.Println(mob)
77 | fmt.Println(player)
78 | num := parse_int(4)
79 | fmt.Println(num)
80 | num = parse_int("4")
81 | fmt.Println(num)
82 | num = parse_int(4.1243)
83 | fmt.Println(num)
84 |
85 | entity := []Creature{Player{}, Mob{}, Mob{}, Player{}}
86 |
87 | for _, obj := range entity {
88 | fmt.Println(obj.intro())
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/scripts/interfaces/slice.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | type Device interface {
8 | wifi() string
9 | }
10 |
11 | type Laptop struct {
12 | name string
13 | }
14 |
15 | type Phone struct {
16 | name string
17 | price int
18 | ram int
19 | }
20 |
21 | func (l Laptop) wifi() string {
22 | fmt.Println("+Connect to wifi with Laptop interface")
23 | return l.name
24 | }
25 |
26 | func (m Phone) wifi() string {
27 | fmt.Println("+Connect to wifi with Mobile interface")
28 | return m.name
29 | }
30 |
31 | func main() {
32 |
33 | devices := []Device{Laptop{}, Phone{}, Phone{}, Laptop{}}
34 |
35 | for _, obj := range devices {
36 | fmt.Println(obj.wifi())
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/scripts/interfaces/switch_interface.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func compute_length(n interface{}) int {
8 | switch n.(type) {
9 | case int:
10 | return (n).(int)
11 | case string:
12 | return len(n.(string))
13 | case []int:
14 | return len(n.([]int))
15 | case []string:
16 | return len(n.([]string))
17 | case []float64:
18 | return len(n.([]float64))
19 | default:
20 | return n.(int)
21 | }
22 | }
23 |
24 | func main() {
25 | num := compute_length(2)
26 | fmt.Println(num)
27 | num = compute_length("hello world")
28 | fmt.Println(num)
29 | num = compute_length([]int{1, 3, 4})
30 | fmt.Println(num)
31 | num = compute_length([]string{"python", "c++", "js", "java", "go"})
32 | fmt.Println(num)
33 | }
34 |
--------------------------------------------------------------------------------
/scripts/loops/for.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 |
7 | //three statement basic for loop
8 | for k := 0; k < 4; k++ {
9 | fmt.Println(k)
10 | }
11 |
12 | // range based for loop
13 | name := "GOLANG"
14 | for i, s := range name {
15 | fmt.Printf("%d -> %c\n", i, s)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/scripts/loops/infinite.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | //Inifinite Loop better keep commented
7 | /*
8 | flag := 4
9 | for {
10 | flag++
11 | fmt.Println(flag)
12 | }
13 | */
14 |
15 | // Break Statement
16 | flag := 1
17 | for {
18 | fmt.Println(flag)
19 | flag++
20 | if flag == 7 {
21 | fmt.Println("It's time to break at", flag)
22 | break
23 | }
24 | }
25 |
26 | // Continue Statement
27 | counter := 2
28 | for counter < 4 {
29 | counter++
30 | if counter < 4 {
31 | continue
32 | }
33 | fmt.Println("Missed the Continue? at counter =", counter)
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/scripts/loops/while.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | count := 3
7 | for count < 9 {
8 | fmt.Println(count)
9 | count++
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/scripts/maps/map.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 |
7 | // simple map litetal
8 | char_freq := map[string]int{
9 | "M": 1,
10 | "e": 2,
11 | "t": 1,
12 | }
13 | fmt.Println(char_freq)
14 |
15 | // declare map with make function
16 | marks := make(map[int]int)
17 | fmt.Println(len(marks))
18 | marks[65] = 8
19 | marks[95] = 3
20 | marks[80] = 5
21 | fmt.Println(marks)
22 |
23 | // declare map with new function
24 | name := new(map[byte]int)
25 | *name = map[byte]int{}
26 | name_map := *name
27 | name_map['m'] = 1
28 | name_map['e'] = 2
29 | name_map['t'] = 1
30 | fmt.Println(len(name_map))
31 | fmt.Println(name_map)
32 |
33 | // check if a key exist in map
34 | var key byte = 't'
35 | value, exist := name_map[key]
36 | if exist == true {
37 | fmt.Printf("The key %c exist and has value %d\n", key, value)
38 | } else {
39 | fmt.Printf("The key %c does not exist.\n", key)
40 | }
41 |
42 | for k, _ := range name_map {
43 | fmt.Printf("%c\n", k)
44 | }
45 |
46 | cart_list := map[string]int{
47 | "shirt": 2,
48 | "mug": 4,
49 | "shoes": 3,
50 | }
51 | fmt.Println(cart_list)
52 |
53 | // add new key in map
54 | cart_list["jeans"] = 1
55 |
56 | // update existing keys in map
57 | cart_list["mug"] = 3
58 |
59 | // delete keys from map
60 | delete(cart_list, "shoes")
61 | fmt.Println(cart_list)
62 |
63 | is_prime := map[int]bool{
64 | 7: true,
65 | 9: false,
66 | 13: true,
67 | 15: false,
68 | 16: false,
69 | }
70 |
71 | // iterate over map
72 | for key, value := range is_prime {
73 | fmt.printf("%d -> %t\n", key, value)
74 | }
75 |
76 | // iterate only with key or value
77 | for key, _ := range is_prime {
78 | fmt.Printf("Key : %t\n", _)
79 | }
80 |
81 | for _, value := range is_prime {
82 | fmt.Printf("Value: %t\n", value)
83 | }
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/scripts/math/basic-functions/constants.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | )
7 |
8 | func main() {
9 | fmt.Println("Pi = ", math.Pi)
10 | fmt.Println("E = ", math.E)
11 | fmt.Println("Phi = ", math.Phi)
12 | fmt.Println("Sqrt of 2 = ", math.Sqrt2)
13 | fmt.Println("Naturla Log 2 = ", math.Ln2)
14 | fmt.Println("Naturla Log 10 = ", math.Ln10)
15 | }
16 |
--------------------------------------------------------------------------------
/scripts/math/basic-functions/expo_log.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | )
7 |
8 | func main() {
9 | // exponential function
10 | var x float64 = 2
11 | y := math.Exp(x)
12 | fmt.Println("e^x = ", y)
13 | var n float64 = 3.5
14 | y = math.Exp2(n)
15 | fmt.Println("2^n = ", y)
16 |
17 | // Logarithmic function
18 | y = math.Log(x)
19 | fmt.Println("natural log x = ", y)
20 |
21 | n = 128
22 | y = math.Log2(n)
23 | fmt.Println("Log2 of 100 = ", y)
24 | }
25 |
--------------------------------------------------------------------------------
/scripts/math/basic-functions/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | )
7 |
8 | func main() {
9 |
10 | //absolute function
11 | a := 45
12 | b := 100
13 | diff := a - b
14 | fmt.Println(diff)
15 |
16 | absolute_diff := math.Abs(float64(a) - float64(b))
17 | fmt.Println(absolute_diff)
18 |
19 | //min-max
20 | a = 120
21 | b = 54
22 | minimum := math.Min(float64(a), float64(b))
23 | maximum := math.Max(float64(a), float64(b))
24 | fmt.Printf("Min of %v and %v is %v \n", a, b, minimum)
25 | fmt.Printf("Max of %v and %v is %v \n", a, b, maximum)
26 |
27 | //pow and pow-10
28 | var x float64 = 3
29 | var y float64 = 4
30 | z := math.Pow(x, y)
31 | z10 := math.Pow10(int(x))
32 | fmt.Println("X ^ Y = ", z)
33 | fmt.Println("10 ^ X = ", z10)
34 |
35 | // sqrt and cbrt
36 |
37 | var k float64 = 125
38 | sqrt_of_k := math.Sqrt(k)
39 | cbrt_of_k := math.Cbrt(k)
40 |
41 | fmt.Printf("Square root of %v = %v \n", k, sqrt_of_k)
42 | fmt.Printf("Cube root of %v = %v \n", k, cbrt_of_k)
43 |
44 | // truncate
45 |
46 | var p float64 = 445.235
47 | trunc_p := math.Trunc(p)
48 | fmt.Printf("Truncated value of %v = %v \n", p, trunc_p)
49 | p = 123.678
50 | trunc_p = math.Trunc(p)
51 | fmt.Printf("Truncated value of %v = %v \n", p, trunc_p)
52 |
53 | // ceil
54 |
55 | var c float64 = 33.25
56 | ceil_c := math.Ceil(c)
57 | fmt.Printf("Ceiled value of %v = %v \n", c, ceil_c)
58 | c = 134.78
59 | ceil_c = math.Ceil(c)
60 | fmt.Printf("Ceiled value of %v = %v \n", c, ceil_c)
61 | }
62 |
--------------------------------------------------------------------------------
/scripts/math/basic-functions/trignometric.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | )
7 |
8 | func main() {
9 | // basic trigonometric functions
10 | var x float64 = math.Pi / 2
11 | sinx := math.Sin(x)
12 | cosx := math.Cos(x)
13 | tanx := math.Tan(x)
14 | fmt.Printf("Sin(%v) = %v \n", x, sinx)
15 | fmt.Printf("Cos(%v) = %v \n", x, cosx)
16 | fmt.Printf("Tan(%v) = %v \n", x, tanx)
17 |
18 | // hyperbolic trigonometric functions
19 | var h float64 = math.Pi / 2
20 | sinh := math.Sinh(h)
21 | cosh := math.Cosh(h)
22 | tanh := math.Tanh(h)
23 | fmt.Printf("Sinh(%v) = %v \n", h, sinh)
24 | fmt.Printf("Cosh(%v) = %v \n", h, cosh)
25 | fmt.Printf("Tanh(%v) = %v \n", h, tanh)
26 |
27 | // Inverse Trigonometric functions
28 | var y float64 = -1
29 | arc_sin := math.Asin(y)
30 | arc_cos := math.Acos(y)
31 | arc_tan := math.Atan(y)
32 | fmt.Printf("Sin^-1(%v) = %v \n", y, arc_sin)
33 | fmt.Printf("Cos^-1(%v) = %v \n", y, arc_cos)
34 | fmt.Printf("Tan^-1(%v) = %v \n", y, arc_tan)
35 | }
36 |
--------------------------------------------------------------------------------
/scripts/math/basic-functions/type_casting.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | foo := 77
7 | fmt.Printf("Type of foo = %T \n", foo)
8 | fmt.Println("foo = ", int(foo))
9 | fmt.Println("String Cast: ", string(foo))
10 | fmt.Println("Float Cast: ", float64(foo))
11 | var a float64 = 5
12 | var b float64 = 0
13 | fmt.Println(a / b)
14 | }
15 |
--------------------------------------------------------------------------------
/scripts/math/bit.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math/bits"
6 | )
7 |
8 | func main() {
9 | s, c := bits.Add(0, 9, 1)
10 | fmt.Printf("Sum = %d \nCarry = %d \n", s, c)
11 |
12 | // (45) in decimal = (1 0 1 1 0 1) in binary
13 | var n uint = 45
14 | length := bits.Len(n)
15 | ones_in_45 := bits.OnesCount(n)
16 | fmt.Printf("Minimum bits required to represent 45 = %d \n", length)
17 | fmt.Printf("Set Bits in 45 = %d \n", ones_in_45)
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/scripts/math/complex.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math/cmplx"
6 | )
7 |
8 | func main() {
9 |
10 | x := complex(5, 8)
11 | y := complex(3, 4)
12 | mod_x := cmplx.Abs(x)
13 | mod_y := cmplx.Abs(y)
14 | conj_x := cmplx.Conj(x)
15 | phase_x := cmplx.Phase(x)
16 | mod, phase := cmplx.Polar(x)
17 |
18 | fmt.Println("x = ", x)
19 | fmt.Println("Modulus of x = ", mod_x)
20 | fmt.Println("Modulus of y = ", mod_y)
21 | fmt.Println("Conjugate of x = ", conj_x)
22 | fmt.Println("Phase of x = ", phase_x)
23 | fmt.Printf("Polar Form : %v, %v\n", mod, phase)
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/scripts/math/rand.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math/rand"
6 | )
7 |
8 | func main() {
9 | // random integer generation
10 | x := rand.Int()
11 | fmt.Println(x)
12 |
13 | // random number generation till range
14 | for i := 0; i < 5; i++ {
15 | y := rand.Intn(10)
16 | fmt.Println(y)
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/scripts/operators/arithmetic/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | a := 30
7 | b := 50
8 | fmt.Println("A + B = ", a+b)
9 | fmt.Println("A - B = ", a-b)
10 | fmt.Println("A * B = ", a*b)
11 | fmt.Println("A / B = ", a/b)
12 | fmt.Println("A % B = ", a%b)
13 |
14 | k := 3
15 | j := 20
16 | fmt.Println("k = ", k)
17 | fmt.Println("j = ", j)
18 | k++
19 | j--
20 | fmt.Println("k = ", k)
21 | fmt.Println("j = ", j)
22 | }
23 |
--------------------------------------------------------------------------------
/scripts/operators/assignment/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | var a int = 100
7 | b := 20
8 | fmt.Println("a = ", a)
9 | fmt.Println("b = ", b)
10 | a += 30
11 | fmt.Println("a = ", a)
12 | b -= 5
13 | fmt.Println("b = ", b)
14 | a *= b
15 | fmt.Println("a = ", a)
16 | fmt.Println("b = ", b)
17 | a /= b
18 | fmt.Println("a = ", a)
19 | fmt.Println("b = ", b)
20 | a %= b
21 | fmt.Println("a = ", a)
22 | fmt.Println("b = ", b)
23 | }
24 |
--------------------------------------------------------------------------------
/scripts/operators/bitwise/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | x := 3
7 | y := 5
8 | // 3 -> 011
9 | // 5 -> 101
10 | fmt.Println("X AND Y = ", x&y)
11 | fmt.Println("X OR Y = ", x|y)
12 | fmt.Println("X EXOR Y = ", x^y)
13 | fmt.Println("X Right Shift 1 = ", x>>1)
14 | fmt.Println("X Right Shift 2 = ", x>>2)
15 | fmt.Println("Y Left Shift 1 = ", y<<1)
16 | fmt.Println("X = ", x&^y)
17 | }
18 |
--------------------------------------------------------------------------------
/scripts/operators/comparison/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | a := 45
7 | b := 12
8 | fmt.Println("Is A equal to B ? ", a == b)
9 | fmt.Println("Is A not equal to B ? ", a != b)
10 | fmt.Println("Is A greater than B ? ", a > b)
11 | fmt.Println("Is A less than B ? ", a < b)
12 | fmt.Println("Is A greater than or equal to B ? ", a >= b)
13 | fmt.Println("Is A less than or equal to B ? ", a <= b)
14 | }
15 |
--------------------------------------------------------------------------------
/scripts/operators/logical/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | a := 45
7 | b := "Something"
8 | fmt.Println(a > 40 && b == "Something")
9 | fmt.Println(a < 40 && b == "Something")
10 | fmt.Println(a < 40 || b == "Something")
11 | fmt.Println(a < 40 || b != "Something")
12 | fmt.Println(!(a < 40 || b != "Something"))
13 | }
14 |
--------------------------------------------------------------------------------
/scripts/packages/blank_import.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | _ "fmt"
5 | )
6 |
7 | func main() {
8 | }
9 |
--------------------------------------------------------------------------------
/scripts/packages/import.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | r "math/rand"
6 | )
7 |
8 | func main() {
9 | fmt.Println(r.Int())
10 | }
11 |
--------------------------------------------------------------------------------
/scripts/packages/mux_demo/go.mod:
--------------------------------------------------------------------------------
1 | module mux_demo
2 |
3 | go 1.17
4 |
5 | require github.com/gorilla/mux v1.8.0 // indirect
6 |
--------------------------------------------------------------------------------
/scripts/packages/mux_demo/go.sum:
--------------------------------------------------------------------------------
1 | github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
2 | github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
3 |
--------------------------------------------------------------------------------
/scripts/packages/mux_demo/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "net/http"
5 |
6 | "github.com/gorilla/mux"
7 | )
8 |
9 | func main() {
10 |
11 | router := mux.NewRouter()
12 |
13 | router.HandleFunc("/", Server)
14 |
15 | http.ListenAndServe(":8000", router)
16 | }
17 |
18 | func Server(writer http.ResponseWriter, request *http.Request) {
19 | writer.Write([]byte("Hello Mux!"))
20 | }
21 |
--------------------------------------------------------------------------------
/scripts/paths/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "os"
6 | "path"
7 | "path/filepath"
8 | "strings"
9 | //"path/filepath"
10 | )
11 |
12 | func main() {
13 | dir, err := os.Getwd()
14 | if err != nil {
15 | panic(err)
16 | }
17 | log.Println(dir)
18 | s := filepath.Base("math/")
19 | log.Println(s)
20 | m, _ := os.Stat(s)
21 | log.Println(os.FileInfo(m).Name())
22 | //log.Println(filepath.IsAbs(s))
23 | //log.Println(filepath.Dir(s))
24 |
25 | k := "bit.go"
26 | //os.Chdir("math/")
27 | p, _ := filepath.Abs(k)
28 | log.Println(strings.TrimSuffix(k, path.Ext(k)))
29 | log.Println(path.Ext(k))
30 |
31 | if t, err := os.Stat(p); os.IsNotExist(err) {
32 | log.Println("No, " + p + " does not exists")
33 | } else {
34 | log.Println(t.IsDir())
35 | log.Println("Yes, " + p + " exists")
36 | }
37 |
38 | currentDirectory, err := os.Getwd()
39 | if err != nil {
40 | log.Fatal(err)
41 | }
42 | iterate(currentDirectory)
43 |
44 | // Read Text from a file
45 | //txt, _ := os.ReadFile(p)
46 | //log.Println(string(txt))
47 | var files []string
48 |
49 | root := "../"
50 | err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
51 | dir_name := filepath.Base(root)
52 | if info.IsDir() == true && info.Name() != dir_name {
53 | return filepath.SkipDir
54 | } else {
55 | files = append(files, path)
56 | return nil
57 | }
58 | })
59 | if err != nil {
60 | panic(err)
61 | }
62 | for _, file := range files {
63 | log.Println(file)
64 | }
65 | }
66 |
67 | func iterate(path string) {
68 | count := 0
69 | filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
70 | if err != nil {
71 | log.Fatalf(err.Error())
72 | }
73 | count += 1
74 | var f string
75 | if info.IsDir() {
76 | f = "Directory"
77 | } else {
78 | f = "File"
79 | }
80 | log.Printf("%s Name: %s\n", f, info.Name())
81 | return nil
82 | })
83 | log.Println(count)
84 | }
85 |
--------------------------------------------------------------------------------
/scripts/paths/rel_abs.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "os"
6 | "path/filepath"
7 | )
8 |
9 | func main() {
10 |
11 | dir, err := os.Getwd()
12 | if err != nil {
13 | panic(err)
14 | }
15 | log.Println(dir)
16 | s := filepath.Base("math/")
17 | k := "/"
18 | log.Println(filepath.IsAbs(k))
19 |
20 | log.Println(filepath.Base(dir))
21 |
22 | // return true if the pattern matches with the path
23 | log.Println(filepath.Match("paths*", filepath.Base(dir)))
24 |
25 | // get the absolute path of the provided path
26 | s, _ = filepath.Abs("operators/arithmetic/")
27 | log.Println(s)
28 | log.Println(dir)
29 |
30 | // get the relative path between the base and target directory
31 | log.Println(filepath.Rel(s, dir))
32 |
33 | // join the two path strings as one path
34 | log.Println(filepath.Join("golang", "files"))
35 | log.Println(filepath.Join(s, "/files", "//read"))
36 | }
37 |
--------------------------------------------------------------------------------
/scripts/paths/script.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "os"
6 | "path"
7 | "path/filepath"
8 | "strings"
9 | )
10 |
11 | func main() {
12 |
13 | // get the working directory
14 | dir, err := os.Getwd()
15 | if err != nil {
16 | panic(err)
17 | }
18 | log.Println(dir)
19 |
20 | // get the user home directory of the user
21 | dir, err = os.UserHomeDir()
22 | if err != nil {
23 | panic(err)
24 | }
25 | log.Println(dir)
26 |
27 | // get the base name of the path
28 | s := filepath.Base("math/")
29 | log.Println(s)
30 |
31 | // Get the file info for a given path
32 | m, _ := os.Stat(s)
33 | log.Println(os.FileInfo(m).Name())
34 |
35 | // return true if the provided path is absolute
36 | log.Println(filepath.IsAbs(s))
37 |
38 | // get the paretn directory of the path
39 | log.Println(filepath.Dir(s))
40 |
41 | k := "bit.go"
42 | //os.Chdir("math/")
43 | p, _ := filepath.Abs(k)
44 |
45 | // teim the string before the suffix from the end
46 | log.Println(strings.TrimSuffix(k, path.Ext(k)))
47 |
48 | // get the extension of the path
49 | log.Println(path.Ext(k))
50 |
51 | // check if the path exists or not
52 | if t, err := os.Stat(p); os.IsNotExist(err) {
53 | log.Println("No, " + p + " does not exists")
54 | } else {
55 | log.Println(t.IsDir())
56 | log.Println("Yes, " + p + " exists")
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/scripts/paths/walk.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "io/fs"
5 | "log"
6 | "path/filepath"
7 | )
8 |
9 | func main() {
10 |
11 | dir_path := "."
12 | walkfunc := iterate_files_walk
13 | walkdirfunc := iterate_files_walkdir
14 | err := filepath.WalkDir(dir_path, walkdirfunc)
15 | if err != nil {
16 | panic(err)
17 | }
18 | err = filepath.Walk(dir_path, walkfunc)
19 | if err != nil {
20 | panic(err)
21 | }
22 |
23 | }
24 |
25 | func iterate_files_walkdir(path string, info fs.DirEntry, err error) error {
26 | var f string
27 | if info.IsDir() {
28 | f = "Directory"
29 | } else {
30 | f = "File"
31 | }
32 | log.Println(f + " : " + info.Name())
33 |
34 | if err != nil {
35 | return err
36 | } else {
37 | return nil
38 | }
39 | }
40 |
41 | func iterate_files_walk(path string, info fs.FileInfo, err error) error {
42 | var f string
43 | if info.IsDir() {
44 | f = "Directory"
45 | } else {
46 | f = "File"
47 | }
48 | log.Println(f + " : " + info.Name())
49 | if err != nil {
50 | return err
51 | } else {
52 | return nil
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/scripts/paths/walk_anonymous.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "io/fs"
5 | "log"
6 | "os"
7 | "path/filepath"
8 | )
9 |
10 | func main() {
11 |
12 | var files []string
13 | var dirs []string
14 |
15 | root := "math/"
16 | // walk funciton with paramter as os.FileInfo
17 | err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
18 | dir_name := filepath.Base(root)
19 |
20 | // skip the path if it is a directory and also the nested directory
21 | if info.IsDir() == true && info.Name() != dir_name {
22 | return filepath.SkipDir
23 | } else {
24 | files = append(files, path)
25 | return nil
26 | }
27 | })
28 | if err != nil {
29 | panic(err)
30 | }
31 | log.Println("Files : ")
32 | for _, file := range files {
33 | log.Println(file)
34 | }
35 |
36 | err = filepath.WalkDir(root, func(path string, info fs.DirEntry, err error) error {
37 | dir_name := filepath.Base(root)
38 |
39 | // add the path if the path is a directory
40 | if info.IsDir() == true && info.Name() != dir_name {
41 | dirs = append(dirs, path)
42 | } else {
43 | // add the path to the files slice
44 | files = append(files, path)
45 | }
46 | if err != nil {
47 | return err
48 | } else {
49 | return nil
50 | }
51 | })
52 | if err != nil {
53 | panic(err)
54 | }
55 | log.Println("Files : ")
56 | for _, file := range files {
57 | log.Println(file)
58 | }
59 | log.Println("Dirs: ")
60 | for _, dir := range dirs {
61 | log.Println(dir)
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/scripts/pointers/pointer.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func swap(x *int, y *int) {
6 | temp := *x
7 | *x = *y
8 | *y = temp
9 | }
10 |
11 | type Book struct {
12 | pages int
13 | genre string
14 | title string
15 | }
16 |
17 | func main() {
18 |
19 | // pointer declaration
20 | var ptr *int
21 | fmt.Println(ptr)
22 |
23 | // accessing memory address of variable with &
24 | n := 34
25 | var a_pointer *int = &n
26 | fmt.Println(a_pointer)
27 |
28 | // de-referncing pointers with *
29 | m := *a_pointer
30 | fmt.Println(m)
31 |
32 | //pass by reference to a function
33 | x := 3
34 | y := 6
35 | k := &x
36 | p := &y
37 | fmt.Printf("Before swapping : x = %d and y = %d.\n", x, y)
38 | swap(k, p)
39 | fmt.Printf("After swapping : x = %d and y = %d.\n", x, y)
40 |
41 | // pointer to a struct instance
42 | new_book := Book{120, "fiction", "Harry Potter"}
43 | fmt.Println(new_book)
44 | fmt.Printf("Type of new_book -> %T\n", new_book)
45 | book_ptr := &new_book
46 | book_ptr.title = "Games of Thrones"
47 | fmt.Println(new_book)
48 | }
49 |
--------------------------------------------------------------------------------
/scripts/random-num/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | crypto_rand "crypto/rand"
5 | "fmt"
6 | "math/big"
7 | "math/rand"
8 | "time"
9 | )
10 |
11 | func Handle_error(err error) {
12 | if err != nil {
13 | panic(err)
14 | }
15 | }
16 |
17 | func main() {
18 | fmt.Println(rand.Int())
19 | rand_num := rand.Int()
20 | fmt.Printf("%T %d\n", rand_num, rand_num)
21 | // set the seed as the current tim in nano seconds
22 | // this will set the initial value of the RNG so that
23 | // each time a new sequence is generated based on the seed value
24 |
25 | // deprecated
26 | //rand.Seed(time.Now().UnixNano())
27 |
28 | r := rand.New(rand.NewSource(time.Now().UnixNano()))
29 | fmt.Println(r.Int())
30 | rand_num = r.Int()
31 | fmt.Printf("%T %d\n", rand_num, rand_num)
32 |
33 | num := r.Int()
34 | fmt.Println(num)
35 |
36 | rand_float32 := r.Float32()
37 | fmt.Println(rand_float32)
38 |
39 | rand_float64 := r.Float64()
40 | fmt.Println(rand_float64)
41 |
42 | rand_exp_float := r.ExpFloat64()
43 | fmt.Println(rand_exp_float)
44 |
45 | rand_norm_float := r.NormFloat64()
46 | fmt.Println(rand_norm_float)
47 |
48 | for i := 0; i < 5; i++ {
49 | rand_float := r.Float32()
50 | fmt.Println(rand_float)
51 | }
52 |
53 | for i := 0; i < 10; i++ {
54 | // generate a integer between 0 and 5
55 | dice_throw := r.Intn(6)
56 | // Move the Offset of 0
57 | fmt.Println(dice_throw + 1)
58 |
59 | }
60 |
61 | // Cryptographic random numbers
62 | var max *big.Int = big.NewInt(6)
63 | // big is a package for high precision arithmetic
64 | for i := 0; i < 10; i++ {
65 | crypt_rand_num, err := crypto_rand.Int(crypto_rand.Reader, max)
66 | Handle_error(err)
67 | // Move the Offset of 0 by adding 1
68 | crypt_num := crypt_rand_num.Add(crypt_rand_num, big.NewInt(1))
69 | fmt.Println(crypt_num)
70 | }
71 | prime, err := crypto_rand.Prime(crypto_rand.Reader, 8)
72 | Handle_error(err)
73 | fmt.Println(prime)
74 |
75 | rand_byte := make([]byte, 5)
76 | fmt.Println(rand_byte)
77 | _, err = r.Read(rand_byte)
78 | Handle_error(err)
79 | fmt.Println(rand_byte)
80 | fmt.Printf("%c \n", rand_byte)
81 |
82 | crypt_rand_byte := make([]byte, 5)
83 | fmt.Println(crypt_rand_byte)
84 | _, err = crypto_rand.Read(crypt_rand_byte)
85 | Handle_error(err)
86 | fmt.Println(crypt_rand_byte)
87 | fmt.Printf("%c \n", crypt_rand_byte)
88 |
89 | }
90 |
--------------------------------------------------------------------------------
/scripts/random-num/rand_source.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math/rand"
6 | "time"
7 | )
8 |
9 | func main() {
10 | source := rand.NewSource(time.Now().UnixNano())
11 | rand_source := rand.New(source)
12 | for i := 0; i < 5; i++ {
13 | rand_num := rand_source.Int()
14 | fmt.Println(rand_num)
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/scripts/random-num/shuffle.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math/rand"
6 | "time"
7 | )
8 |
9 | func main() {
10 | r := rand.New(rand.NewSource(time.Now().UnixNano()))
11 |
12 | fmt.Println(r.Perm(10))
13 | arr := []int{1, 2, 3, 4, 5, 6}
14 | fmt.Println("Before shuffle:", arr)
15 | r.Shuffle(len(arr), func(i, j int) {
16 | arr[i], arr[j] = arr[j], arr[i]
17 | })
18 | fmt.Println("After shuffle:", arr)
19 | r.Shuffle(len(arr), func(i, j int) {
20 | arr[i], arr[j] = arr[j], arr[i]
21 | })
22 | fmt.Println("After shuffle:", arr)
23 |
24 | //random characters
25 | for i := 0; i < 30; i++ {
26 | // Uppercase character
27 | random_byte := r.Intn(26) + 65
28 | fmt.Printf("character = %d : %c\n", random_byte, random_byte)
29 | // Lowercase character
30 | random_byte = r.Intn(26) + 97
31 | fmt.Printf("character = %d : %c\n", random_byte, random_byte)
32 | }
33 |
34 | //Random string
35 | randomLowerCase := make([]rune, 6)
36 | randomUpperCase := make([]rune, 6)
37 | fmt.Println(randomLowerCase)
38 | fmt.Println(randomUpperCase)
39 | for i := range randomLowerCase {
40 | randomLowerCase[i] = rune(r.Intn(26) + 97)
41 | randomUpperCase[i] = rune(r.Intn(26) + 65)
42 | }
43 | randomLowerCaseStr := string(randomLowerCase)
44 | randomUpperCaseStr := string(randomUpperCase)
45 | fmt.Println(randomLowerCase)
46 | fmt.Println(randomLowerCaseStr)
47 | fmt.Println(randomUpperCase)
48 | fmt.Println(randomUpperCaseStr)
49 |
50 | //Randomly shuffled alphabets
51 | letters := "abcdefghijklmnopqrstuvwxyz"
52 | shuffled := r.Perm(len(letters))
53 |
54 | result := make([]byte, len(letters))
55 | for i, randIndex := range shuffled {
56 | result[i] = letters[randIndex]
57 | }
58 |
59 | rand_str := string(result)
60 | fmt.Println(rand_str)
61 | fmt.Println(rand_str[:10])
62 | }
63 |
--------------------------------------------------------------------------------
/scripts/regex/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "os"
6 | "regexp"
7 | )
8 |
9 | func log_error(err error) {
10 | if err != nil {
11 | log.Fatal(err)
12 | }
13 | }
14 |
15 | func main() {
16 |
17 | str := "gophers of the goland"
18 | is_matching, err := regexp.MatchString("go", str)
19 | log_error(err)
20 | log.Println(is_matching)
21 | file_content, err := os.ReadFile("temp.txt")
22 | log_error(err)
23 | is_matching, err = regexp.Match(`.*memory`, file_content)
24 | log_error(err)
25 | log.Println(is_matching)
26 | is_matching, err = regexp.Match(`text `, file_content)
27 | log_error(err)
28 | log.Println(is_matching)
29 |
30 | exp, err := regexp.Compile(`\b\d{5}(?:[-\s]\d{4})?\b`)
31 | log_error(err)
32 | pincode_file, err := os.ReadFile("pincode.txt")
33 | log_error(err)
34 | match := exp.FindAll(pincode_file, -1)
35 | matches := exp.FindAllString(string(pincode_file), -1)
36 | log.Println(match)
37 | log.Println(matches)
38 |
39 | match_indexes := exp.FindAllIndex(pincode_file, -1)
40 | match_index := exp.FindIndex(pincode_file)
41 | log.Println(match_indexes)
42 | log.Printf("%T\n", match_indexes)
43 | log.Println(match_index)
44 | if len(match_index) > 0 {
45 | log.Printf("%s\n", pincode_file[match_index[0]:match_index[1]])
46 | }
47 | log.Printf("%T\n", match_index)
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/scripts/regex/pincode.txt:
--------------------------------------------------------------------------------
1 | Pincode: 12345-1234
2 | City, 40084
3 | State 123
4 |
--------------------------------------------------------------------------------
/scripts/regex/replace.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "regexp"
6 | )
7 |
8 | func main() {
9 |
10 | str := "Gophy gophers go in the golang grounds"
11 | exp := regexp.MustCompile(`Go|go`)
12 | log.Println("Original: ", str)
13 | replaced_str := exp.ReplaceAllString(str, "to")
14 | log.Println("Replaced: ", replaced_str)
15 |
16 | exp2 := regexp.MustCompile(`(Go|go)|(phers)|(rounds)`)
17 | log.Println(exp2.ReplaceAllString(str, "hop"))
18 | log.Println(exp2.ReplaceAllString(str, "$1"))
19 | log.Println(exp2.ReplaceAllString(str, "$2"))
20 | log.Println(exp2.ReplaceAllString(str, "$3"))
21 | log.Println(exp2.ReplaceAllString(str, "$1$2"))
22 | str = "Gophy gophers go in the golang cophers grounds"
23 | log.Println(exp2.ReplaceAllString(str, "$1$3"))
24 |
25 | log.Println(exp2.ReplaceAllLiteralString(str, "$1"))
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/scripts/regex/submatch.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "log"
5 | "os"
6 | "regexp"
7 | )
8 |
9 | func log_error(err error) {
10 | if err != nil {
11 | log.Fatal(err)
12 | }
13 | }
14 |
15 | func main() {
16 |
17 | str := "abe21@def.com is the mail address of 8th user with id 124"
18 | //exp := regexp.MustCompile(`([a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,}:\d+)|(email|mail)|(\d{1,3})`)
19 | exp := regexp.MustCompile(
20 | `([a-zA-Z]+(\d*)[a-zA-Z]*@[a-zA-Z]+(\d*)[a-zA-Z]*\.[a-z|A-Z]{2,})` +
21 | `|(mail|email)` +
22 | `|(\d{1,3})`,
23 | )
24 |
25 | match := exp.FindStringSubmatch(str)
26 | match_index := exp.FindStringSubmatchIndex(str)
27 | match_indexes := exp.FindAllStringSubmatchIndex(str, -1)
28 | log.Println(match)
29 | log.Println(match_index)
30 | log.Println(match_indexes)
31 | matches := exp.FindAllStringSubmatch(str, -1)
32 | log.Println(matches)
33 |
34 | email_file, err := os.ReadFile("subtext.txt")
35 | log_error(err)
36 | mail_match := exp.FindSubmatch(email_file)
37 | log.Printf("%T\n", mail_match)
38 | log.Printf("%s\n", mail_match)
39 | mail_matches := exp.FindAllSubmatch(email_file, -1)
40 | //log.Println(mail_matches)
41 | log.Printf("%T\n", mail_matches)
42 | log.Printf("%s\n", mail_matches)
43 | }
44 |
--------------------------------------------------------------------------------
/scripts/regex/subtext.txt:
--------------------------------------------------------------------------------
1 | abc21@def.com is the mail address of user id 1234
2 | The email address abe2def.com is of user name abc
3 | a2be.@def.com
4 | Email address: abe@de2f.com, User id: 45
5 | johndoe@example.com
6 | jane.doe123@example.com
7 | janedoe@example.co.uk
8 | john123@example.org
9 | janedoe456@example.net
10 |
--------------------------------------------------------------------------------
/scripts/regex/temp.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "regexp"
6 | )
7 |
8 | func main() {
9 |
10 | exp := regexp.MustCompile(`[a-zA-Z]*(\d*)[a-zA-Z]*@[a-zA-Z]*(\d*)[a-zA-Z]+\.[a-z|A-Z]{2,}`)
11 | str := "abc@def.com ab1e@def.com abe2@def.com a21be@def.com abe@de2f.com"
12 | matches := exp.FindAllStringSubmatch(str, -1)
13 | fmt.Println(matches)
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/scripts/regex/temp.txt:
--------------------------------------------------------------------------------
1 | One of the gophers used a slice,
2 | the other one used a arrays.
3 | Some gophers were idle in the memory.
4 |
--------------------------------------------------------------------------------
/scripts/slices/slices.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | //basic slice declaration
7 | var marks []int
8 | fmt.Println(marks)
9 |
10 | // declare and initialize using slice literal
11 | var frameworks = []string{"Django", "Laravel", "Flask", "Rails"}
12 | fmt.Println(frameworks)
13 |
14 | //using make function
15 | var langs = make([]string, 3, 5)
16 | langs[0], langs[1], langs[2] = "Python", "Go", "Javascript"
17 | fmt.Println(langs)
18 | fmt.Printf("Length = %d \nCapacity = %d\n", len(langs), cap(langs))
19 | langs = append(langs, "Java", "Kotlin", "PHP")
20 | fmt.Println(langs)
21 | fmt.Printf("Length = %d \nCapacity = %d\n", len(langs), cap(langs))
22 |
23 | // using new function
24 | langs2 := new([3]string)[0:2]
25 |
26 | langs2[0], langs2[1] = "Python", "Go"
27 | fmt.Println(langs2)
28 | fmt.Printf("Length = %d \nCapacity = %d\n", len(langs2), cap(langs2))
29 | langs2 = append(langs2, "Java", "Kotlin", "PHP")
30 | fmt.Println(langs2)
31 | fmt.Printf("Length = %d \nCapacity = %d\n", len(langs2), cap(langs2))
32 |
33 | // append function to add elements in slice
34 | var percentages = []float64{78.8, 85.7, 94.4, 79.8}
35 | fmt.Println(percentages)
36 | percentages = append(percentages, 60.5, 75.6)
37 | fmt.Println(percentages)
38 |
39 | // delete an elements
40 | marklist := []int{80, 85, 90, 75, 60}
41 | fmt.Println(marklist)
42 | var index int
43 | fmt.Printf("Enter the index to be deleted: ")
44 | fmt.Scan(&index)
45 | elem := marklist[index]
46 | marklist = append(marklist[:index], marklist[index+1:]...)
47 | fmt.Printf("The element %d was deleted.\n", elem)
48 | fmt.Println(marklist)
49 |
50 | // Using index slicing
51 | scores := []int{80, 85, 90, 75, 60, 56, 83}
52 | fmt.Println(scores)
53 | fmt.Println("From index 2 to 4", scores[2:5])
54 | fmt.Println("From index 0 to 2", scores[:3])
55 | fmt.Println("From index 3 to 6", scores[3:])
56 |
57 | // Modifying elements in slices
58 | word := []byte{'f', 'u', 'z', 'z', 'y'}
59 | fmt.Printf("%s\n", word)
60 | word[0] = 'b'
61 | word[len(word)-1] = 'z'
62 | fmt.Printf("%s\n", word)
63 |
64 | // three statement for loop in slices
65 | code := [7]rune{'g', 'o', 'l', 'a', 'n', 'g'}
66 | for i := 0; i < len(code); i++ {
67 | fmt.Printf("%c\n", code[i])
68 | }
69 |
70 | // using range based for loop
71 | for _, s := range scores[1:4] {
72 | fmt.Println(s)
73 | }
74 |
75 | start, i, end := 2, 2, 5
76 | modes := []string{"normal", "command", "insert", "visual", "select", "replace"}
77 | for range scores[start:end] {
78 | fmt.Printf("Element at index %d = %s \n", i, modes[i])
79 | i++
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/scripts/strings/comparison.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "strings"
6 | )
7 |
8 | func main() {
9 |
10 | s1 := "gopher"
11 | s2 := "Gopher"
12 | s3 := "gopher"
13 |
14 | isEqual := s1 == s2
15 |
16 | //"gopher" is not same as "Gopher" and hence `false`
17 | fmt.Printf("S1 and S2 are Equal? %t \n", isEqual)
18 | fmt.Println(s1 == s2)
19 |
20 | // "gopher" is not equal to "Gopher" and hence `true`
21 | fmt.Println(s1 != s2)
22 |
23 | // "Gopher" comes first lexicographically than "gopher" so return true
24 | // G -> 71 in ASCII and g -> 103
25 | fmt.Println(s2 < s3)
26 | fmt.Println(s2 <= s3)
27 |
28 | // "Gopher" is not greater than "gopher" as `G` comes first in ASCII table
29 | // So G value is less than g i.e. 71 > 103 which is false
30 | fmt.Println(s2 > s3)
31 | fmt.Println(s2 >= s3)
32 |
33 | fmt.Println(strings.Compare(s1, s2))
34 | fmt.Println(strings.Compare(s1, s3))
35 | fmt.Println(strings.Compare(s2, s3))
36 |
37 | fmt.Println(strings.EqualFold(s1, s2))
38 | fmt.Println(strings.EqualFold(s1, s3))
39 | fmt.Println(strings.EqualFold(s2, s3))
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/scripts/strings/concatenate.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "strings"
7 | )
8 |
9 | func main() {
10 |
11 | // Using + operator
12 | s1 := "Go"
13 | s2 := "Programming"
14 | s3 := "30"
15 |
16 | s := s1 + s2 + s3
17 | fmt.Println(s)
18 |
19 | // Using += operator
20 |
21 | p := "Story"
22 | p += "Book"
23 | fmt.Println(p)
24 |
25 | // Using join function
26 |
27 | q := []string{"meetgor.com", "tags", "golang", "string"}
28 | r := strings.Join(q, "/")
29 | fmt.Println(r)
30 |
31 | // Using Sprintf function
32 |
33 | name := "peter"
34 | domain := "telecom"
35 | service := "ceo"
36 |
37 | email := fmt.Sprintf("%s.%s@%s.com", service, name, domain)
38 | fmt.Println(email)
39 |
40 | // Using Builder function
41 |
42 | c := []string{"j", "a", "v", "a"}
43 | var builder strings.Builder
44 | for _, item := range c {
45 | builder.WriteString(item)
46 | }
47 | fmt.Println("builder = ", builder.String())
48 | b := []byte{'s', 'c', 'r', 'i', 'p', 't'}
49 | for _, item := range b {
50 | builder.WriteByte(item)
51 | }
52 | fmt.Println("builder = ", builder.String())
53 | builder.WriteRune('s')
54 | fmt.Println("builder = ", builder.String())
55 | fmt.Println("builder = ", builder)
56 |
57 | // Using bytes buffer method
58 |
59 | var buf bytes.Buffer
60 |
61 | for i := 0; i < 2; i++ {
62 | buf.WriteString("ja")
63 | }
64 | fmt.Println(buf.String())
65 |
66 | buf.WriteByte('r')
67 |
68 | fmt.Println(buf.String())
69 |
70 | k := []rune{'s', 'c', 'r', 'i', 'p', 't'}
71 | for _, item := range k {
72 | buf.WriteRune(item)
73 | }
74 | fmt.Println(buf.String())
75 | fmt.Println(buf)
76 |
77 | buff := make([]byte, 0, 0)
78 | buff.WriteByte('s')
79 | buff.WriteByte('p')
80 | buff.off = 1
81 | fmt.Println(buff)
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/scripts/strings/go.mod:
--------------------------------------------------------------------------------
1 | module utility.go
2 |
3 | go 1.18
4 |
5 | require golang.org/x/text v0.3.7 // indirect
6 |
--------------------------------------------------------------------------------
/scripts/strings/go.sum:
--------------------------------------------------------------------------------
1 | golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
2 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
3 |
--------------------------------------------------------------------------------
/scripts/strings/utility.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "strings"
6 |
7 | "golang.org/x/text/cases"
8 | "golang.org/x/text/language"
9 | )
10 |
11 | func main() {
12 | s1 := "Ubuntu 22"
13 | s2 := "meet"
14 | s3 := "IND"
15 |
16 | // ToLower method for converting string into Lower case
17 | fmt.Println(strings.ToLower(s1))
18 | fmt.Println(strings.ToLower(s2))
19 | fmt.Println(strings.ToLower(s3))
20 |
21 | // ToUpper method for converting string into Upper case
22 | fmt.Printf("\n")
23 | fmt.Println(strings.ToUpper(s1))
24 | fmt.Println(strings.ToUpper(s2))
25 | fmt.Println(strings.ToUpper(s3))
26 |
27 | // Title method for converting string into title case
28 | fmt.Printf("\n")
29 | cases := cases.Title(language.English)
30 | fmt.Println(cases.String(s1))
31 | fmt.Println(cases.String(s2))
32 | fmt.Println(cases.String(s3))
33 |
34 | str := "javascript"
35 | substr := "script"
36 | s := "python"
37 |
38 | // Contains method for finding substring in the string
39 | fmt.Println(strings.Contains(str, substr))
40 | fmt.Println(strings.Contains(str, s))
41 |
42 | // ContainsAny method for finding characters in the string
43 | fmt.Println(strings.ContainsAny(str, "joke"))
44 | fmt.Println(strings.ContainsAny(str, "xyz"))
45 | fmt.Println(strings.ContainsAny(str, ""))
46 |
47 | // Split method for splitting string into slice of string
48 | link := "meetgor.com/blog/golang/strings"
49 | fmt.Println(strings.Split(link, "/"))
50 | fmt.Println(strings.SplitAfter(link, "/"))
51 |
52 | // SplitAfter method for splitting string into slice of string with the pattern
53 | data := "200kms50kms120kms"
54 | fmt.Println(strings.Split(data, "kms"))
55 | fmt.Println(strings.SplitAfter(data, "kms"))
56 |
57 | // Repeat method for creating strings with given string and integer
58 | pattern := "OK"
59 | fmt.Println(strings.Repeat(pattern, 3))
60 |
61 | // Fields method for extracting string from the given string with white space as delimiters
62 | text := "Python is a prgramming language. Go is not"
63 | text_data := strings.Fields(text)
64 | fmt.Println(text_data)
65 | for _, d := range text_data {
66 | fmt.Println("data = ", d)
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/scripts/structs/constructor.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type Repository struct {
6 | name string
7 | file_count int
8 | }
9 |
10 | func New_Repository(name string, file_count int) *Repository {
11 | file_count++
12 | name = "Test"
13 | return &Repository{name, file_count}
14 | }
15 |
16 | func main() {
17 | blog := *New_Repository("", 0)
18 | fmt.Println(blog)
19 | }
20 |
--------------------------------------------------------------------------------
/scripts/structs/methods.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type Mail struct {
6 | sender string
7 | subject string
8 | sent bool
9 | word_count int
10 | }
11 |
12 | func (m Mail) check_spam() bool {
13 | if m.subject == "" {
14 | return true
15 | } else {
16 | return false
17 | }
18 | }
19 |
20 | func (m Mail) print_spam(spam bool) {
21 | if spam {
22 | fmt.Println("Spam!!")
23 | } else {
24 | fmt.Println("Safe!!")
25 | }
26 | }
27 |
28 | func main() {
29 | mail_one := *new(Mail)
30 | fmt.Printf("Mail one: ")
31 | is_mail_1_spam := mail_one.check_spam()
32 | mail_one.print_spam(is_mail_1_spam)
33 |
34 | mail_two := Mail{"xyz@xyz.com", "Golang Structs", true, 100}
35 | fmt.Printf("Mail two: ")
36 | is_mail_2_spam := mail_two.check_spam()
37 | mail_two.print_spam(is_mail_2_spam)
38 | }
39 |
--------------------------------------------------------------------------------
/scripts/structs/struct.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type Article struct {
6 | title string
7 | is_published bool
8 | words int
9 | }
10 |
11 | func main() {
12 | golang := Article{"Golang Intro", true, 2000}
13 | fmt.Println(golang)
14 |
15 | vim := Article{title: "Vim: Keymapping", is_published: false}
16 | fmt.Println(vim)
17 |
18 | django := *new(Article)
19 | fmt.Println(django)
20 |
21 | django.title = "Django View and URLs"
22 | django.words = 3500
23 | django.is_published = true
24 | fmt.Println(django)
25 | }
26 |
--------------------------------------------------------------------------------
/scripts/variables/bool.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | // Default value of bool is false
7 | var power bool
8 | fmt.Println(power)
9 |
10 | // %t is the placeholder for bool
11 | const result = true
12 | fmt.Printf("The statement is %t", result)
13 | }
14 |
--------------------------------------------------------------------------------
/scripts/variables/byte.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main() {
8 | // byte is alias for uint8
9 | var s byte = 't'
10 | fmt.Println(s)
11 |
12 | // %c is the placeholder for character
13 | const c byte = 't'
14 | fmt.Printf("Character = %c \nInteger value = %d\n", c, c)
15 | }
16 |
--------------------------------------------------------------------------------
/scripts/variables/complex.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | var percent = 30.738
7 | var f = 4.545
8 |
9 | // complex is used to store real and imaginary data
10 | var comp1 = complex(f, percent)
11 | var comp2 = complex(percent, f)
12 | fmt.Println(comp1 - comp2)
13 | }
14 |
--------------------------------------------------------------------------------
/scripts/variables/float.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main() {
8 |
9 | // default type of decimal numbers is float64
10 | const percent = 30.5
11 | fmt.Println(percent+50)
12 | fmt.Printf("type = %T\n", percent)
13 |
14 | // optionally we can assign float32 for less precission than float64
15 | const percentage float32 = 46.34
16 | fmt.Println(percentage - 3.555)
17 | fmt.Printf("type = %T\n", percentage)
18 | }
19 |
--------------------------------------------------------------------------------
/scripts/variables/int.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 |
7 | // by default a int type is dependent on computer architecture
8 | // it can be either int64 or int32
9 | var likes int = 140
10 | fmt.Println(likes)
11 | fmt.Printf("type = %T\n",likes)
12 |
13 | //The below code will give error as limit overflow for int8
14 | //var age int8 = 140
15 | //fmt.Println("Age = ",age)
16 | }
17 |
--------------------------------------------------------------------------------
/scripts/variables/max_value_int.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main(){
8 | var min_uint = 0
9 | var max_uint8 uint8 = ^uint8(0)
10 | var max_uint16 uint16 = ^uint16(0)
11 | var max_uint32 uint32 = ^uint32(0)
12 | var max_uint64 uint64 = ^uint64(0)
13 |
14 | var max_int8 int8 = int8(max_uint8>>1)
15 | var min_int8 int8 = -max_int8 - 1
16 | var max_int16 int16 = int16(max_uint16>>1)
17 | var min_int16 int16 = -max_int16 - 1
18 | var max_int32 int32 = int32(max_uint32>>1)
19 | var min_int32 int32 = -max_int32 - 1
20 | var max_int64 int64 = int64(max_uint64>>1)
21 | var min_int64 int64 = -max_int64 - 1
22 |
23 | fmt.Println("uint8 -> ", min_uint, " to ", max_uint8)
24 | fmt.Println("uint16 -> ", min_uint, " to ", max_uint16)
25 | fmt.Println("uint32 -> ", min_uint, " to ", max_uint32)
26 | fmt.Println("uint64 -> ", min_uint, " to ", max_uint64)
27 | fmt.Println("")
28 | fmt.Println("int8 -> ", min_int8, " to ", max_int8)
29 | fmt.Println("int16 -> ", min_int16, " to ", max_int16)
30 | fmt.Println("int32 -> ", min_int32, " to ", max_int32)
31 | fmt.Println("int64 -> ", min_int64, " to ", max_int64)
32 | }
33 |
--------------------------------------------------------------------------------
/scripts/variables/multivar.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 |
7 | var (
8 | x int8 = 100
9 | y byte = '#'
10 | z = "daysofcode"
11 | )
12 |
13 | fmt.Printf(" x = %d \n y = %c \n z = %s \n",x,y,z)
14 |
15 | var pi, e, G float32 = 3.141, 2.718, 6.67e-11
16 | var start, end byte = 65, 90
17 | fmt.Println(pi, e, G)
18 | fmt.Printf("%c %c\n",start, end)
19 | }
20 |
--------------------------------------------------------------------------------
/scripts/variables/rune.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main() {
8 | var smiley_emoji = '\u263A'
9 | fmt.Printf("Smiley Emoji --> %c \n", smiley_emoji)
10 | }
11 |
--------------------------------------------------------------------------------
/scripts/variables/string.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main() {
8 | var code = "12AB34CD"
9 | fmt.Println(code[6])
10 | fmt.Printf("2nd Character in string = %c\n\n", code[4])
11 |
12 | var statement = `This is the first line
13 | The next line
14 | The last line`
15 |
16 | fmt.Println(statement)
17 | }
18 |
--------------------------------------------------------------------------------
/scripts/variables/walrus.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | place := "school"
7 | fmt.Println(place)
8 |
9 | x, y, z := "foo", 32, true
10 | fmt.Println(x, y, z)
11 | fmt.Printf("%T %T %T", x, y, z)
12 | }
13 |
--------------------------------------------------------------------------------
/web/README.md:
--------------------------------------------------------------------------------
1 | ## Web Development with Golang
2 |
3 |
--------------------------------------------------------------------------------
/web/methods/delete/simple.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | "net/http"
7 | )
8 |
9 | func main() {
10 | baseURL := "https://reqres.in"
11 | userID := 2
12 | apiURL := fmt.Sprintf("%s/api/users/%d", baseURL, userID)
13 |
14 | req, err := http.NewRequest(http.MethodDelete, apiURL, nil)
15 | if err != nil {
16 | fmt.Println(err)
17 | return
18 | }
19 |
20 | client := &http.Client{}
21 | resp, err := client.Do(req)
22 | if err != nil {
23 | fmt.Println(err)
24 | return
25 | }
26 |
27 | fmt.Println("Response Status:", resp.Status)
28 | respBody, err := io.ReadAll(resp.Body)
29 | if err != nil {
30 | fmt.Println(err)
31 | return
32 | }
33 | fmt.Println("Response Body:", string(respBody))
34 | }
35 |
--------------------------------------------------------------------------------
/web/methods/get/body.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | "net/http"
7 | )
8 |
9 | func main() {
10 | reqURL := "https://httpbin.org/html"
11 | resp, err := http.Get(reqURL)
12 | if err != nil {
13 | panic(err)
14 | }
15 | // close the body object before returning of the function
16 | // this is to avoid the memory leak
17 | defer resp.Body.Close()
18 |
19 | // stream the data from the response body only once
20 | // it is not buffered in the memory
21 | body, err := io.ReadAll(resp.Body)
22 | if err != nil {
23 | panic(err)
24 | }
25 | fmt.Println(string(body))
26 | }
27 |
--------------------------------------------------------------------------------
/web/methods/get/chunk.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "net/http"
7 | )
8 |
9 | func main() {
10 | reqURL := "https://httpbin.org/html"
11 | resp, err := http.Get(reqURL)
12 | if err != nil {
13 | panic(err)
14 | }
15 | defer resp.Body.Close()
16 |
17 | // create a empty buffer
18 | buf := new(bytes.Buffer)
19 |
20 | // create a chunk buffer of a fixed size
21 | chunk := make([]byte, 1024)
22 |
23 | for {
24 | // Read into buffer
25 | n, err := resp.Body.Read(chunk)
26 | if err != nil {
27 | break
28 | }
29 | // append the chunk to the buffer
30 | buf.Write(chunk[:n])
31 | fmt.Printf("%s\n", chunk[:n])
32 | }
33 |
34 | // entire body stored in bytes
35 | fmt.Println(buf.String())
36 | }
37 |
--------------------------------------------------------------------------------
/web/methods/get/decoder.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "net/http"
7 | )
8 |
9 | /*
10 | GET
11 | https://dummyjson.com/products/1
12 |
13 | {"id":1,"title":"iPhone 9","description":"An apple mobile which is nothing like apple","price":549,"discountPercentage":12.96,"rating":4.69,"stock":94,"brand":"Apple","category":"smartphones","thumbnail":"https://cdn.dummyjson.com/product-images/1/thumbnail.jpg","images":["https://cdn.dummyjson.com/product-images/1/1.jpg","https://cdn.dummyjson.com/product-images/1/2.jpg","https://cdn.dummyjson.com/product-images/1/3.jpg","https://cdn.dummyjson.com/product-images/1/4.jpg","https://cdn.dummyjson.com/product-images/1/thumbnail.jpg"]}
14 | */
15 |
16 | // we define a struct for the json data
17 | // we can only include the fields that we want
18 | type Product struct {
19 | ID int `json:"id"`
20 | Title string `json:"title"`
21 | Description string `json:"description"`
22 | Price float64 `json:"price"`
23 | DiscountPercentage float64 `json:"discountPercentage"`
24 | Rating float64 `json:"rating"`
25 | Stock int `json:"stock"`
26 | Brand string `json:"brand"`
27 | Category string `json:"category"`
28 | Thumbnail string `json:"thumbnail,omitempty"`
29 | Images []string `json:"-"`
30 | /*
31 | // we can skip the fields that we don't want
32 | Thumbnail string `json:"thumbnail"`
33 | Images []string `json:"images"`
34 | // or include omitempty flag
35 | // the omitempty flag will skip the field if it is empty
36 | Thumbnail string `json:"thumbnail,omitempty"`
37 | Images []string `json:"images,omitempty"`
38 | */
39 | }
40 |
41 | func main() {
42 | reqURL := "https://dummyjson.com/products/1"
43 | resp, err := http.Get(reqURL)
44 | if err != nil {
45 | panic(err)
46 | }
47 | defer resp.Body.Close()
48 |
49 | var data Product
50 | decoder := json.NewDecoder(resp.Body)
51 | err = decoder.Decode(&data)
52 | if err != nil {
53 | panic(err)
54 | }
55 |
56 | fmt.Println(data)
57 | //we can now access the data with the struct
58 | fmt.Println(data.Title)
59 | }
60 |
--------------------------------------------------------------------------------
/web/methods/get/header.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | "net/http"
7 | )
8 |
9 | func main() {
10 | req, err := http.NewRequest(http.MethodGet, "https://api.github.com/users/mr-destructive", nil)
11 | if err != nil {
12 | panic(err)
13 | }
14 | // if the below line is commented, it works fine, but for real authentication-based APIs/services, it won't work
15 | //req.Header.Add("Authorization", "token YOUR_TOKEN")
16 | resp, err := http.DefaultClient.Do(req)
17 | if err != nil {
18 | panic(err)
19 | }
20 | defer resp.Body.Close()
21 | body, err := io.ReadAll(resp.Body)
22 | if err != nil {
23 | panic(err)
24 | }
25 | fmt.Println(string(body))
26 | }
27 |
--------------------------------------------------------------------------------
/web/methods/get/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | )
7 |
8 | func main() {
9 | reqURL := "https://www.google.com"
10 | resp, err := http.Get(reqURL)
11 | if err != nil {
12 | panic(err)
13 | }
14 | fmt.Println(resp)
15 | fmt.Println(resp.Status)
16 | fmt.Println("Status Code:", resp.StatusCode)
17 | }
18 |
--------------------------------------------------------------------------------
/web/methods/get/newreq.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | )
7 |
8 | func main() {
9 | reqURL := "https://www.google.com"
10 | req, err := http.NewRequest(http.MethodGet, reqURL, nil)
11 | if err != nil {
12 | panic(err)
13 | }
14 | resp, err := http.DefaultClient.Do(req)
15 | if err != nil {
16 | panic(err)
17 | }
18 | fmt.Println(resp)
19 | }
20 |
--------------------------------------------------------------------------------
/web/methods/get/unmarshal.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | )
9 |
10 | /*
11 | GET
12 | https://dummyjson.com/products/1
13 |
14 | {"id":1,"title":"iPhone 9","description":"An apple mobile which is nothing like apple","price":549,"discountPercentage":12.96,"rating":4.69,"stock":94,"brand":"Apple","category":"smartphones","thumbnail":"https://cdn.dummyjson.com/product-images/1/thumbnail.jpg","images":["https://cdn.dummyjson.com/product-images/1/1.jpg","https://cdn.dummyjson.com/product-images/1/2.jpg","https://cdn.dummyjson.com/product-images/1/3.jpg","https://cdn.dummyjson.com/product-images/1/4.jpg","https://cdn.dummyjson.com/product-images/1/thumbnail.jpg"]}
15 | */
16 |
17 | // we define a struct for the json data
18 | // we can only include the fields that we want
19 | type Product struct {
20 | ID int `json:"id"`
21 | Title string `json:"title"`
22 | Description string `json:"description"`
23 | Price float64 `json:"price"`
24 | DiscountPercentage float64 `json:"discountPercentage"`
25 | Rating float64 `json:"rating"`
26 | Stock int `json:"stock"`
27 | Brand string `json:"brand"`
28 | Category string `json:"category"`
29 | /*
30 | // we can skip the fields that we don't want
31 | Thumbnail string `json:"thumbnail"`
32 | Images []string `json:"images"`
33 | // or include omitempty flag
34 | // the omitempty flag will skip the field if it is empty
35 | Thumbnail string `json:"thumbnail,omitempty"`
36 | Images []string `json:"images,omitempty"`
37 | */
38 | }
39 |
40 | func main() {
41 | reqURL := "https://dummyjson.com/products/1"
42 | resp, err := http.Get(reqURL)
43 | if err != nil {
44 | panic(err)
45 | }
46 | defer resp.Body.Close()
47 |
48 | body, err := io.ReadAll(resp.Body)
49 | if err != nil {
50 | panic(err)
51 | }
52 |
53 | var data Product
54 | if err := json.Unmarshal(body, &data); err != nil {
55 | panic(err)
56 | }
57 |
58 | fmt.Println(data)
59 | //we can now access the data with the struct
60 | fmt.Println(data.Title)
61 | }
62 |
--------------------------------------------------------------------------------
/web/methods/patch/json-patch/add.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | "strings"
9 | )
10 |
11 | type Document struct {
12 | ID int `json:"id"`
13 | Data interface{} `json:"data"`
14 | }
15 |
16 | type JSONPatch struct {
17 | Op string `json:"op"`
18 | Path string `json:"path"`
19 | From string `json:"from,omitempty"`
20 | Value string `json:"value,omitempty"`
21 | }
22 |
23 | func main() {
24 | baseURL := "https://dummy-json-patch.netlify.app/.netlify/functions"
25 | docId := 4
26 | apiURL := fmt.Sprintf("%s/documents/?id=%d", baseURL, docId)
27 |
28 | jsonPatchData := []JSONPatch{
29 | {
30 | Op: "add",
31 | Path: "/name",
32 | Value: "dummy",
33 | },
34 | }
35 |
36 | jsonPatchBytes, err := json.Marshal(jsonPatchData)
37 | if err != nil {
38 | panic(err)
39 | }
40 | jsonPatchBody := string(jsonPatchBytes)
41 |
42 | /*
43 | jsonPatchBody := `[
44 | {
45 | "op": "add",
46 | "path": "/name",
47 | "value": "dummy"
48 | }
49 | ]`
50 | */
51 |
52 | req, err := http.NewRequest("PATCH", apiURL, strings.NewReader(jsonPatchBody))
53 | req.Header.Set("Content-Type", "application/json-patch+json")
54 |
55 | client := &http.Client{}
56 | resp, err := client.Do(req)
57 | if err != nil {
58 | panic(err)
59 | }
60 | defer resp.Body.Close()
61 |
62 | var updatedDoc Document
63 |
64 | resBody, err := io.ReadAll(resp.Body)
65 | fmt.Println(string(resBody))
66 | if err != nil {
67 | panic(err)
68 | }
69 | err = json.Unmarshal(resBody, &updatedDoc)
70 | if err != nil {
71 | panic(err)
72 | }
73 |
74 | fmt.Println("Updated/Patched Document", updatedDoc)
75 | fmt.Println("id:", updatedDoc.ID)
76 | fmt.Println("document:", updatedDoc.Data)
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/web/methods/patch/json-patch/copy.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | "strings"
9 | )
10 |
11 | type Document struct {
12 | ID int `json:"id"`
13 | Data interface{} `json:"data"`
14 | }
15 |
16 | type JSONPatch struct {
17 | Op string `json:"op"`
18 | Path string `json:"path"`
19 | From string `json:"from,omitempty"`
20 | Value string `json:"value,omitempty"`
21 | }
22 |
23 | func main() {
24 | baseURL := "https://dummy-json-patch.netlify.app/.netlify/functions"
25 | docId := 4
26 | apiURL := fmt.Sprintf("%s/documents/?id=%d", baseURL, docId)
27 |
28 | jsonPatchData := []JSONPatch{
29 | {
30 | Op: "copy",
31 | Path: "/name",
32 | },
33 | }
34 |
35 | jsonPatchBytes, err := json.Marshal(jsonPatchData)
36 | if err != nil {
37 | panic(err)
38 | }
39 | jsonPatchBody := string(jsonPatchBytes)
40 | /*
41 | jsonPatchBody := `[
42 | {
43 | "op": "copy",
44 | "from": "/name",
45 | "path": "/new_name"
46 | }
47 | ]`
48 | */
49 |
50 | req, err := http.NewRequest("PATCH", apiURL, strings.NewReader(jsonPatchBody))
51 | req.Header.Set("Content-Type", "application/json-patch+json")
52 |
53 | client := &http.Client{}
54 | resp, err := client.Do(req)
55 | if err != nil {
56 | panic(err)
57 | }
58 | defer resp.Body.Close()
59 |
60 | var updatedDoc Document
61 |
62 | resBody, err := io.ReadAll(resp.Body)
63 | fmt.Println(string(resBody))
64 | if err != nil {
65 | panic(err)
66 | }
67 | err = json.Unmarshal(resBody, &updatedDoc)
68 | if err != nil {
69 | panic(err)
70 | }
71 |
72 | fmt.Println("Updated/Patched Document", updatedDoc)
73 | fmt.Println("id:", updatedDoc.ID)
74 | fmt.Println("document:", updatedDoc.Data)
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/web/methods/patch/json-patch/move.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | "strings"
9 | )
10 |
11 | type Document struct {
12 | ID int `json:"id"`
13 | Data interface{} `json:"data"`
14 | }
15 |
16 | type JSONPatch struct {
17 | Op string `json:"op"`
18 | Path string `json:"path"`
19 | From string `json:"from,omitempty"`
20 | Value string `json:"value,omitempty"`
21 | }
22 |
23 | func main() {
24 | baseURL := "https://dummy-json-patch.netlify.app/.netlify/functions"
25 | docId := 4
26 | apiURL := fmt.Sprintf("%s/documents/?id=%d", baseURL, docId)
27 |
28 | jsonPatchData := []JSONPatch{
29 | {
30 | Op: "move",
31 | Path: "/name",
32 | From: "/user/description",
33 | },
34 | }
35 |
36 | jsonPatchBytes, err := json.Marshal(jsonPatchData)
37 | if err != nil {
38 | panic(err)
39 | }
40 | jsonPatchBody := string(jsonPatchBytes)
41 | /*
42 | jsonPatchBody := `[
43 | {
44 | "op": "move",
45 | "from": "/name",
46 | "path": "/user/description"
47 | }
48 | ]`
49 | */
50 |
51 | req, err := http.NewRequest("PATCH", apiURL, strings.NewReader(jsonPatchBody))
52 | req.Header.Set("Content-Type", "application/json-patch+json")
53 |
54 | client := &http.Client{}
55 | resp, err := client.Do(req)
56 | if err != nil {
57 | panic(err)
58 | }
59 | defer resp.Body.Close()
60 |
61 | var updatedDoc Document
62 |
63 | resBody, err := io.ReadAll(resp.Body)
64 | fmt.Println(string(resBody))
65 | if err != nil {
66 | panic(err)
67 | }
68 | err = json.Unmarshal(resBody, &updatedDoc)
69 | if err != nil {
70 | panic(err)
71 | }
72 |
73 | fmt.Println("Updated/Patched Document", updatedDoc)
74 | fmt.Println("id:", updatedDoc.ID)
75 | fmt.Println("document:", updatedDoc.Data)
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/web/methods/patch/json-patch/remove.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | "strings"
9 | )
10 |
11 | type Document struct {
12 | ID int `json:"id"`
13 | Data interface{} `json:"data"`
14 | }
15 |
16 | type JSONPatch struct {
17 | Op string `json:"op"`
18 | Path string `json:"path"`
19 | From string `json:"from,omitempty"`
20 | Value string `json:"value,omitempty"`
21 | }
22 |
23 | func main() {
24 | baseURL := "https://dummy-json-patch.netlify.app/.netlify/functions"
25 | docId := 4
26 | apiURL := fmt.Sprintf("%s/documents/?id=%d", baseURL, docId)
27 |
28 | jsonPatchData := []JSONPatch{
29 | {
30 | Op: "remove",
31 | Path: "/name",
32 | },
33 | }
34 | jsonPatchBytes, err := json.Marshal(jsonPatchData)
35 | if err != nil {
36 | panic(err)
37 | }
38 | jsonPatchBody := string(jsonPatchBytes)
39 | /*
40 | jsonPatchBody := `[
41 | {
42 | "op": "remove",
43 | "path": "/name"
44 | }
45 | ]`
46 | */
47 |
48 | req, err := http.NewRequest("PATCH", apiURL, strings.NewReader(jsonPatchBody))
49 | req.Header.Set("Content-Type", "application/json-patch+json")
50 |
51 | client := &http.Client{}
52 | resp, err := client.Do(req)
53 | if err != nil {
54 | panic(err)
55 | }
56 | defer resp.Body.Close()
57 |
58 | var updatedDoc Document
59 |
60 | resBody, err := io.ReadAll(resp.Body)
61 | fmt.Println(string(resBody))
62 | if err != nil {
63 | panic(err)
64 | }
65 | err = json.Unmarshal(resBody, &updatedDoc)
66 | if err != nil {
67 | panic(err)
68 | }
69 |
70 | fmt.Println("Updated/Patched Document", updatedDoc)
71 | fmt.Println("id:", updatedDoc.ID)
72 | fmt.Println("document:", updatedDoc.Data)
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/web/methods/patch/json-patch/test.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | "strings"
9 | )
10 |
11 | type Document struct {
12 | ID int `json:"id"`
13 | Data interface{} `json:"data"`
14 | }
15 |
16 | type JSONPatch struct {
17 | Op string `json:"op"`
18 | Path string `json:"path"`
19 | From string `json:"from,omitempty"`
20 | Value string `json:"value,omitempty"`
21 | }
22 |
23 | func main() {
24 | baseURL := "https://dummy-json-patch.netlify.app/.netlify/functions"
25 | docId := 4
26 | apiURL := fmt.Sprintf("%s/documents/?id=%d", baseURL, docId)
27 |
28 | jsonPatchData := []JSONPatch{
29 | {
30 | Op: "test",
31 | Path: "/new_name",
32 | Value: "dummy",
33 | },
34 | {
35 | Op: "add",
36 | Path: "/user/id",
37 | Value: "123",
38 | },
39 | }
40 | jsonPatchBytes, err := json.Marshal(jsonPatchData)
41 | if err != nil {
42 | panic(err)
43 | }
44 | jsonPatchBody := string(jsonPatchBytes)
45 | /*
46 | jsonPatchBody := `[
47 | {
48 | "op": "test",
49 | "path": "/new_name",
50 | "value": "dummy"
51 | },
52 | {
53 | "op": "add",
54 | "path": "/user/id",
55 | "value": 123
56 | }
57 | ]`
58 | */
59 |
60 | req, err := http.NewRequest("PATCH", apiURL, strings.NewReader(jsonPatchBody))
61 | req.Header.Set("Content-Type", "application/json-patch+json")
62 |
63 | client := &http.Client{}
64 | resp, err := client.Do(req)
65 | if err != nil {
66 | panic(err)
67 | }
68 | defer resp.Body.Close()
69 |
70 | var updatedDoc Document
71 |
72 | resBody, err := io.ReadAll(resp.Body)
73 | fmt.Println(string(resBody))
74 | if err != nil {
75 | panic(err)
76 | }
77 | err = json.Unmarshal(resBody, &updatedDoc)
78 | if err != nil {
79 | panic(err)
80 | }
81 |
82 | fmt.Println("Updated/Patched Document", updatedDoc)
83 | fmt.Println("id:", updatedDoc.ID)
84 | fmt.Println("document:", updatedDoc.Data)
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/web/methods/patch/json_merge_patch.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | "strings"
9 | )
10 |
11 | type User struct {
12 | ID int `json:"id,omitempty"`
13 | Name string `json:"name,omitempty"`
14 | Email string `json:"email,omitempty"`
15 | Bio string `json:"bio,omitempty"`
16 | Roles string `json:"roles,omitempt"`
17 | }
18 |
19 | func main() {
20 | apiURL := "https://dummy-json-patch.netlify.app/.netlify/functions/users/?id=2"
21 |
22 | userObj := User{
23 | Name: "dummy",
24 | Roles: "dummy role",
25 | }
26 |
27 | var jsonPatchBody []byte
28 | jsonPatchBody, err := json.Marshal(userObj)
29 | if err != nil {
30 | panic(err)
31 | }
32 | fmt.Println("Request Body:", string(jsonPatchBody))
33 |
34 | //jsonPatchBody := `{
35 | // "name": "dummy",
36 | // "roles": "new dummy role"
37 | //}`
38 |
39 | req, err := http.NewRequest("PATCH", apiURL, strings.NewReader(string(jsonPatchBody)))
40 | req.Header.Set("Content-Type", "application/merge-patch+json")
41 |
42 | client := &http.Client{}
43 | resp, err := client.Do(req)
44 | if err != nil {
45 | panic(err)
46 | }
47 | defer resp.Body.Close()
48 |
49 | var user User
50 |
51 | resBody, err := io.ReadAll(resp.Body)
52 | fmt.Println(string(resBody))
53 | if err != nil {
54 | panic(err)
55 | }
56 | err = json.Unmarshal(resBody, &user)
57 | if err != nil {
58 | panic(err)
59 | }
60 |
61 | fmt.Println("Updated/Patched User", user)
62 | fmt.Println("id:", user.ID)
63 | fmt.Println("name:", user.Name)
64 | fmt.Println("bio:", user.Bio)
65 | fmt.Println("email:", user.Email)
66 | fmt.Println("roles:", user.Roles)
67 | }
68 |
--------------------------------------------------------------------------------
/web/methods/patch/json_patch.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | "strings"
9 | )
10 |
11 | type User struct {
12 | ID int `json:"id,omitempty"`
13 | Name string `json:"name"`
14 | Email string `json:"email"`
15 | Roles string `json:"Roles"`
16 | }
17 |
18 | func main() {
19 | apiURL := "https://dummy-json-patch.netlify.app/.netlify/functions/users/?id=2"
20 |
21 | jsonPatchBody := `[
22 | {
23 | "op": "replace",
24 | "path": "/name",
25 | "value": "some dummy name"
26 | }
27 | ]`
28 |
29 | req, err := http.NewRequest("PATCH", apiURL, strings.NewReader(jsonPatchBody))
30 | req.Header.Set("Content-Type", "application/json-patch+json")
31 |
32 | client := &http.Client{}
33 | resp, err := client.Do(req)
34 | if err != nil {
35 | panic(err)
36 | }
37 | defer resp.Body.Close()
38 |
39 | var user User
40 |
41 | resBody, err := io.ReadAll(resp.Body)
42 | fmt.Println(string(resBody))
43 | if err != nil {
44 | panic(err)
45 | }
46 | err = json.Unmarshal(resBody, &user)
47 | if err != nil {
48 | panic(err)
49 | }
50 |
51 | fmt.Println("Updated/Patched User", user)
52 | fmt.Println("id:", user.ID)
53 | fmt.Println("name:", user.Name)
54 | fmt.Println("email:", user.Email)
55 | fmt.Println("roles:", user.Roles)
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/web/methods/patch/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io"
7 | "log"
8 | "net/http"
9 | "strings"
10 | )
11 |
12 | type Post struct {
13 | ID int `json:"id"`
14 | Title string `json:"title"`
15 | Body string `json:"body"`
16 | UserId int `json:"userId"`
17 | }
18 |
19 | func main() {
20 | URL := "https://jsonplaceholder.typicode.com/posts/4"
21 | req1, err := http.Get(URL)
22 | if err != nil {
23 | log.Fatal(err)
24 | }
25 | fmt.Println(req1.Status)
26 | if req1.StatusCode != http.StatusOK {
27 | log.Fatal("Status code is not 200")
28 | }
29 | defer req1.Body.Close()
30 | body, err := io.ReadAll(req1.Body)
31 | if err != nil {
32 | log.Fatal(err)
33 | }
34 | fmt.Println("Existing body:", string(body))
35 |
36 | reqBody := `{"body": "new body"}`
37 | fmt.Println("New body:", reqBody)
38 |
39 | req, err := http.NewRequest("PATCH", URL, strings.NewReader(reqBody))
40 | if err != nil {
41 | log.Fatal(err)
42 | }
43 | req.Header.Set("Content-Type", "application/json; charset=utf-8")
44 |
45 | client := &http.Client{}
46 | resp, err := client.Do(req)
47 | if err != nil {
48 | log.Fatal(err)
49 | }
50 | defer resp.Body.Close()
51 | fmt.Println("Response status code:", resp.StatusCode)
52 | fmt.Println("Response Status:", resp.Status)
53 | var updatedPost Post
54 |
55 | respBody, err := io.ReadAll(resp.Body)
56 | if err != nil {
57 | log.Fatal(err)
58 | }
59 |
60 | err = json.Unmarshal(respBody, &updatedPost)
61 | if err != nil {
62 | log.Fatal(err)
63 | }
64 |
65 | fmt.Println(updatedPost)
66 | fmt.Println("title:", updatedPost.Title)
67 | fmt.Println("body:", updatedPost.Body)
68 | fmt.Println("id:", updatedPost.ID)
69 | fmt.Println("user id:", updatedPost.UserId)
70 | }
71 |
--------------------------------------------------------------------------------
/web/methods/patch/marshal.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io"
7 | "log"
8 | "net/http"
9 | "strings"
10 | )
11 |
12 | type Post struct {
13 | ID int `json:"id,omitempty"`
14 | Title string `json:"title,omitempty"`
15 | Body string `json:"body,omitempty"`
16 | UserId int `json:"userId,omitempty"`
17 | }
18 |
19 | func main() {
20 |
21 | // define URL to hit the API
22 | baseURL := "https://jsonplaceholder.typicode.com"
23 | postId := 4
24 | postURL := fmt.Sprintf("%s/posts/%d", baseURL, postId)
25 |
26 | userObj := Post{
27 | Body: "New Body",
28 | }
29 |
30 | var reqBody []byte
31 | reqBody, err := json.Marshal(userObj)
32 | if err != nil {
33 | log.Fatal(err)
34 | }
35 |
36 | fmt.Println("New body:", string(reqBody))
37 |
38 | // send a new request, with the `PATCH` method, url and the body
39 | req, err := http.NewRequest("PATCH", postURL, strings.NewReader(string(reqBody)))
40 | if err != nil {
41 | log.Fatal(err)
42 | }
43 | // set the header content type to json
44 | req.Header.Set("Content-Type", "application/json")
45 |
46 | client := &http.Client{}
47 | resp, err := client.Do(req)
48 | if err != nil {
49 | log.Fatal(err)
50 | }
51 | defer resp.Body.Close()
52 | fmt.Println("Response status code:", resp.StatusCode)
53 | fmt.Println("Response Status:", resp.Status)
54 |
55 | var updatedPost Post
56 |
57 | respBody, err := io.ReadAll(resp.Body)
58 | if err != nil {
59 | log.Fatal(err)
60 | }
61 |
62 | // convert the response json bytes to Post object in golang
63 | err = json.Unmarshal(respBody, &updatedPost)
64 | if err != nil {
65 | log.Fatal(err)
66 | }
67 |
68 | fmt.Println(updatedPost)
69 | fmt.Println(updatedPost.Title)
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/web/methods/patch/put.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | "strings"
9 | )
10 |
11 | type User struct {
12 | ID int `json:"id,omitempty"`
13 | Name string `json:"name,omitempty"`
14 | Email string `json:"email,omitempty"`
15 | Bio string `json:"bio,omitempty"`
16 | Roles string `json:"roles,omitempt"`
17 | }
18 |
19 | func main() {
20 | apiURL := "https://dummy-json-patch.netlify.app/.netlify/functions/users/?id=2"
21 |
22 | userObj := User{
23 | Name: "not a dummy name",
24 | Roles: "not a dummy role",
25 | }
26 |
27 | var jsonPatchBody []byte
28 | jsonPatchBody, err := json.Marshal(userObj)
29 | if err != nil {
30 | panic(err)
31 | }
32 | fmt.Println("Request Body:", string(jsonPatchBody))
33 |
34 | //jsonPatchBody := `{
35 | // "name": "dummy",
36 | // "roles": "new dummy role"
37 | //}`
38 |
39 | req, err := http.NewRequest("PUT", apiURL, strings.NewReader(string(jsonPatchBody)))
40 | req.Header.Set("Content-Type", "application/merge-patch+json")
41 |
42 | client := &http.Client{}
43 | resp, err := client.Do(req)
44 | if err != nil {
45 | panic(err)
46 | }
47 | defer resp.Body.Close()
48 |
49 | var user User
50 |
51 | resBody, err := io.ReadAll(resp.Body)
52 | fmt.Println(string(resBody))
53 | if err != nil {
54 | panic(err)
55 | }
56 | err = json.Unmarshal(resBody, &user)
57 | if err != nil {
58 | panic(err)
59 | }
60 |
61 | fmt.Println("Updated/Patched User", user)
62 | fmt.Println("id:", user.ID)
63 | fmt.Println("name:", user.Name)
64 | fmt.Println("bio:", user.Bio)
65 | fmt.Println("email:", user.Email)
66 | fmt.Println("roles:", user.Roles)
67 | }
68 |
--------------------------------------------------------------------------------
/web/methods/post/file.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "fmt"
7 | "io"
8 | "mime/multipart"
9 | "net/http"
10 | "os"
11 | )
12 |
13 | type ResponseFile struct {
14 | Files map[string]string `json:"files"`
15 | }
16 |
17 | func main() {
18 | // Define the URL of the API endpoint
19 | apiURL := "http://postman-echo.com/post"
20 | // other dummy apis for uplaod
21 | // https://api.escuelajs.co/api/v1/files/upload
22 | // https://v2.convertapi.com/upload
23 |
24 | // file to uplaod
25 | fileName := "sample.csv"
26 |
27 | // Open the CSV file
28 | file, err := os.Open(fileName)
29 | if err != nil {
30 | panic(err)
31 | }
32 | defer file.Close()
33 |
34 | // Create a new multipart writer
35 | body := &bytes.Buffer{}
36 | writer := multipart.NewWriter(body)
37 |
38 | // Add the file to the multipart form
39 | part, err := writer.CreateFormFile("csvFile", fileName)
40 | if err != nil {
41 | panic(err)
42 | }
43 | _, err = io.Copy(part, file)
44 | if err != nil {
45 | panic(err)
46 | }
47 |
48 | contentType := writer.FormDataContentType()
49 | fmt.Println(contentType)
50 | // Close the multipart writer
51 | writer.Close()
52 | fmt.Println(body.String())
53 |
54 | // Make a POST request with the multipart form
55 | resp, err := http.Post(apiURL, contentType, body)
56 | if err != nil {
57 | panic(err)
58 | }
59 | defer resp.Body.Close()
60 |
61 | // Print response status code
62 | fmt.Println("Status Code:", resp.StatusCode)
63 |
64 | // Print response body
65 | respBody, err := io.ReadAll(resp.Body)
66 | if err != nil {
67 | panic(err)
68 | }
69 | token := ResponseFile{}
70 | json.Unmarshal(respBody, &token)
71 | fmt.Println(token)
72 | fmt.Println(token.Files[fileName])
73 | }
74 |
--------------------------------------------------------------------------------
/web/methods/post/file_2.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "encoding/base64"
6 | "encoding/json"
7 | "fmt"
8 | "io"
9 | "mime/multipart"
10 | "net/http"
11 | "os"
12 | "strings"
13 | )
14 |
15 | type ResponseFile struct {
16 | Files map[string]string `json:"files"`
17 | }
18 |
19 | func main() {
20 | // Define the URL of the API endpoint
21 | apiURL := "http://postman-echo.com/post"
22 | // other dummy apis for uplaod
23 | // https://api.escuelajs.co/api/v1/files/upload
24 | // https://v2.convertapi.com/upload
25 |
26 | // file to uplaod
27 | fileName := "sample.csv"
28 |
29 | // Open the CSV file
30 | file, err := os.Open(fileName)
31 | if err != nil {
32 | panic(err)
33 | }
34 | defer file.Close()
35 |
36 | // Create a new multipart writer
37 | body := &bytes.Buffer{}
38 | writer := multipart.NewWriter(body)
39 |
40 | // Add the file to the multipart form
41 | part, err := writer.CreateFormFile("csvFile", fileName)
42 | if err != nil {
43 | panic(err)
44 | }
45 | _, err = io.Copy(part, file)
46 | if err != nil {
47 | panic(err)
48 | }
49 |
50 | contentType := writer.FormDataContentType()
51 | fmt.Println(contentType)
52 | // Close the multipart writer
53 | writer.Close()
54 | fmt.Println(body.String())
55 |
56 | // Make a POST request with the multipart form
57 | resp, err := http.Post(apiURL, contentType, body)
58 | if err != nil {
59 | panic(err)
60 | }
61 | defer resp.Body.Close()
62 |
63 | // Print response status code
64 | fmt.Println("Status Code:", resp.StatusCode)
65 |
66 | // Print response body
67 | respBody, err := io.ReadAll(resp.Body)
68 | if err != nil {
69 | panic(err)
70 | }
71 | token := ResponseFile{}
72 | json.Unmarshal(respBody, &token)
73 |
74 | fmt.Println(token)
75 | fmt.Println(token.Files[fileName])
76 |
77 | decodedFiles := make(map[string]string)
78 | for key, value := range token.Files {
79 | encodedVal := strings.Split(value, "base64,")[1]
80 | decodedContent, err := base64.StdEncoding.DecodeString(encodedVal)
81 | if err != nil {
82 | panic(err)
83 | }
84 | decodedFiles[key] = string(decodedContent)
85 | }
86 | fmt.Println(decodedFiles[fileName])
87 | }
88 |
--------------------------------------------------------------------------------
/web/methods/post/form-data.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | "net/url"
9 | "strings"
10 | )
11 |
12 | type ResponseLogin struct {
13 | Token string `json:"token"`
14 | }
15 |
16 | func main() {
17 | // Define the URL of the API endpoint
18 | apiURL := "https://reqres.in/api/login"
19 |
20 | // Define form data
21 | formData := url.Values{}
22 | formData.Set("email", "eve.holt@reqres.in")
23 | formData.Set("password", "cityslicka")
24 |
25 | // Encode the form data
26 | fmt.Println(formData.Encode())
27 | reqBody := strings.NewReader(formData.Encode())
28 | fmt.Println(reqBody)
29 |
30 | // Make a POST request with form data
31 | resp, err := http.Post(apiURL, "application/x-www-form-urlencoded", reqBody)
32 | if err != nil {
33 | panic(err) // Handle error
34 | }
35 | defer resp.Body.Close()
36 |
37 | // Print response status code
38 | fmt.Println("Status Code:", resp.StatusCode)
39 |
40 | // Print response body
41 | respBody, _ := io.ReadAll(resp.Body)
42 | token := ResponseLogin{}
43 | json.Unmarshal(respBody, &token)
44 | fmt.Println(token)
45 | }
46 |
--------------------------------------------------------------------------------
/web/methods/post/json.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "fmt"
7 | "io"
8 | "net/http"
9 | )
10 |
11 | /*
12 | POST Request when you have Go struct
13 | Need to convert the Golang struct object to JSON -> Marshal
14 | Marshal is converting Go specific data structure/types to JSON
15 | Load that string into a buffer / in-memeory
16 | Send the POST request with that buffer as body
17 |
18 | POST Request Response is in JSON format
19 | But it is a in-memory object
20 | Read the buffer into bytes
21 | Convert bytes into JSON -> Unmarshal
22 | Unmarshal is converting JSON into Go specific data structure
23 | */
24 |
25 | type User struct {
26 | Name string `json:"name"`
27 | Salary int `json:"salary"`
28 | Age string `json:"age"`
29 | ID int `json:"id,omitempty"`
30 | }
31 |
32 | type UserResponse struct {
33 | Status string `json:"status"`
34 | Data User `json:"data"`
35 | }
36 |
37 | func main() {
38 | user := User{
39 | Name: "Alice",
40 | Salary: 50000,
41 | Age: "25",
42 | }
43 | apiURL := "https://dummy.restapiexample.com/api/v1/create"
44 |
45 | // marshalling process
46 | // converting Go specific data structure/types to JSON
47 | bodyBytes, err := json.Marshal(user)
48 | if err != nil {
49 | panic(err)
50 | }
51 | fmt.Println(string(bodyBytes))
52 |
53 | // reading json into a buffer/in-memory
54 | body := bytes.NewBuffer(bodyBytes)
55 |
56 | // post request
57 | resp, err := http.Post(apiURL, "application/json", body)
58 | if err != nil {
59 | panic(err)
60 | }
61 | fmt.Println(resp.StatusCode)
62 | fmt.Println(resp)
63 | defer resp.Body.Close()
64 |
65 | // Read response body
66 | respBody, err := io.ReadAll(resp.Body)
67 | if err != nil {
68 | panic(err)
69 | }
70 |
71 | // unmarshalling process
72 | // converting JSON to Go specific data structure/types
73 | var userResponse UserResponse
74 | if err := json.Unmarshal(respBody, &userResponse); err != nil {
75 | panic(err)
76 | }
77 | fmt.Println(userResponse)
78 | fmt.Println(userResponse.Data)
79 |
80 | }
81 |
--------------------------------------------------------------------------------
/web/methods/post/newreq.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | )
7 |
8 | func main() {
9 | apiURL := "https://reqres.in/api/users"
10 |
11 | req, err := http.NewRequest(http.MethodPost, apiURL, nil)
12 | if err != nil {
13 | panic(err)
14 | }
15 | resp, err := http.DefaultClient.Do(req)
16 | if err != nil {
17 | panic(err)
18 | }
19 | fmt.Println(resp.StatusCode)
20 | fmt.Println(resp)
21 | defer resp.Body.Close()
22 | }
23 |
--------------------------------------------------------------------------------
/web/methods/post/post-req.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | "bytes"
7 | "encoding/json"
8 | )
9 |
10 | func main() {
11 | apiURL := "https://reqres.in/api/users"
12 | bodyMap := map[string]interface{}{
13 | "name": "morpheus",
14 | "job": "leader",
15 | }
16 |
17 | requestBody, err := json.Marshal(bodyMap)
18 | if err != nil {
19 | panic(err)
20 | }
21 | body := bytes.NewBuffer(requestBody)
22 |
23 | resp, err := http.Post(apiURL, "application/json", body)
24 | if err != nil {
25 | panic(err)
26 | }
27 | fmt.Println(resp.StatusCode)
28 | defer resp.Body.Close()
29 | }
30 |
--------------------------------------------------------------------------------
/web/methods/post/request-json.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "net/http"
7 | )
8 |
9 | /*
10 | POST Request when you have JSON string ready to send
11 | Load that string into a buffer / in-memeory
12 | Send the POST request with that buffer as body
13 | */
14 | func main() {
15 | // dummy api
16 | apiURL := "https://dummy.restapiexample.com/api/v1/create"
17 |
18 | // json data
19 | data := `{
20 | "name": "Alice",
21 | "job": "Teacher"
22 | }`
23 | body := bytes.NewBuffer([]byte(data))
24 |
25 | // POST request
26 | resp, err := http.Post(apiURL, "application/json", body)
27 | if err != nil {
28 | panic(err)
29 | }
30 | fmt.Println(resp.StatusCode)
31 | fmt.Println(resp)
32 | defer resp.Body.Close()
33 | }
34 |
--------------------------------------------------------------------------------
/web/methods/post/request-obj/encode.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "fmt"
7 | "net/http"
8 | )
9 |
10 | type User struct {
11 | Name string `json:"name"`
12 | Salary int `json:"salary"`
13 | Age int `json:"age"`
14 | }
15 |
16 | /*
17 | POST Request when you have a Go struct
18 | Need to convert the Golang struct object to JSON
19 | Read the JSON into a buffer / in-memeory
20 | Send the POST request with that buffer as body
21 | */
22 |
23 | func main() {
24 | user := User{
25 | Name: "Alice",
26 | Salary: 50000,
27 | Age: 25,
28 | }
29 | apiURL := "https://dummy.restapiexample.com/api/v1/create"
30 |
31 | // encoding process
32 | // converting Go specific data structure/types to JSON
33 | var buffer bytes.Buffer
34 | var encoder = json.NewEncoder(&buffer)
35 | err := encoder.Encode(user)
36 | if err != nil {
37 | panic(err)
38 | }
39 |
40 | //bodyBytes := buffer.Bytes()
41 | //fmt.Println(string(bodyBytes))
42 |
43 | //// reading json into a buffer/in-memory
44 | //body := bytes.NewBuffer(bodyBytes)
45 |
46 | // post request
47 | resp, err := http.Post(apiURL, "application/json", &buffer)
48 | if err != nil {
49 | panic(err)
50 | }
51 | fmt.Println(resp.StatusCode)
52 | fmt.Println(resp)
53 | defer resp.Body.Close()
54 | }
55 |
--------------------------------------------------------------------------------
/web/methods/post/request-obj/marshal.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "fmt"
7 | "net/http"
8 | )
9 |
10 | type User struct {
11 | Name string `json:"name"`
12 | Salary int `json:"salary"`
13 | Age int `json:"age"`
14 | }
15 |
16 | /*
17 | POST Request when you have a Go struct
18 | Need to convert the Golang struct object to JSON
19 | Read the JSON into a buffer / in-memeory
20 | Send the POST request with that buffer as body
21 | */
22 |
23 | func main() {
24 | user := User{
25 | Name: "Alice",
26 | Salary: 50000,
27 | Age: 25,
28 | }
29 | apiURL := "https://dummy.restapiexample.com/api/v1/create"
30 |
31 | // marshalling process
32 | // converting Go specific data structure/types to JSON
33 | bodyBytes, err := json.Marshal(user)
34 | if err != nil {
35 | panic(err)
36 | }
37 |
38 | fmt.Println(string(bodyBytes))
39 |
40 | // reading json into a buffer/in-memory
41 | body := bytes.NewBuffer(bodyBytes)
42 |
43 | // post request
44 | resp, err := http.Post(apiURL, "application/json", body)
45 | if err != nil {
46 | panic(err)
47 | }
48 | fmt.Println(resp.StatusCode)
49 | fmt.Println(resp)
50 | defer resp.Body.Close()
51 | }
52 |
--------------------------------------------------------------------------------
/web/methods/post/sample.csv:
--------------------------------------------------------------------------------
1 | User,City,Age,Country
2 | Alex Smith,Los Angeles,20,USA
3 | John Doe,New York,30,USA
4 | Jane Smith,Paris,25,France
5 | Bob Johnson,London,40,UK
6 |
--------------------------------------------------------------------------------
/web/methods/post/simple.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | )
7 |
8 | func main() {
9 | apiURL := "https://reqres.in/api/users"
10 | // dummy api
11 | // few other apis
12 | // https://dummyjson.com/posts
13 | // https://jsonplaceholder.typicode.com/posts
14 | // https://httpbin.org/post
15 | // https://postman-echo.com/post
16 |
17 | // POST request
18 | resp, err := http.Post(apiURL, "", nil)
19 | if err != nil {
20 | panic(err)
21 | }
22 | fmt.Println(resp.StatusCode)
23 | fmt.Println(resp)
24 | defer resp.Body.Close()
25 | }
26 |
--------------------------------------------------------------------------------
/web/methods/put/create.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | )
9 |
10 | func main() {
11 | apiURL := "https://dummy.restapiexample.com/api/v1/create"
12 |
13 | data := `{
14 | "name": "jim",
15 | "salary": "50000",
16 | "age": 25,
17 | }`
18 | body := bytes.NewBuffer([]byte(data))
19 |
20 | // POST request
21 | resp, err := http.Post(apiURL, "application/json", body)
22 | if err != nil {
23 | panic(err)
24 | }
25 | fmt.Println(resp.StatusCode)
26 | fmt.Println(resp)
27 | // read response body
28 | respBody, err := io.ReadAll(resp.Body)
29 | if err != nil {
30 | panic(err)
31 | }
32 | fmt.Println(string(respBody))
33 | defer resp.Body.Close()
34 | }
35 |
--------------------------------------------------------------------------------
/web/methods/put/json.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "fmt"
7 | "io"
8 | "net/http"
9 | )
10 |
11 | type User struct {
12 | Name string `json:"name"`
13 | Salary int `json:"salary"`
14 | Age string `json:"age"`
15 | ID int `json:"id,omitempty"`
16 | }
17 |
18 | type UserResponse struct {
19 | Status string `json:"status"`
20 | Message string `json:"message"`
21 | }
22 |
23 | func main() {
24 | user := User{
25 | Name: "Alice",
26 | Salary: 50000,
27 | Age: "25",
28 | }
29 | apiURL := "https://dummy.restapiexample.com/api/v1/update/11"
30 |
31 | // marshalling process
32 | // converting Go specific data structure/types to JSON
33 | bodyBytes, err := json.Marshal(user)
34 | if err != nil {
35 | panic(err)
36 | }
37 | fmt.Println(string(bodyBytes))
38 |
39 | // reading json into a buffer/in-memory
40 | body := bytes.NewBuffer(bodyBytes)
41 |
42 | // post request
43 | req, err := http.NewRequest(http.MethodPut, apiURL, body)
44 | if err != nil {
45 | panic(err)
46 | }
47 | resp, err := http.DefaultClient.Do(req)
48 | if err != nil {
49 | panic(err)
50 | }
51 | fmt.Println(resp.StatusCode)
52 | if resp.StatusCode == 429 {
53 | fmt.Println("too many requests")
54 | return
55 | }
56 | respBody, err := io.ReadAll(resp.Body)
57 | if err != nil {
58 | panic(err)
59 | }
60 | fmt.Println(string(respBody))
61 | defer resp.Body.Close()
62 |
63 | // unmarshalling process
64 | // converting JSON to Go specific data structure/types
65 | var userResponse UserResponse
66 | if err := json.Unmarshal(respBody, &userResponse); err != nil {
67 | panic(err)
68 | }
69 | fmt.Println(userResponse)
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/web/methods/put/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | "net/http"
7 | )
8 |
9 | func main() {
10 | apiURL := "https://reqres.in/api/users/5"
11 |
12 | req, err := http.NewRequest(http.MethodPut, apiURL, nil)
13 | if err != nil {
14 | panic(err)
15 | }
16 | resp, err := http.DefaultClient.Do(req)
17 | if err != nil {
18 | panic(err)
19 | }
20 | fmt.Println(resp.StatusCode)
21 | respBody, err := io.ReadAll(resp.Body)
22 | if err != nil {
23 | panic(err)
24 | }
25 | fmt.Println(string(respBody))
26 |
27 | defer resp.Body.Close()
28 | }
29 |
--------------------------------------------------------------------------------
/web/methods/put/update.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | )
9 |
10 | func main() {
11 | apiURL := "https://dummy.restapiexample.com/api/v1/update/4334"
12 | data := `{
13 | "employee_name": "tim",
14 | "employee_salary": "50000",
15 | "employee_age": 25
16 | }`
17 | body := bytes.NewBuffer([]byte(data))
18 |
19 | req, err := http.NewRequest(http.MethodPut, apiURL, body)
20 | if err != nil {
21 | panic(err)
22 | }
23 | resp, err := http.DefaultClient.Do(req)
24 | if err != nil {
25 | panic(err)
26 | }
27 | fmt.Println(resp.StatusCode)
28 | respBody, err := io.ReadAll(resp.Body)
29 | if err != nil {
30 | panic(err)
31 | }
32 | fmt.Println(string(respBody))
33 |
34 | defer resp.Body.Close()
35 | }
36 |
--------------------------------------------------------------------------------
/web/url-parsing/db.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/url"
6 | )
7 |
8 | func main() {
9 | //postgres db url
10 | dbUrl, err := url.Parse("postgres://admin:pass1234@localhost:5432/mydb")
11 | if err != nil {
12 | panic(err)
13 | }
14 | fmt.Println(dbUrl)
15 | fmt.Println("Scheme/Protocol = ", dbUrl.Scheme)
16 | fmt.Println("User = ", dbUrl.User)
17 | //fmt.Println("User = ", dbUrl.User.String())
18 | fmt.Println("Username = ", dbUrl.User.Username())
19 | password, _ := dbUrl.User.Password()
20 | fmt.Println("Password = ", password)
21 | fmt.Println("Host = ", dbUrl.Host)
22 | fmt.Println("HostName = ", dbUrl.Hostname())
23 | fmt.Println("Port = ", dbUrl.Port())
24 | fmt.Println("DB Name = ", dbUrl.Path)
25 | }
26 |
--------------------------------------------------------------------------------
/web/url-parsing/fragments.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/url"
6 | )
7 |
8 | func main() {
9 | // url with fragments
10 | urlStr := "https://pkg.go.dev/math/rand#Norm Float64"
11 | parsedUrl, err := url.Parse(urlStr)
12 | if err != nil {
13 | panic(err)
14 | }
15 | fmt.Println(parsedUrl)
16 | fmt.Println(parsedUrl.Fragment)
17 | fmt.Println(parsedUrl.RawFragment)
18 | fmt.Println(parsedUrl.EscapedFragment())
19 | }
20 |
--------------------------------------------------------------------------------
/web/url-parsing/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/url"
6 | )
7 |
8 | func main() {
9 | // simple url
10 | urlString := "http://www.google.com"
11 | parsedUrl, err := url.Parse(urlString)
12 | if err != nil {
13 | panic(err)
14 | }
15 | fmt.Println(parsedUrl)
16 | fmt.Println("Schema/Protocol = ", parsedUrl.Scheme)
17 | fmt.Println("Host = ", parsedUrl.Host)
18 | fmt.Println("Path = ", parsedUrl.Path)
19 | }
20 |
--------------------------------------------------------------------------------
/web/url-parsing/manual_parsing.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "strings"
6 | )
7 |
8 | func main() {
9 | urlString := []string{"http://www.google.com",
10 | "http://www.google.com/about/",
11 | "http://www.google.com/about?q=hello",
12 | "http://www.google.com:8080/about?q=hello",
13 | "http://user:password@example.com:8080/path/to/resource?query=value#fragment",
14 | }
15 | for _, url := range urlString {
16 | hostStr := strings.Split(url, "//")[1]
17 | hostName := strings.Split(hostStr, "/")[0]
18 | fmt.Println(hostName)
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/web/url-parsing/path.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/url"
6 | "strings"
7 | )
8 |
9 | func main() {
10 |
11 | // url with multiple path
12 | url1 := "https://github.com/appwrite/console/issues/396"
13 | parsedUrl, err := url.Parse(url1)
14 | if err != nil {
15 | panic(err)
16 | }
17 | fmt.Println(parsedUrl)
18 | fmt.Println("Paths", parsedUrl.Path)
19 | paths := strings.Split(parsedUrl.Path, "/")
20 | for _, path := range paths {
21 | fmt.Println(path)
22 | }
23 |
24 | // url with subdomain
25 | url2 := "https://docs.mindsdb.com/what-is-mindsdb"
26 | parsedUrl, err = url.Parse(url2)
27 | if err != nil {
28 | panic(err)
29 | }
30 | fmt.Println(parsedUrl)
31 | fmt.Println("Host", parsedUrl.Host)
32 | }
33 |
--------------------------------------------------------------------------------
/web/url-parsing/query_params.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/url"
6 | )
7 |
8 | func main() {
9 | // a complex url with query params
10 | urlStr := "http://www.google.com/?q=hello+world&lang=en&q=gopher"
11 | parsedUrl, err := url.Parse(urlStr)
12 | if err != nil {
13 | panic(err)
14 | }
15 | fmt.Println(parsedUrl)
16 | fmt.Println(parsedUrl.Query())
17 | for k, v := range parsedUrl.Query() {
18 | fmt.Println("KEY:", k)
19 | for _, vv := range v {
20 | fmt.Println(vv)
21 | }
22 | }
23 |
24 | queryParams := parsedUrl.Query()
25 |
26 | // Get the value
27 | // will only give the first value
28 | fmt.Println(queryParams.Get("q"))
29 |
30 | // has value
31 | fmt.Println(queryParams.Has("q"))
32 |
33 | if queryParams.Has("lang") {
34 | fmt.Println(queryParams.Get("lang"))
35 | }
36 |
37 | //Add value to a key
38 | queryParams.Add("q", "ferris")
39 | fmt.Println(queryParams)
40 |
41 | // Encode the query params
42 | q := queryParams.Encode()
43 | fmt.Println(q)
44 |
45 | //Set the value
46 | queryParams.Set("q", "books")
47 | fmt.Println(queryParams)
48 |
49 | //Delete the value
50 | queryParams.Del("q")
51 | fmt.Println(queryParams)
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/web/url-parsing/str.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net/url"
6 | )
7 |
8 | func main() {
9 | // a complex url with query params
10 | urlStr := "http://www.google.com/?q=hello+world&lang=en&q=gopher"
11 | fmt.Println("URL:", urlStr)
12 | parsedUrl, err := url.Parse(urlStr)
13 | if err != nil {
14 | panic(err)
15 | }
16 | queryParams := parsedUrl.Query()
17 | queryParams.Add("name", "ferris")
18 |
19 | q := queryParams.Encode()
20 | fmt.Println(q)
21 | parsedUrl.RawQuery = q
22 | newUrl := parsedUrl.String()
23 | fmt.Println("New URL:", newUrl)
24 | }
25 |
--------------------------------------------------------------------------------