├── .gitignore
├── .vscode
└── launch.json
├── GetGoing
├── Advanced
│ ├── channels.go
│ ├── channelsBuff.go
│ ├── concurrency.go
│ └── lambda.go
├── Basics
│ ├── array.go
│ ├── controlstatements.go
│ ├── interfaces.go
│ ├── main.go
│ ├── pointers.go
│ └── structure.go
├── CRUD
│ ├── controller
│ │ ├── crud.go
│ │ ├── ping.go
│ │ └── routes.go
│ ├── go.mod
│ ├── go.sum
│ ├── main.go
│ ├── model
│ │ ├── connect.go
│ │ ├── create.go
│ │ └── reade.go
│ └── view
│ │ └── view.go
└── README.md
├── GoLangProgrammers
├── README.md
├── conditionals.go
├── constants.go
├── functions.go
├── go.mod
├── loops.go
├── main.go
├── operators.go
├── typeCasting.go
└── variables.go
├── GoRmGin
├── .gitignore
├── README.md
├── go.mod
├── go.sum
└── main.go
├── LICENSE
├── LetsGo
├── .vscode
│ └── settings.json
├── ReadMe.md
└── snippetbox
│ ├── .gitignore
│ ├── .vscode
│ └── settings.json
│ ├── ReadMe.md
│ ├── cmd
│ └── web
│ │ ├── context.go
│ │ ├── handlers.go
│ │ ├── helpers.go
│ │ ├── main.go
│ │ ├── middleware.go
│ │ ├── routes.go
│ │ └── templates.go
│ ├── docs
│ └── Schema-SnippetBox.sql
│ ├── go.mod
│ ├── go.sum
│ ├── internal
│ ├── models
│ │ ├── error.go
│ │ ├── snippets.go
│ │ └── users.go
│ └── validator
│ │ └── validator.go
│ └── ui
│ ├── html
│ ├── base.tmpl
│ ├── pages
│ │ ├── create.tmpl
│ │ ├── home.tmpl
│ │ ├── login.tmpl
│ │ ├── signup.tmpl
│ │ └── view.tmpl
│ └── partials
│ │ └── nav.tmpl
│ └── static
│ ├── css
│ └── main.css
│ ├── img
│ ├── favicon.ico
│ └── logo.png
│ └── js
│ └── main.js
├── MasterGoLang
├── Readme.md
├── Section 1
│ ├── Basic Strings
│ │ ├── 01-windows-path
│ │ │ └── main.go
│ │ ├── 02-print-json
│ │ │ └── main.go
│ │ ├── 03-raw-concat
│ │ │ └── main.go
│ │ ├── 04-count-the-chars
│ │ │ └── main.go
│ │ ├── 05-improved-banger
│ │ │ └── main.go
│ │ ├── 06-tolowercase
│ │ │ └── main.go
│ │ ├── 07-trim-it
│ │ │ └── main.go
│ │ └── 08-right-trim-it
│ │ │ └── main.go
│ ├── Command Line Arguments
│ │ ├── 01-count-arguments
│ │ │ └── main.go
│ │ ├── 03-print-your-name
│ │ │ └── main.go
│ │ ├── 04-greet-more-people
│ │ │ └── main.go
│ │ └── 05-greet-5-people
│ │ │ └── main.go
│ ├── Error Handling
│ │ ├── 05-movie-ratings
│ │ │ └── main.go
│ │ ├── 06-odd-even
│ │ │ └── main.go
│ │ ├── 07-leap-year
│ │ │ └── main.go
│ │ ├── 08-simplify-leap-year
│ │ │ └── main.go
│ │ └── 09-days-in-month
│ │ │ └── main.go
│ ├── IOTA
│ │ ├── 07-iota-months
│ │ │ └── main.go
│ │ ├── 08-iota-months-2
│ │ │ └── main.go
│ │ └── 09-iota-seasons
│ │ │ └── main.go
│ ├── If Statement
│ │ ├── 01-age-seasons
│ │ │ └── main.go
│ │ ├── 02-simplify-it
│ │ │ └── main.go
│ │ ├── 03-arg-count
│ │ │ └── main.go
│ │ └── 04-vowel-or-cons
│ │ │ └── main.go
│ ├── LOOP
│ │ ├── 01-dynamic-table
│ │ │ └── main.go
│ │ ├── 01-sum-the-numbers
│ │ │ └── main.go
│ │ ├── 02-math-tables
│ │ │ └── main.go
│ │ ├── 02-sum-the-numbers-verbose
│ │ │ └── main.go
│ │ ├── 03-sum-up-to-n
│ │ │ └── main.go
│ │ ├── 04-only-evens
│ │ │ └── main.go
│ │ ├── 05-break-up
│ │ │ └── main.go
│ │ └── 06-infinite-kill
│ │ │ └── main.go
│ ├── PRINTF
│ │ ├── 01-print-your-age
│ │ │ └── main.go
│ │ ├── 02-print-your-name-and-lastname
│ │ │ └── main.go
│ │ ├── 03-false-claims
│ │ │ └── main.go
│ │ ├── 04-print-the-temperature
│ │ │ └── main.go
│ │ ├── 05-double-quotes
│ │ │ └── main.go
│ │ ├── 06-print-the-type
│ │ │ └── main.go
│ │ ├── 07-print-the-type-2
│ │ │ └── main.go
│ │ ├── 08-print-the-type-3
│ │ │ └── main.go
│ │ ├── 09-print-the-type-4
│ │ │ └── main.go
│ │ └── 10-print-your-fullname
│ │ │ └── main.go
│ ├── Pass Me Challenges Source Code
│ │ ├── 01-challenge
│ │ │ └── main.go
│ │ └── 02-challenge
│ │ │ └── main.go
│ ├── Readme.md
│ ├── SWITCH
│ │ ├── 01-richter-scale
│ │ │ └── main.go
│ │ ├── 02-richter-scale-2
│ │ │ └── main.go
│ │ ├── 03-convert
│ │ │ └── main.go
│ │ ├── 04-string-manipulator
│ │ │ └── main.go
│ │ └── 05-days-in-month
│ │ │ └── main.go
│ ├── Type-Conversion
│ │ ├── 01-convert-and-fix
│ │ │ └── main.go
│ │ ├── 02-convert-and-fix-2
│ │ │ └── main.go
│ │ ├── 03-convert-and-fix-3
│ │ │ └── main.go
│ │ ├── 04-convert-and-fix-4
│ │ │ └── main.go
│ │ └── 05-convert-and-fix-5
│ │ │ └── main.go
│ └── Variables
│ │ ├── 01-make-it-blue
│ │ └── main.go
│ │ ├── 02-vars-to-vars
│ │ └── main.go
│ │ ├── 03-assign-with-expressions
│ │ └── main.go
│ │ ├── 04-find-the-rectangle-perimeter
│ │ └── main.go
│ │ ├── 05-multi-assign
│ │ └── main.go
│ │ ├── 06-multi-assign-2
│ │ └── main.go
│ │ ├── 07-multi-short-func
│ │ └── main.go
│ │ ├── 08-swapper
│ │ └── main.go
│ │ ├── 09-swapper-2
│ │ └── main.go
│ │ └── 10-discard-the-file
│ │ └── main.go
└── Section 2
│ ├── 02-random-messages
│ └── main.go
│ ├── 03-double-guesses
│ └── main.go
│ ├── 04-verbose-mode
│ └── main.go
│ ├── 05-enough-picks
│ └── main.go
│ ├── 06-dynamic-difficulty
│ └── main.go
│ ├── Randomization
│ └── 01-first-turn-winner
│ │ └── main.go
│ └── Readme.md
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries for programs and plugins
2 | *.exe
3 | *.exe~
4 | *.dll
5 | *.so
6 | *.dylib
7 |
8 | # Test binary, built with `go test -c`
9 | *.test
10 |
11 | # Output of the go coverage tool, specifically when used with LiteIDE
12 | *.out
13 |
14 | # Dependency directories (remove the comment below to include it)
15 | # vendor/
16 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to learn about possible attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "name": "Launch Package",
9 | "type": "go",
10 | "request": "launch",
11 | "mode": "auto",
12 | "program": "${fileDirname}"
13 | }
14 | ]
15 | }
--------------------------------------------------------------------------------
/GetGoing/Advanced/channels.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func main() {
9 | fmt.Println("Consuming Channels")
10 | c := make(chan int)
11 |
12 | // Send
13 |
14 | go func() {
15 | c <- 1
16 | }()
17 |
18 | // Sniff
19 | val := <-c
20 | fmt.Println(val)
21 | go func() {
22 | c <- 5
23 | }()
24 |
25 | time.Sleep(time.Second * 2)
26 | val = <-c
27 | fmt.Println(val)
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/GetGoing/Advanced/channelsBuff.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main() {
8 | fmt.Println("Consuming Channels Buffered")
9 | c := make(chan int, 3)
10 |
11 | go func() {
12 | c <- 1
13 | c <- 2
14 | c <- 4
15 | c <- 5
16 | close(c)
17 | }()
18 |
19 | for i := range c {
20 | fmt.Println(i)
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/GetGoing/Advanced/concurrency.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func heavy() {
9 | time.Sleep(time.Second * 5)
10 | fmt.Println("Stopped")
11 | }
12 |
13 | func main() {
14 | fmt.Println("GoRoutines Initialized")
15 | go heavy()
16 | fmt.Println("Completed")
17 | select {}
18 | }
19 |
--------------------------------------------------------------------------------
/GetGoing/Advanced/lambda.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | func main() {
9 | fmt.Println("Lambda/ Anonymous functions")
10 | // Wait Group for GoRoutines
11 | wg := &sync.WaitGroup{}
12 |
13 | // mg:=&sync.Mutex{}
14 | // Use Mutex when using shared resources
15 | // mg.Lock()
16 | // mg.Unlock()
17 | // mg.TryLock()
18 |
19 | wg.Add(1)
20 |
21 | go func() {
22 | fmt.Println("I'm a Lambda Function")
23 | wg.Done()
24 | }()
25 |
26 | wg.Wait()
27 | fmt.Println("Its an end")
28 | }
29 |
--------------------------------------------------------------------------------
/GetGoing/Basics/array.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // Global Array
6 | var strArr []string
7 |
8 | func arrayMaipulation() {
9 | fmt.Println(strArr)
10 | strArr = append(strArr, "Dibesh")
11 | // Local Array
12 | intArr := []int{1, 2, 3}
13 | fmt.Println(intArr)
14 | }
15 |
16 | func main() {
17 | strArr = append(strArr, "Dinesh")
18 | arrayMaipulation()
19 | fmt.Println(strArr)
20 | for i, v := range strArr {
21 | println("\t", i, v)
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/GetGoing/Basics/controlstatements.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | fmt.Println("Control Statements")
7 | // If/Else, For, Switch, Break, Continue
8 | f := true
9 | flag := &f
10 | if flag == nil {
11 | fmt.Println("Value is Nil")
12 | } else if *flag {
13 | fmt.Println("Value is true")
14 | } else {
15 | fmt.Println("Value is False")
16 | }
17 |
18 | // Looping Over Number
19 | for i := 0; i < 10; i++ {
20 | fmt.Printf("%d is in the loop\n", i)
21 | }
22 |
23 | myMap := make(map[string]interface{})
24 | myMap["Name"] = "Dibesh"
25 | myMap["Age"] = 12
26 |
27 | for k, v := range myMap {
28 | fmt.Printf("Key:%s and Value:%v\n", k, v)
29 | }
30 |
31 | for i := 0; i < 200; i++ {
32 | if i%2 == 0 {
33 | continue
34 | } else if i == 149 {
35 | fmt.Println("Loop has limit of", i)
36 | break
37 | }
38 | fmt.Println(i, "is a odd number")
39 | }
40 |
41 | getDay(2)
42 | getDay(7)
43 | getDay(9)
44 |
45 | }
46 |
47 | func getDay(day int) {
48 | switch day {
49 | case 1:
50 | fmt.Println("Sunday")
51 | break
52 | case 2:
53 | fmt.Println("Monday")
54 | break
55 | case 3:
56 | fmt.Println("Tuesday")
57 | break
58 | case 4:
59 | fmt.Println("Wednesday")
60 | break
61 | case 5:
62 | fmt.Println("ThursDay")
63 | break
64 | case 6:
65 | fmt.Println("Friday")
66 | break
67 | case 7:
68 | fmt.Println("Saturday")
69 | break
70 | default:
71 | fmt.Println("Invalid Number")
72 | break
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/GetGoing/Basics/interfaces.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type Human interface {
6 | Walk()
7 | Talk()
8 | }
9 |
10 | type Man struct {
11 | name string
12 | }
13 |
14 | type Woman struct {
15 | name string
16 | }
17 |
18 | func NewMan(arg string) Human {
19 | return &Man{arg}
20 | }
21 |
22 | func (m *Man) Walk() {
23 | fmt.Println("He is waling")
24 | fmt.Println(m.name, "is walking.")
25 | }
26 |
27 | func (m *Man) Talk() {
28 | fmt.Println(m.name, "is talking.")
29 | }
30 |
31 | func (w *Woman) Walk() {
32 | fmt.Println("She is waling")
33 | fmt.Println(w.name, "is walking.")
34 | }
35 |
36 | type Any interface{}
37 |
38 | func Something(any Any) {
39 | fmt.Println(any)
40 | }
41 |
42 | func main() {
43 | fmt.Println("Playing with Interfaces")
44 | dina := Woman{"dina"}
45 | john := NewMan("John")
46 | dina.Walk()
47 | john.Walk()
48 | john.Talk()
49 | Something("Dibesh Raj Subedi")
50 | Something(12)
51 | }
52 |
--------------------------------------------------------------------------------
/GetGoing/Basics/main.go:
--------------------------------------------------------------------------------
1 | // Defining the package name
2 | package main
3 |
4 | // Importing I/O package
5 | import (
6 | "fmt"
7 | "strings"
8 | )
9 |
10 | // Executing Main Function
11 | func main() {
12 | // Using Println to print the message in console.
13 | fmt.Println("Hello World")
14 | // Defining and assigning a value to a variable
15 | var val1 = 2
16 | fmt.Println(val1)
17 |
18 | // Defining and assigning multiple numeric variables
19 | var (
20 | val2 int32 = 3
21 | val3 int64 = 4
22 | )
23 |
24 | // TypeCasting and adding up the variables
25 | fmt.Println(int64(val2) + val3)
26 |
27 | // Shorthand Variable Declaration
28 | val4 := 5
29 | fmt.Printf("val4 has value %d and is of type %T\n", val4, val4)
30 |
31 | // Declaring a string via shorthand
32 | val5 := "MyName is Dibesh"
33 | fmt.Println(val5)
34 | // Checking string Mutability
35 | val5 = "My Name is Dibesh"
36 | fmt.Println(val5)
37 |
38 | // String Manipulation Begins
39 | val6 := "Dibesh"
40 |
41 | // String is included in a substring
42 | fmt.Println(strings.Contains(val5, val6))
43 |
44 | // Replacing all the strings
45 | fmt.Println(strings.ReplaceAll(val5, "e", " me"))
46 | fmt.Println(val5)
47 |
48 | // Splitting string
49 | fmt.Println(strings.Split(val5, " "))
50 |
51 | // For more about string manipulation use strings and auto intelligence to suggest the possible operations
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/GetGoing/Basics/pointers.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | value1 := 20
7 | value2 := 5
8 | fmt.Println("Comparing Values of value1 and Value 2:", value1 == value2)
9 | fmt.Println("Comparing Address of value1 and Value 2:", &value1 == &value2)
10 | fmt.Println("Addresses:", &value1, &value2)
11 | fmt.Println(value1, value2)
12 | swap(&value1, &value2)
13 | fmt.Println(value1, value2)
14 | }
15 |
16 | func swap(value1, value2 *int) {
17 | var tmp int
18 | tmp = *value2
19 | *value2 = *value1
20 | *value1 = tmp
21 | }
22 |
--------------------------------------------------------------------------------
/GetGoing/Basics/structure.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // Data Encapsulations as similar to C++
6 | type Human struct {
7 | name string
8 | age int
9 | }
10 |
11 | func (h Human) Print() {
12 | fmt.Println(h.name)
13 | }
14 |
15 | func (h Human) Introduce() {
16 | fmt.Println("Hi I'm", h.name)
17 | fmt.Println("I'm", h.age, "years old!")
18 | }
19 |
20 | func (h Human) GetName() string {
21 | return h.name
22 | }
23 |
24 | func main() {
25 | fmt.Println("Testing Structures")
26 | dibesh := Human{"Dibesh", 12}
27 | fmt.Println(dibesh)
28 | dibesh.Print()
29 | dibesh.Introduce()
30 | fmt.Println(dibesh.GetName())
31 | }
32 |
--------------------------------------------------------------------------------
/GetGoing/CRUD/controller/crud.go:
--------------------------------------------------------------------------------
1 | package controller
2 |
3 | import (
4 | "crud/model"
5 | "crud/view"
6 | "encoding/json"
7 | "net/http"
8 | )
9 |
10 | func crud() http.HandlerFunc {
11 | return func(resp http.ResponseWriter, req *http.Request) {
12 | switch req.Method {
13 | case http.MethodPost:
14 | data := view.PostRequest{}
15 | json.NewDecoder(req.Body).Decode(&data)
16 | if err := model.CreateToDo(data.Name, data.ToDo); err != nil {
17 | resp.Write([]byte(err.Error()))
18 | return
19 | }
20 | resp.WriteHeader(http.StatusCreated)
21 | json.NewEncoder(resp).Encode(data)
22 | case http.MethodGet:
23 | name := req.URL.Query().Get("name")
24 | if len(name) > 0 {
25 | data, err := model.ReadByName(name)
26 | if err != nil {
27 | resp.Write([]byte(err.Error()))
28 | }
29 | resp.WriteHeader(http.StatusOK)
30 | json.NewEncoder(resp).Encode(data)
31 | } else {
32 | data, err := model.ReadAll()
33 | if err != nil {
34 | resp.Write([]byte(err.Error()))
35 | }
36 | resp.WriteHeader(http.StatusOK)
37 | json.NewEncoder(resp).Encode(data)
38 | }
39 | case http.MethodDelete:
40 | name := req.URL.Path[1:]
41 | if err := model.DeleteToDo(name); err != nil {
42 | resp.Write([]byte(err.Error()))
43 | return
44 | }
45 | resp.WriteHeader(http.StatusOK)
46 | json.NewEncoder(resp).Encode(struct {
47 | Status string `json:status`
48 | }{"Item deleted"})
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/GetGoing/CRUD/controller/ping.go:
--------------------------------------------------------------------------------
1 | package controller
2 |
3 | import (
4 | "crud/view"
5 | "encoding/json"
6 | "net/http"
7 | )
8 |
9 | func ping() http.HandlerFunc {
10 | return func(resp http.ResponseWriter, req *http.Request) {
11 | if req.Method == http.MethodGet {
12 | data := view.Response{
13 | Code: http.StatusOK,
14 | Body: "pong",
15 | }
16 | resp.WriteHeader(http.StatusOK)
17 | json.NewEncoder(resp).Encode(data)
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/GetGoing/CRUD/controller/routes.go:
--------------------------------------------------------------------------------
1 | package controller
2 |
3 | import "net/http"
4 |
5 | func Register() *http.ServeMux {
6 | mux := http.NewServeMux()
7 | mux.HandleFunc("/ping", ping())
8 | mux.HandleFunc("/", crud())
9 | return mux
10 | }
11 |
--------------------------------------------------------------------------------
/GetGoing/CRUD/go.mod:
--------------------------------------------------------------------------------
1 | module crud
2 |
3 | go 1.19
4 |
5 | require github.com/go-sql-driver/mysql v1.7.0 // indirect
6 |
--------------------------------------------------------------------------------
/GetGoing/CRUD/go.sum:
--------------------------------------------------------------------------------
1 | github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
2 | github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
3 |
--------------------------------------------------------------------------------
/GetGoing/CRUD/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "crud/controller"
5 | "crud/model"
6 | "fmt"
7 | "log"
8 | "net/http"
9 |
10 | _ "github.com/go-sql-driver/mysql"
11 | )
12 |
13 | func main() {
14 | server := "localhost:3000"
15 | db := model.Connect()
16 | defer db.Close()
17 | fmt.Println("Server started at http://", server)
18 | log.Fatal(http.ListenAndServe(server, controller.Register()))
19 | }
20 |
--------------------------------------------------------------------------------
/GetGoing/CRUD/model/connect.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import (
4 | "database/sql"
5 | "fmt"
6 | "log"
7 | )
8 |
9 | var connection *sql.DB
10 |
11 | func Connect() *sql.DB {
12 | db, err := sql.Open("mysql", "root:password@/mysql")
13 | if err != nil {
14 | log.Fatal(err)
15 | }
16 | fmt.Println("Connected to the database")
17 | connection = db
18 | return db
19 | }
20 |
--------------------------------------------------------------------------------
/GetGoing/CRUD/model/create.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import "fmt"
4 |
5 | func CreateToDo(name, todo string) error {
6 | insertQ, err := connection.Query("INSERT INTO TODO VALUES(?,?)", name, todo)
7 | if err != nil {
8 | fmt.Println(err)
9 | return err
10 | }
11 | defer insertQ.Close()
12 | return nil
13 | }
14 |
15 | func DeleteToDo(name string) error {
16 | deleteQ, err := connection.Query("DELETE FROM TODO WHERE name=?", name)
17 | if err != nil {
18 | fmt.Println(err)
19 | return err
20 | }
21 | defer deleteQ.Close()
22 | return nil
23 | }
24 |
--------------------------------------------------------------------------------
/GetGoing/CRUD/model/reade.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import "crud/view"
4 |
5 | func ReadAll() ([]view.PostRequest, error) {
6 | rows, err := connection.Query("SELECT * FROM TODO;")
7 | if err != nil {
8 | return nil, err
9 | }
10 | todos := []view.PostRequest{}
11 | for rows.Next() {
12 | data := view.PostRequest{}
13 | rows.Scan(&data.Name, &data.ToDo)
14 | todos = append(todos, data)
15 | }
16 | return todos, nil
17 | }
18 |
19 | func ReadByName(name string) ([]view.PostRequest, error) {
20 | rows, err := connection.Query("SELECT * FROM TODO WHERE name=?;", name)
21 | if err != nil {
22 | return nil, err
23 | }
24 | todos := []view.PostRequest{}
25 | for rows.Next() {
26 | data := view.PostRequest{}
27 | rows.Scan(&data.Name, &data.ToDo)
28 | todos = append(todos, data)
29 | }
30 | return todos, nil
31 | }
32 |
--------------------------------------------------------------------------------
/GetGoing/CRUD/view/view.go:
--------------------------------------------------------------------------------
1 | package view
2 |
3 | type Response struct {
4 | Code int `json:"code"`
5 | Body interface{} `json:"body"`
6 | }
7 |
8 | type PostRequest struct {
9 | Name string `json:"name"`
10 | ToDo string `json:"todo"`
11 | }
12 |
--------------------------------------------------------------------------------
/GetGoing/README.md:
--------------------------------------------------------------------------------
1 | # GetGoing
2 |
3 | [👈 Root Directory](../README.md)
4 |
5 | Free Course From Udemy [GetGoing](https://www.udemy.com/course/getgoing/)
6 |
7 | __Folder Structure__
8 |
9 | ```JavaScript
10 | [GetGoing]
11 | |---> Advanced
12 | | |---> channels.go
13 | | |---> channelsBuf.go
14 | | |---> concurrency.go
15 | | |---> lambda.go
16 | |
17 | |---> Basics
18 | | |---> array.go
19 | | |---> controlstatements.go
20 | | |---> interfaces.go
21 | | |---> main.go
22 | | |---> pointers.go
23 | | |---> structures.go
24 | |
25 | |---> CRUD
26 | | |---> controller
27 | | | |---> crud.go
28 | | | |---> ping.go
29 | | | |---> routes.go
30 | | |
31 | | |---> model
32 | | | |---> connect.go
33 | | | |---> crate.go
34 | | | |---> read.go
35 | | |
36 | | |---> view
37 | | | |---> view.go
38 | | |
39 | | |---> go.mod
40 | | |---> go.sum
41 | | |---> main.go
42 | |
43 | |---> README.md
44 | ```
45 |
--------------------------------------------------------------------------------
/GoLangProgrammers/README.md:
--------------------------------------------------------------------------------
1 | # GoLangProgrammers
2 |
--------------------------------------------------------------------------------
/GoLangProgrammers/conditionals.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func conditionals() {
9 | // if var declaration; condition {
10 | // code to be executed if condition is true
11 | // }
12 | if x := 100; x == 100 {
13 | fmt.Println("Germany")
14 | }
15 | today := time.Now()
16 |
17 | switch today.Day() {
18 | case 5:
19 | fmt.Println("Today is 5th. Clean your house.")
20 | case 10:
21 | fmt.Println("Today is 10th. Buy some wine.")
22 | case 15:
23 | fmt.Println("Today is 15th. Visit a doctor.")
24 | case 25:
25 | fmt.Println("Today is 25th. Buy some food.")
26 | case 31:
27 | fmt.Println("Party tonight.")
28 | default:
29 | fmt.Println("No information available for that day.")
30 | }
31 |
32 | var t int = today.Day()
33 |
34 | switch t {
35 | case 5, 10, 15:
36 | fmt.Println("Clean your house.")
37 | case 25, 26, 27:
38 | fmt.Println("Buy some food.")
39 | case 31:
40 | fmt.Println("Party tonight.")
41 | default:
42 | fmt.Println("No information available for that day.")
43 | }
44 |
45 | // The fallthrough keyword used to force the execution flow to fall through the successive case block.
46 | switch today.Day() {
47 | case 5:
48 | fmt.Println("Clean your house.")
49 | fallthrough
50 | case 10:
51 | fmt.Println("Buy some wine.")
52 | fallthrough
53 | case 15:
54 | fmt.Println("Visit a doctor.")
55 | fallthrough
56 | case 25:
57 | fmt.Println("Buy some food.")
58 | fallthrough
59 | case 31:
60 | fmt.Println("Party tonight.")
61 | default:
62 | fmt.Println("No information available for that day.")
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/GoLangProgrammers/constants.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "reflect"
6 | )
7 |
8 | // Constant with defined type
9 | const LAPTOP string = "HP-Omen"
10 |
11 | // Constant with implicit type definition
12 | const PRICE = 124000
13 |
14 | func constants() {
15 | // Syntax: const identifier type(optional) = value
16 | // Grouped Constant Declaration
17 | const (
18 | PRODUCT = "Mackintosh"
19 | InStock = false
20 | InNRS = 12.34
21 | )
22 | fmt.Println(LAPTOP, PRICE)
23 | fmt.Println(PRODUCT, InStock)
24 | fmt.Println("LAPTOP is of type", reflect.TypeOf(LAPTOP), "and a constant")
25 | fmt.Println("InNRS is of type", reflect.TypeOf(InNRS), "and a constant")
26 | fmt.Println("PRICE is of type", reflect.TypeOf(PRICE), "and a constant")
27 | fmt.Println("InStock is of type", reflect.TypeOf(InStock), "and a constant")
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/GoLangProgrammers/functions.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | "os"
7 | )
8 |
9 | func functions() {
10 | printName("Dibesh")
11 | fmt.Println("2 + 222 =", add(2, 222))
12 | fmt.Println("Value of PI is", pi())
13 | whoAmI()
14 | firstName, middleName, lastName := introduceYourSelf()
15 | fmt.Println("My name is", firstName, middleName, lastName)
16 | name := "Dibesh"
17 | age := 10
18 | fmt.Printf("Value Before => Name: %s and Age: %d\n", name, age)
19 | pointersAreGreat(&name, &age)
20 | fmt.Printf("Value After => Name: %s and Age: %d\n", name, age)
21 | fmt.Printf("Area of my house is : %d meeter square.\n", area(20, 30))
22 | // GoLang also supports IIFE -> Immediately Invoked Function Expression
23 | func(name string) {
24 | fmt.Println("Well It's IIFE printing Name:", name)
25 | }("Dibesh")
26 | // Closer in use as well
27 | fmt.Printf(
28 | "%s says 100 (°F) = %.2f (°C)\n", name,
29 | func(f float64) float64 {
30 | return (f - 32.0) * (5.0 / 9.0)
31 | }(100),
32 | )
33 | // Anonymous Function accessing the variable inside loop
34 | for i := 10.0; i < 100; i += 10.0 {
35 | rad := func() float64 {
36 | return i * 39.370
37 | }()
38 | fmt.Printf("%.2f Meter = %.2f Inch\n", i, rad)
39 | }
40 | fmt.Println("Executing my Super Function:")
41 | addFn := func() int64 {
42 | return add(10, 20)
43 | }
44 | fmt.Println("Result of my super function:", compounder(addFn)(3))
45 | num := squareSum(5)(6)(7)
46 | fmt.Println("Result:", num)
47 | }
48 |
49 | // Function with Argument and no return value
50 | func printName(name string) {
51 | fmt.Println("Your Name is:", name)
52 | }
53 |
54 | // Function with Argument and return value
55 | // Function with multiple params
56 | func add(number1, number2 int64) int64 {
57 | return number1 + number2
58 | }
59 |
60 | // Function with no Argument and return value
61 | func pi() (PI float64) {
62 | PI = math.Pi
63 | // Returning Statement without specifying var name
64 | return
65 | }
66 |
67 | // Function with no Argument and no return value
68 | func whoAmI() {
69 | os, _ := os.Hostname()
70 | fmt.Println(os)
71 | }
72 |
73 | // Function returning multiple values
74 | func introduceYourSelf() (firstName, middleName, lastName string) {
75 | firstName = "Dibesh"
76 | middleName = "Raj"
77 | lastName = "Subedi"
78 | return
79 | }
80 |
81 | func pointersAreGreat(name *string, age *int) {
82 | *name += " Raj Subedi" // defrencing pointer address
83 | *age += 15
84 | }
85 |
86 | // Anonymous Function
87 | var area = func(length, breadth int) int {
88 | return length * breadth
89 | }
90 |
91 | // High Order Function
92 | // Note: A Function that receives a function as an argument or returns the function as output.
93 | // Func returning a Func
94 | func compounder(magicFunc func() int64) func(product int64) float64 {
95 | return func(product int64) float64 {
96 | value := magicFunc()
97 | return float64(value) * float64(product)
98 | }
99 | }
100 |
101 | // Defining Custom Function Type
102 |
103 | type Number func() float64
104 | type InputNumber func(string) float64
105 |
106 | type First func(int) int
107 | type Second func(int) First
108 |
109 | func squareSum(x int) Second {
110 | return func(y int) First {
111 | return func(z int) int {
112 | return x*x + y*y + z*z
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/GoLangProgrammers/go.mod:
--------------------------------------------------------------------------------
1 | module GoLangProgrammers
2 |
3 | go 1.19
4 |
--------------------------------------------------------------------------------
/GoLangProgrammers/loops.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func loops() {
8 | iterations := 2
9 | characterSeq := "NEPAL"
10 | fmt.Println("Enter the number of iterations:", iterations)
11 | // fmt.Scan(&iterations)
12 | fmt.Println("Enter the character sequence:", characterSeq)
13 | // fmt.Scan(&characterSeq)
14 | fmt.Println("Printing sequence: ")
15 | length := len(characterSeq)
16 | for i := 0; i < iterations; i++ {
17 | for j := 0; j < length; j++ {
18 | for k := 0; k <= j; k++ {
19 | // The Value here is of type rune and needs to be parsed as string
20 | value := characterSeq[k]
21 | fmt.Print(" ", string(value))
22 | }
23 | fmt.Println()
24 | }
25 | }
26 | fmt.Println("\n\tPlaying with rune and strings")
27 | for index, value := range characterSeq {
28 | fmt.Print("Index:", index, ", has value ", value, ", which is :", string(value), "\n")
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/GoLangProgrammers/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | const currentlyWorking = "Functions"
8 |
9 | var workOut = map[string]func(){
10 | "Variables": variables,
11 | "Constants": constants,
12 | "TypeCasting": typeCasting,
13 | "Operators": operators,
14 | "Conditionals": conditionals,
15 | "Loops": loops,
16 | "Functions": functions,
17 | }
18 |
19 | func main() {
20 | if len(currentlyWorking) != 0 {
21 | fmt.Println("\n\tWorking with ", currentlyWorking)
22 | workOut[currentlyWorking]()
23 | } else {
24 | for index, value := range workOut {
25 | fmt.Println("\n\tWorking with ", index)
26 | value()
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/GoLangProgrammers/operators.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func operators() {
6 | var x, y = 35, 7
7 |
8 | fmt.Printf("x + y = %d\n", x+y)
9 | fmt.Printf("x - y = %d\n", x-y)
10 | fmt.Printf("x * y = %d\n", x*y)
11 | fmt.Printf("x / y = %d\n", x/y)
12 | fmt.Printf("x mod y = %d\n", x%y)
13 |
14 | x, y = 15, 25
15 |
16 | x++
17 | fmt.Printf("x++ = %d\n", x)
18 |
19 | y--
20 | fmt.Printf("y-- = %d\n", y)
21 |
22 | x = y
23 | fmt.Println("= ", x)
24 |
25 | x = 15
26 | x += y
27 | fmt.Println("+=", x)
28 |
29 | x = 50
30 | x -= y
31 | fmt.Println("-=", x)
32 |
33 | x = 2
34 | x *= y
35 | fmt.Println("*=", x)
36 |
37 | x = 100
38 | x /= y
39 | fmt.Println("/=", x)
40 |
41 | x = 40
42 | x %= y
43 | fmt.Println("%=", x)
44 |
45 | x, y = 15, 25
46 |
47 | fmt.Println(x == y)
48 | fmt.Println(x != y)
49 | fmt.Println(x < y)
50 | fmt.Println(x <= y)
51 | fmt.Println(x > y)
52 | fmt.Println(x >= y)
53 |
54 | x, y = 10, 20
55 | z := 30
56 |
57 | fmt.Println(x < y && x > z)
58 | fmt.Println(x < y || x > z)
59 | fmt.Println(!(x == y && x > z))
60 |
61 | var X uint = 9 //0000 1001
62 | var Y uint = 65 //0100 0001
63 | var Z uint
64 |
65 | Z = X & Y
66 | fmt.Println("X & Y =", Z)
67 |
68 | Z = X | Y
69 | fmt.Println("X | Y =", Z)
70 |
71 | Z = X ^ Y
72 | fmt.Println("X ^ Y =", Z)
73 |
74 | Z = X << 1
75 | fmt.Println("X << 1 =", Z)
76 |
77 | Z = X >> 1
78 | fmt.Println("X >> 1 =", Z)
79 | }
80 |
--------------------------------------------------------------------------------
/GoLangProgrammers/typeCasting.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "reflect"
6 | "strconv"
7 | )
8 |
9 | func typeCasting() {
10 | strNumber := "1000"
11 | intNum, err := strconv.Atoi(strNumber)
12 | fmt.Println(intNum, err, reflect.TypeOf(intNum))
13 | // Format -> x to string
14 | // Parse -> string to x
15 | }
16 |
--------------------------------------------------------------------------------
/GoLangProgrammers/variables.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "reflect"
6 | )
7 |
8 | func variables() {
9 | // Syntax: var identifier type(optional) = value
10 | // Variable Declaration With Initialization
11 | var bio string = "I'm Dibesh Raj Subedi"
12 | // Multiple Variable Declaration With initialization
13 | var firstName, middleName, LastName string = "Dibesh", "Raj", "Subedi"
14 | // Short Variable Declaration with Implicitly Type Definition
15 | age := 24
16 | isWorking := true
17 | // Grouped Variable Declaration
18 | var (
19 | location string = "Gaushala"
20 | zipCode int = 44660
21 | )
22 | // Printing the values in console
23 | fmt.Println(bio)
24 | fmt.Println(firstName, middleName, LastName, age, isWorking)
25 | fmt.Println(location, zipCode)
26 |
27 | // Checking Type of Variables
28 | fmt.Println("firstName is of type ", reflect.TypeOf(firstName))
29 | fmt.Println("age is of type ", reflect.TypeOf(age))
30 | fmt.Println("isWorking is of type ", reflect.TypeOf(isWorking))
31 | }
32 |
--------------------------------------------------------------------------------
/GoRmGin/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries for programs and plugins
2 | *.exe
3 | *.exe~
4 | *.dll
5 | *.so
6 | *.dylib
7 |
8 | # Test binary, built with `go test -c`
9 | *.test
10 |
11 | # Output of the go coverage tool, specifically when used with LiteIDE
12 | *.out
13 |
14 | # Dependency directories (remove the comment below to include it)
15 | vendor/
16 |
--------------------------------------------------------------------------------
/GoRmGin/README.md:
--------------------------------------------------------------------------------
1 | # GoRmGin
2 |
--------------------------------------------------------------------------------
/GoRmGin/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/itSubeDibesh/LearnGoLang/GoRmGin
2 |
3 | go 1.19
4 |
5 | require github.com/gin-gonic/gin v1.8.2
6 |
7 | require (
8 | github.com/gin-contrib/sse v0.1.0 // indirect
9 | github.com/go-playground/locales v0.14.0 // indirect
10 | github.com/go-playground/universal-translator v0.18.0 // indirect
11 | github.com/go-playground/validator/v10 v10.11.1 // indirect
12 | github.com/goccy/go-json v0.9.11 // indirect
13 | github.com/json-iterator/go v1.1.12 // indirect
14 | github.com/leodido/go-urn v1.2.1 // indirect
15 | github.com/mattn/go-isatty v0.0.16 // indirect
16 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
17 | github.com/modern-go/reflect2 v1.0.2 // indirect
18 | github.com/pelletier/go-toml/v2 v2.0.6 // indirect
19 | github.com/ugorji/go/codec v1.2.7 // indirect
20 | golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 // indirect
21 | golang.org/x/net v0.4.0 // indirect
22 | golang.org/x/sys v0.3.0 // indirect
23 | golang.org/x/text v0.5.0 // indirect
24 | google.golang.org/protobuf v1.28.1 // indirect
25 | gopkg.in/yaml.v2 v2.4.0 // indirect
26 | )
27 |
--------------------------------------------------------------------------------
/GoRmGin/go.sum:
--------------------------------------------------------------------------------
1 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
4 | github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
5 | github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
6 | github.com/gin-gonic/gin v1.8.2 h1:UzKToD9/PoFj/V4rvlKqTRKnQYyz8Sc1MJlv4JHPtvY=
7 | github.com/gin-gonic/gin v1.8.2/go.mod h1:qw5AYuDrzRTnhvusDsrov+fDIxp9Dleuu12h8nfB398=
8 | github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
9 | github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU=
10 | github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs=
11 | github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho=
12 | github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA=
13 | github.com/go-playground/validator/v10 v10.11.1 h1:prmOlTVv+YjZjmRmNSF3VmspqJIxJWXmqUsHwfTRRkQ=
14 | github.com/go-playground/validator/v10 v10.11.1/go.mod h1:i+3WkQ1FvaUjjxh1kSvIA4dMGDBiPU55YFDl0WbKdWU=
15 | github.com/goccy/go-json v0.9.11 h1:/pAaQDLHEoCq/5FFmSKBswWmK6H0e8g4159Kc/X/nqk=
16 | github.com/goccy/go-json v0.9.11/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
17 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
18 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
19 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
20 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
21 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
22 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
23 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
24 | github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
25 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
26 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
27 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
28 | github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=
29 | github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
30 | github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
31 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
32 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
33 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
34 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
35 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
36 | github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU=
37 | github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek=
38 | github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
39 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
40 | github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
41 | github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
42 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
43 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
44 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
45 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
46 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
47 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
48 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
49 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
50 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
51 | github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M=
52 | github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=
53 | github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=
54 | golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 h1:0es+/5331RGQPcXlMfP+WrnIIS6dNnNRe0WB02W0F4M=
55 | golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
56 | golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
57 | golang.org/x/net v0.4.0 h1:Q5QPcMlvfxFTAPV0+07Xz/MpK9NTXu2VDUuy0FeMfaU=
58 | golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
59 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
60 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
61 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
62 | golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
63 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
64 | golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
65 | golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
66 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
67 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
68 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
69 | golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM=
70 | golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
71 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
72 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
73 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
74 | google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=
75 | google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
76 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
77 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
78 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
79 | gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
80 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
81 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
82 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
83 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
84 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
85 |
--------------------------------------------------------------------------------
/GoRmGin/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "net/http"
5 |
6 | "github.com/gin-gonic/gin"
7 | )
8 |
9 | type album struct {
10 | ID string `json:"id"`
11 | Title string `jsonL:title"`
12 | Artist string `json:"artist"`
13 | Price float64 `json:"price"`
14 | }
15 |
16 | var albums = []album{
17 | {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
18 | {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
19 | {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
20 | }
21 |
22 | func getAlbums(c *gin.Context) {
23 | c.IndentedJSON(http.StatusOK, albums)
24 | }
25 |
26 | func main() {
27 | router := gin.Default()
28 | router.GET("/albums", getAlbums)
29 | router.Run("localhost:8080")
30 | }
31 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Dibesh Raj Subedi
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/LetsGo/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "cSpell.words": ["httprouter", "mysqlstore", "nosurf", "tmpl"]
3 | }
4 |
--------------------------------------------------------------------------------
/LetsGo/ReadMe.md:
--------------------------------------------------------------------------------
1 | # Let's Go
2 |
3 | 
4 |
5 | [👈 Back](../README.md)
6 |
7 | ## Coding Snippet Box
8 |
9 | I will be creating the the Snippet Box app as per explained in the book by [Alex Edwards](https://github.com/alexedwards) along with documenting all the necessary resources. Explore more of the code in [snippetbox](./snippetbox/ReadMe.md) directory.
10 |
11 | ## Things to consider
12 |
13 | - Avoid using `DefaultServeMux` for security purpose and prefer locally-scoped servemux
14 |
15 | ## To Further Research
16 |
17 | - Supply Chain Attacks
18 | - Directory Traversal Attacks
19 | - Data Racing and its Prevention
20 | - Closure Pattern
21 | - Clean URL
22 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries for programs and plugins
2 | *.exe
3 | *.exe~
4 | *.dll
5 | *.so
6 | *.dylib
7 |
8 | # Test binary, built with `go test -c`
9 | *.test
10 |
11 | # Output of the go coverage tool, specifically when used with LiteIDE
12 | *.out
13 |
14 | # Dependency directories (remove the comment below to include it)
15 | vendor/
16 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "cSpell.words": ["snippetbox"]
3 | }
4 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/ReadMe.md:
--------------------------------------------------------------------------------
1 | # SnippetBox
2 |
3 | ## API Routes
4 |
5 | |S.N|Method|Pattern|Handler|Action|
6 | |:--|:----:|:------|:-----:|:-----|
7 | |1|ANY|/|home|Display the home page|
8 | |2|ANY|/snippet/view/:id|snippetView|Display a specific snippet|
9 | |3|GET|/snippet/create|snippetCreate|Display a HTML form for creating a new snippet|
10 | |4|POST|/snippet/create|snippetCreatePost|Create a new snippet|
11 | |5|GET|/user/signup|userSignup|Display a HTML form for signing up a new user|
12 | |6|POST|/user/signup|userSignupPost|Create a new user|
13 | |7|GET|/user/login|userLogin|Display a html form for logging in a user|
14 | |8|POST|/user/login|userLoginPost|Authenticate and login the user|
15 | |9|POST|/user/logout|userLogoutPost|Logout the user|
16 | |10|ANY |/static/*filepath| http.FileServer| Serve a specific static file|
17 |
18 | You can find `DB Schema` at [docs directory](./docs/Schema-SnippetBox.sql)
19 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/cmd/web/context.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | type contextKey string
4 |
5 | const isAuthenticatedContextKey = contextKey("isAuthenticated")
6 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/cmd/web/handlers.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "net/http"
7 | "strconv"
8 |
9 | "github.com/itSubeDibesh/LearnGoLang/LetsGo/snippetbox/internal/models"
10 | "github.com/itSubeDibesh/LearnGoLang/LetsGo/snippetbox/internal/validator"
11 | "github.com/julienschmidt/httprouter"
12 | )
13 |
14 | type snippetCreatForm struct {
15 | Title string `form:"title"`
16 | Content string `form:"content"`
17 | Expires int `form:"expires"`
18 | validator.Validator `form:"-"`
19 | }
20 |
21 | type userLoginForm struct {
22 | Email string `form:"email"`
23 | Password string `form:"password"`
24 | validator.Validator `form:"-"`
25 | }
26 |
27 | type userSignUpForm struct {
28 | Name string `form:"name"`
29 | Email string `form:"email"`
30 | Password string `form:"password"`
31 | validator.Validator `form:"-"`
32 | }
33 |
34 | // Route: localhost:4000/
35 | func (app *application) home(w http.ResponseWriter, r *http.Request) {
36 | if r.URL.Path != "/" {
37 | app.notFound(w)
38 | return
39 | }
40 |
41 | snippets, err := app.snippets.Latest()
42 | if err != nil {
43 | app.serverError(w, err)
44 | return
45 | }
46 |
47 | data := app.newTemplateData(r)
48 | data.Snippets = snippets
49 |
50 | app.render(w, http.StatusOK, "home.tmpl", data)
51 |
52 | }
53 |
54 | // Route: localhost:4000/snippet/view
55 | func (app *application) snippetView(w http.ResponseWriter, r *http.Request) {
56 | params := httprouter.ParamsFromContext(r.Context())
57 | id, err := strconv.Atoi(params.ByName("id"))
58 | if err != nil || id < 1 {
59 | app.notFound(w)
60 | return
61 | }
62 | snippet, err := app.snippets.Get(id)
63 | if err != nil {
64 | if errors.Is(err, models.ErrNoRecord) {
65 | app.notFound(w)
66 | } else {
67 | app.serverError(w, err)
68 | }
69 | return
70 | }
71 |
72 | data := app.newTemplateData(r)
73 | data.Snippet = snippet
74 |
75 | app.render(w, http.StatusOK, "view.tmpl", data)
76 |
77 | }
78 |
79 | // Method:GET Route: localhost:4000/snippet/create
80 | func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) {
81 | data := app.newTemplateData(r)
82 | data.Form = snippetCreatForm{
83 | Expires: 365,
84 | }
85 | app.render(w, http.StatusOK, "create.tmpl", data)
86 | }
87 |
88 | // Method:POST Route: localhost:4000/snippet/create
89 | func (app *application) snippetCreatePost(w http.ResponseWriter, r *http.Request) {
90 | var form snippetCreatForm
91 | err := app.decodePostForm(r, &form)
92 | if err != nil {
93 | app.clientError(w, http.StatusBadRequest)
94 | return
95 | }
96 |
97 | form.CheckField(validator.NotBlank(form.Title), "title", "This field cannot be blank")
98 | form.CheckField(validator.MaxChars(form.Title, 100), "title", "This field cannot be more than 100 characters long")
99 | form.CheckField(validator.NotBlank(form.Content), "content", "This field cannot be blank")
100 | form.CheckField(validator.PermittedInt(form.Expires, 1, 7, 365), "expires", "This field must equal 1, 7 or 365")
101 |
102 | fmt.Println("After Content:", form.Content, "Title:", form.Title, "Expires:", form.Expires, "IsValid:", form.Valid())
103 | if !form.Valid() {
104 | data := app.newTemplateData(r)
105 | data.Form = form
106 | app.render(w, http.StatusUnprocessableEntity, "create.tmpl", data)
107 | return
108 | }
109 |
110 | id, err := app.snippets.Insert(form.Title, form.Content, form.Expires)
111 | if err != nil {
112 | app.serverError(w, err)
113 | return
114 | }
115 |
116 | app.sessionManager.Put(r.Context(), "flash", "Snippet successfully created!")
117 |
118 | http.Redirect(w, r, fmt.Sprintf("/snippet/view/%d", id), http.StatusSeeOther)
119 | }
120 |
121 | // Method:GET Route: localhost:4000/user/signup
122 | func (app *application) userSignUp(w http.ResponseWriter, r *http.Request) {
123 | data := app.newTemplateData(r)
124 | data.Form = userSignUpForm{}
125 | app.render(w, http.StatusOK, "signup.tmpl", data)
126 |
127 | }
128 |
129 | // Method:POST Route: localhost:4000/user/signup
130 | func (app *application) userSignUpPost(w http.ResponseWriter, r *http.Request) {
131 | var form userSignUpForm
132 |
133 | err := app.decodePostForm(r, &form)
134 | if err != nil {
135 | app.clientError(w, http.StatusBadRequest)
136 | return
137 | }
138 |
139 | form.CheckField(validator.NotBlank(form.Name), "name", "This field cannot be blank")
140 | form.CheckField(validator.NotBlank(form.Email), "email", "This field cannot be blank")
141 | form.CheckField(validator.Matches(form.Email, validator.EmailRX), "email", "This field must be a valid email address")
142 | form.CheckField(validator.NotBlank(form.Password), "password", "This field cannot be blank")
143 | form.CheckField(validator.MinChars(form.Password, 8), "password", "This field must be at least 8 characters long")
144 |
145 | if !form.Valid() {
146 | data := app.newTemplateData(r)
147 | data.Form = form
148 | app.render(w, http.StatusUnprocessableEntity, "signup.tmpl", data)
149 | return
150 | }
151 |
152 | err = app.users.Insert(form.Name, form.Email, form.Password)
153 | if err != nil {
154 | if errors.Is(err, models.ErrDuplicateEmail) {
155 | form.AddFieldError("email", "Email address is already in use")
156 | data := app.newTemplateData(r)
157 | data.Form = form
158 | app.render(w, http.StatusUnprocessableEntity, "signup.tmpl", data)
159 | } else {
160 | app.serverError(w, err)
161 | }
162 | return
163 | }
164 |
165 | app.sessionManager.Put(r.Context(), "flash", "Your signup was successful. Please login in.")
166 |
167 | http.Redirect(w, r, "/user/login", http.StatusSeeOther)
168 | }
169 |
170 | // Method:GET Route: localhost:4000/user/login
171 | func (app *application) userLogin(w http.ResponseWriter, r *http.Request) {
172 | data := app.newTemplateData(r)
173 | data.Form = userLoginForm{}
174 | app.render(w, http.StatusOK, "login.tmpl", data)
175 | }
176 |
177 | // Method:POST Route: localhost:4000/user/login
178 | func (app *application) userLoginPost(w http.ResponseWriter, r *http.Request) {
179 | var form userSignUpForm
180 |
181 | err := app.decodePostForm(r, &form)
182 | if err != nil {
183 | app.clientError(w, http.StatusBadRequest)
184 | return
185 | }
186 |
187 | form.CheckField(validator.NotBlank(form.Email), "email", "This field cannot be blank")
188 | form.CheckField(validator.Matches(form.Email, validator.EmailRX), "email", "This field must be a valid email address")
189 | form.CheckField(validator.NotBlank(form.Password), "password", "This field cannot be blank")
190 |
191 | if !form.Valid() {
192 | data := app.newTemplateData(r)
193 | data.Form = form
194 | app.render(w, http.StatusUnprocessableEntity, "login.template", data)
195 | return
196 | }
197 |
198 | id, err := app.users.Authenticate(form.Email, form.Password)
199 | if err != nil {
200 | if errors.Is(err, models.ErrInvalidCredentials) {
201 | form.AddNonFieldError("Email or Password is incorrect")
202 | data := app.newTemplateData(r)
203 | data.Form = form
204 | app.render(w, http.StatusUnprocessableEntity, "login.tmpl", data)
205 | } else {
206 | app.serverError(w, err)
207 | }
208 | }
209 |
210 | err = app.sessionManager.RenewToken(r.Context())
211 | if err != nil {
212 | app.serverError(w, err)
213 | return
214 | }
215 |
216 | app.sessionManager.Put(r.Context(), "authenticatedUserID", id)
217 | http.Redirect(w, r, "/snippet/create", http.StatusSeeOther)
218 | }
219 |
220 | // Method:POST Route: localhost:4000/user/logout
221 | func (app *application) userLogoutPost(w http.ResponseWriter, r *http.Request) {
222 | err := app.sessionManager.RenewToken(r.Context())
223 | if err != nil {
224 | app.serverError(w, err)
225 | return
226 | }
227 |
228 | app.sessionManager.Remove(r.Context(), "authenticatedUserID")
229 | app.sessionManager.Put(r.Context(), "flash", "You've been logged out successfully!")
230 | http.Redirect(w, r, "/", http.StatusSeeOther)
231 | }
232 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/cmd/web/helpers.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "errors"
6 | "fmt"
7 | "net/http"
8 | "runtime/debug"
9 | "time"
10 |
11 | "github.com/go-playground/form/v4"
12 | "github.com/justinas/nosurf"
13 | )
14 |
15 | // Sending A Generic 500 Internal Server Error
16 | func (app *application) serverError(w http.ResponseWriter, err error) {
17 | trace := fmt.Sprintf("%s\n%s", err.Error(), debug.Stack())
18 | app.errorLog.Output(2, trace)
19 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
20 | }
21 |
22 | // Standardizing Custom errors for client
23 | func (app *application) clientError(w http.ResponseWriter, status int) {
24 | http.Error(w, http.StatusText(status), status)
25 | }
26 |
27 | func (app *application) notFound(w http.ResponseWriter) {
28 | app.clientError(w, http.StatusNotFound)
29 | }
30 |
31 | func (app *application) render(w http.ResponseWriter, status int, page string, data *templateData) {
32 | ts, ok := app.templateCache[page]
33 | if !ok {
34 | err := fmt.Errorf("the template %s does not exist", page)
35 | app.serverError(w, err)
36 | return
37 | }
38 |
39 | buff := new(bytes.Buffer)
40 |
41 | err := ts.ExecuteTemplate(buff, "base", data)
42 | if err != nil {
43 | app.serverError(w, err)
44 | }
45 |
46 | w.WriteHeader(status)
47 |
48 | buff.WriteTo(w)
49 | }
50 |
51 | // Common dynamic data
52 | func (app *application) newTemplateData(r *http.Request) *templateData {
53 | return &templateData{
54 | CurrentYear: time.Now().Year(),
55 | Flash: app.sessionManager.PopString(r.Context(), "flash"),
56 | IsAuthenticated: app.isAuthenticated(r),
57 | CSRFToken: nosurf.Token(r),
58 | }
59 | }
60 |
61 | func (app *application) decodePostForm(r *http.Request, dst any) error {
62 | err := r.ParseForm()
63 | if err != nil {
64 | return err
65 | }
66 | err = app.formDecoder.Decode(dst, r.PostForm)
67 | if err != nil {
68 | var invalidDecodeError *form.InvalidDecoderError
69 | if errors.As(err, &invalidDecodeError) {
70 | panic(err)
71 | }
72 | return err
73 | }
74 | return nil
75 | }
76 |
77 | func (app *application) isAuthenticated(r *http.Request) bool {
78 | isAuthenticated, ok := r.Context().Value(isAuthenticatedContextKey).(bool)
79 | if !ok {
80 | return false
81 | }
82 | return isAuthenticated
83 | }
84 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/cmd/web/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "database/sql"
5 | "flag"
6 | "log"
7 | "net/http"
8 | "os"
9 | "text/template"
10 | "time"
11 |
12 | "github.com/alexedwards/scs/mysqlstore"
13 | "github.com/alexedwards/scs/v2"
14 | "github.com/go-playground/form/v4"
15 | "github.com/itSubeDibesh/LearnGoLang/LetsGo/snippetbox/internal/models"
16 |
17 | _ "github.com/go-sql-driver/mysql"
18 | )
19 |
20 | type application struct {
21 | errorLog *log.Logger
22 | infoLog *log.Logger
23 | snippets *models.SnippetModel
24 | users *models.UserModel
25 | templateCache map[string]*template.Template
26 | formDecoder *form.Decoder
27 | sessionManager *scs.SessionManager
28 | }
29 |
30 | func main() {
31 | // Dynamically Accepting addr flag via CLI
32 | addr := flag.String("addr", ":4000", "Http network Address")
33 | dns := flag.String("dns", "web:pass@/snippetbox?parseTime=true", "MySQL data source name")
34 |
35 | flag.Parse()
36 |
37 | infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
38 | errorLog := log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)
39 |
40 | db, err := openDB(*dns)
41 | if err != nil {
42 | errorLog.Fatal(err)
43 | }
44 |
45 | defer db.Close()
46 |
47 | templateCache, err := newTemplateCaching()
48 | if err != nil {
49 | errorLog.Fatal(err)
50 | }
51 |
52 | formDecoder := form.NewDecoder()
53 |
54 | sessionManager := scs.New()
55 | sessionManager.Store = mysqlstore.New(db)
56 | sessionManager.Lifetime = 12 * time.Hour
57 |
58 | app := &application{
59 | errorLog: errorLog,
60 | infoLog: infoLog,
61 | snippets: &models.SnippetModel{DB: db},
62 | users: &models.UserModel{DB: db},
63 | templateCache: templateCache,
64 | formDecoder: formDecoder,
65 | sessionManager: sessionManager,
66 | }
67 |
68 | // Binding loggers with server
69 | server := &http.Server{
70 | Addr: *addr,
71 | ErrorLog: errorLog,
72 | Handler: app.routes(),
73 | }
74 |
75 | infoLog.Print("Server starting on http://localhost" + *addr)
76 | err = server.ListenAndServe()
77 | errorLog.Fatal(err)
78 | }
79 |
80 | func openDB(dns string) (*sql.DB, error) {
81 | db, err := sql.Open("mysql", dns)
82 | if err != nil {
83 | return nil, err
84 | }
85 | if err = db.Ping(); err != nil {
86 | return nil, err
87 | }
88 | return db, nil
89 | }
90 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/cmd/web/middleware.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "fmt"
6 | "net/http"
7 |
8 | "github.com/justinas/nosurf"
9 | )
10 |
11 | func secureHeaders(next http.Handler) http.Handler {
12 | policies := map[string]string{
13 | "Content-Security-Policy": "default-src 'self'; style-src 'self' fonts.googleapis.com; font-src fonts.gstatic.com",
14 | "Referrer-Policy": "origin-whe-cross-origin",
15 | "X-Content-Type-Options": "nosniff",
16 | "X-Frame-Options": "deny",
17 | "X-XSS-Protection": "0",
18 | }
19 |
20 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
21 | for key, value := range policies {
22 | w.Header().Set(key, value)
23 | }
24 | next.ServeHTTP(w, r)
25 | })
26 | }
27 |
28 | func noSURF(next http.Handler) http.Handler {
29 | csrfHandler := nosurf.New(next)
30 | csrfHandler.SetBaseCookie(http.Cookie{
31 | HttpOnly: true,
32 | Path: "/",
33 | Secure: true,
34 | })
35 | return csrfHandler
36 | }
37 |
38 | func (app *application) requireAuthentication(next http.Handler) http.Handler {
39 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
40 | if !app.isAuthenticated(r) {
41 | http.Redirect(w, r, "/user/login", http.StatusSeeOther)
42 | return
43 | }
44 |
45 | w.Header().Add("Cache-Control", "no-store")
46 |
47 | next.ServeHTTP(w, r)
48 | })
49 | }
50 |
51 | func (app *application) logRequest(next http.Handler) http.Handler {
52 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
53 | app.infoLog.Printf("%s - %s %s %s", r.RemoteAddr, r.Proto, r.Method, r.URL.RequestURI())
54 | next.ServeHTTP(w, r)
55 | })
56 | }
57 |
58 | func (app *application) recoverPanic(next http.Handler) http.Handler {
59 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
60 | defer func() {
61 | if err := recover(); err != nil {
62 | w.Header().Set("Connection", "close")
63 | app.serverError(w, fmt.Errorf("%s", err))
64 | }
65 | }()
66 | next.ServeHTTP(w, r)
67 | })
68 | }
69 |
70 | func (app *application) authenticate(next http.Handler) http.Handler {
71 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
72 | id := app.sessionManager.GetInt(r.Context(), "authenticatedUserID")
73 | if id == 0 {
74 | next.ServeHTTP(w, r)
75 | return
76 | }
77 |
78 | exists, err := app.users.Exists(id)
79 | if err != nil {
80 | app.serverError(w, err)
81 | return
82 | }
83 |
84 | if exists {
85 | ctx := context.WithValue(r.Context(), isAuthenticatedContextKey, true)
86 | r = r.WithContext(ctx)
87 | }
88 |
89 | next.ServeHTTP(w, r)
90 | })
91 | }
92 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/cmd/web/routes.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "net/http"
5 |
6 | "github.com/julienschmidt/httprouter"
7 | "github.com/justinas/alice"
8 | )
9 |
10 | func (app *application) routes() http.Handler {
11 | router := httprouter.New()
12 |
13 | router.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
14 | app.notFound(w)
15 | })
16 |
17 | // Serving Static files
18 | fileServer := http.FileServer(http.Dir("./ui/static/"))
19 | router.Handler(http.MethodGet, "/static/*filepath", http.StripPrefix("/static", fileServer))
20 |
21 | // Unprotected Dynamic routes
22 | dynamic := alice.New(app.sessionManager.LoadAndSave, noSURF, app.authenticate)
23 |
24 | router.Handler(http.MethodGet, "/", dynamic.ThenFunc(app.home))
25 | router.Handler(http.MethodGet, "/snippet/view/:id", dynamic.ThenFunc(app.snippetView))
26 | router.Handler(http.MethodGet, "/user/login", dynamic.ThenFunc(app.userLogin))
27 | router.Handler(http.MethodPost, "/user/login", dynamic.ThenFunc(app.userLoginPost))
28 | router.Handler(http.MethodGet, "/user/signup", dynamic.ThenFunc(app.userSignUp))
29 | router.Handler(http.MethodPost, "/user/signup", dynamic.ThenFunc(app.userSignUpPost))
30 |
31 | protected := dynamic.Append(app.requireAuthentication)
32 | router.Handler(http.MethodGet, "/snippet/create", protected.ThenFunc(app.snippetCreate))
33 | router.Handler(http.MethodPost, "/snippet/create", protected.ThenFunc(app.snippetCreatePost))
34 | router.Handler(http.MethodPost, "/user/logout", protected.ThenFunc(app.userLogoutPost))
35 |
36 | middleWareStandard := alice.New(app.recoverPanic, app.logRequest, secureHeaders)
37 | return middleWareStandard.Then(router)
38 | }
39 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/cmd/web/templates.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "path/filepath"
5 | "text/template"
6 | "time"
7 |
8 | "github.com/itSubeDibesh/LearnGoLang/LetsGo/snippetbox/internal/models"
9 | )
10 |
11 | func humanDate(t time.Time) string {
12 | return t.Format("02 Jan 2006 at 15:04")
13 | }
14 |
15 | var functions = template.FuncMap{
16 | "humanDate": humanDate,
17 | }
18 |
19 | type templateData struct {
20 | CurrentYear int
21 | Snippet *models.Snippet
22 | Snippets []*models.Snippet
23 | Form any
24 | Flash string
25 | IsAuthenticated bool
26 | CSRFToken string
27 | }
28 |
29 | func newTemplateCaching() (map[string]*template.Template, error) {
30 | cache := map[string]*template.Template{}
31 | pages, err := filepath.Glob("./ui/html/pages/*.tmpl")
32 | if err != nil {
33 | return nil, err
34 | }
35 | for _, page := range pages {
36 | name := filepath.Base(page)
37 | ts, err := template.New(name).Funcs(functions).ParseFiles("./ui/html/base.tmpl")
38 | if err != nil {
39 | return nil, err
40 | }
41 |
42 | ts, err = ts.ParseGlob("./ui/html/partials/*.tmpl")
43 | if err != nil {
44 | return nil, err
45 | }
46 |
47 | ts, err = ts.ParseFiles(page)
48 | if err != nil {
49 | return nil, err
50 | }
51 | cache[name] = ts
52 | }
53 | return cache, nil
54 | }
55 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/docs/Schema-SnippetBox.sql:
--------------------------------------------------------------------------------
1 | CREATE DATABASE IF NOT EXISTS `snippetbox` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
2 | USE `snippetbox`;
3 | -- MySQL dump 10.13 Distrib 8.0.31, for Win64 (x86_64)
4 | --
5 | -- Host: localhost Database: snippetbox
6 | -- ------------------------------------------------------
7 | -- Server version 8.0.31
8 |
9 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
10 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
11 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
12 | /*!50503 SET NAMES utf8 */;
13 | /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
14 | /*!40103 SET TIME_ZONE='+00:00' */;
15 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
16 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
17 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
18 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
19 |
20 | --
21 | -- Table structure for table `sessions`
22 | --
23 |
24 | DROP TABLE IF EXISTS `sessions`;
25 | /*!40101 SET @saved_cs_client = @@character_set_client */;
26 | /*!50503 SET character_set_client = utf8mb4 */;
27 | CREATE TABLE `sessions` (
28 | `token` char(43) COLLATE utf8mb4_unicode_ci NOT NULL,
29 | `data` blob NOT NULL,
30 | `expiry` timestamp(6) NOT NULL,
31 | PRIMARY KEY (`token`),
32 | KEY `sessions_expiry_idx` (`expiry`)
33 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
34 | /*!40101 SET character_set_client = @saved_cs_client */;
35 |
36 | --
37 | -- Table structure for table `snippets`
38 | --
39 |
40 | DROP TABLE IF EXISTS `snippets`;
41 | /*!40101 SET @saved_cs_client = @@character_set_client */;
42 | /*!50503 SET character_set_client = utf8mb4 */;
43 | CREATE TABLE `snippets` (
44 | `id` int NOT NULL AUTO_INCREMENT,
45 | `title` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
46 | `content` text COLLATE utf8mb4_unicode_ci NOT NULL,
47 | `created` datetime NOT NULL,
48 | `expires` datetime NOT NULL,
49 | PRIMARY KEY (`id`),
50 | KEY `idx_snippets_created` (`created`)
51 | ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
52 | /*!40101 SET character_set_client = @saved_cs_client */;
53 |
54 | --
55 | -- Table structure for table `users`
56 | --
57 |
58 | DROP TABLE IF EXISTS `users`;
59 | /*!40101 SET @saved_cs_client = @@character_set_client */;
60 | /*!50503 SET character_set_client = utf8mb4 */;
61 | CREATE TABLE `users` (
62 | `id` int NOT NULL AUTO_INCREMENT,
63 | `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
64 | `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
65 | `hashed_password` char(60) COLLATE utf8mb4_unicode_ci NOT NULL,
66 | `created` datetime NOT NULL,
67 | PRIMARY KEY (`id`),
68 | UNIQUE KEY `users_uc_email` (`email`)
69 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
70 | /*!40101 SET character_set_client = @saved_cs_client */;
71 |
72 | --
73 | -- Dumping events for database 'snippetbox'
74 | --
75 |
76 | --
77 | -- Dumping routines for database 'snippetbox'
78 | --
79 | /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
80 |
81 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
82 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
83 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
84 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
85 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
86 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
87 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
88 |
89 | -- Dump completed on 2023-01-24 12:46:56
90 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/itSubeDibesh/LearnGoLang/LetsGo/snippetbox
2 |
3 | go 1.19
4 |
5 | require github.com/go-sql-driver/mysql v1.7.0
6 |
7 | require (
8 | github.com/alexedwards/scs/mysqlstore v0.0.0-20221223131519-238b052508b6 // indirect
9 | github.com/alexedwards/scs/v2 v2.5.0 // indirect
10 | github.com/go-playground/form/v4 v4.2.0 // indirect
11 | github.com/julienschmidt/httprouter v1.3.0 // indirect
12 | github.com/justinas/alice v1.2.0 // indirect
13 | github.com/justinas/nosurf v1.1.1 // indirect
14 | golang.org/x/crypto v0.5.0 // indirect
15 | )
16 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/go.sum:
--------------------------------------------------------------------------------
1 | github.com/alexedwards/scs/mysqlstore v0.0.0-20221223131519-238b052508b6 h1:4j0tF8tM3QW7hMWLI8qsWqdQBQz4Lx7Nzp3kGjP0tEQ=
2 | github.com/alexedwards/scs/mysqlstore v0.0.0-20221223131519-238b052508b6/go.mod h1:MKLf409wtunSUZ+5eUwPzlfGYSpITYzJZ4UZzU5rMoY=
3 | github.com/alexedwards/scs/v2 v2.5.0 h1:zgxOfNFmiJyXG7UPIuw1g2b9LWBeRLh3PjfB9BDmfL4=
4 | github.com/alexedwards/scs/v2 v2.5.0/go.mod h1:ToaROZxyKukJKT/xLcVQAChi5k6+Pn1Gvmdl7h3RRj8=
5 | github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
6 | github.com/go-playground/form/v4 v4.2.0 h1:N1wh+Goz61e6w66vo8vJkQt+uwZSoLz50kZPJWR8eic=
7 | github.com/go-playground/form/v4 v4.2.0/go.mod h1:q1a2BY+AQUUzhl6xA/6hBetay6dEIhMHjgvJiGo6K7U=
8 | github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
9 | github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
10 | github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
11 | github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
12 | github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
13 | github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo=
14 | github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA=
15 | github.com/justinas/nosurf v1.1.1 h1:92Aw44hjSK4MxJeMSyDa7jwuI9GR2J/JCQiaKvXXSlk=
16 | github.com/justinas/nosurf v1.1.1/go.mod h1:ALpWdSbuNGy2lZWtyXdjkYv4edL23oSEgfBT1gPJ5BQ=
17 | golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE=
18 | golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU=
19 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/internal/models/error.go:
--------------------------------------------------------------------------------
1 | package models
2 |
3 | import "errors"
4 |
5 | var (
6 | ErrNoRecord = errors.New("models: no matching record found")
7 | ErrInvalidCredentials = errors.New("models: invalid credentials")
8 | ErrDuplicateEmail = errors.New("models: duplicate email")
9 | )
10 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/internal/models/snippets.go:
--------------------------------------------------------------------------------
1 | package models
2 |
3 | import (
4 | "database/sql"
5 | "errors"
6 | "time"
7 | )
8 |
9 | type Snippet struct {
10 | ID int
11 | Title string
12 | Content string
13 | Created time.Time
14 | Expires time.Time
15 | }
16 |
17 | type SnippetModel struct {
18 | DB *sql.DB
19 | }
20 |
21 | func (m *SnippetModel) Insert(title, content string, expires int) (int, error) {
22 | statements := `INSERT INTO snippets (title, content, created, expires) VALUES(?, ?, UTC_TIMESTAMP(), DATE_ADD(UTC_TIMESTAMP(), INTERVAL ? DAY))`
23 | result, err := m.DB.Exec(statements, title, content, expires)
24 | if err != nil {
25 | return 0, err
26 | }
27 | id, err := result.LastInsertId()
28 | if err != nil {
29 | return 0, err
30 | }
31 | return int(id), nil
32 | }
33 |
34 | func (m *SnippetModel) Get(id int) (*Snippet, error) {
35 |
36 | statement := `SELECT id, title, content, created, expires FROM snippets WHERE expires > UTC_TIMESTAMP() AND id = ?`
37 | rows := m.DB.QueryRow(statement, id)
38 | s := &Snippet{}
39 |
40 | err := rows.Scan(&s.ID, &s.Title, &s.Content, &s.Created, &s.Expires)
41 | if err != nil {
42 | if errors.Is(err, sql.ErrNoRows) {
43 | return nil, ErrNoRecord
44 | } else {
45 | return nil, err
46 | }
47 | }
48 | return s, nil
49 | }
50 |
51 | func (m *SnippetModel) Latest() ([]*Snippet, error) {
52 | statement := `SELECT id, title, content, created, expires FROM snippets WHERE expires > UTC_TIMESTAMP() ORDER BY id DESC LIMIT 10`
53 | rows, err := m.DB.Query(statement)
54 | if err != nil {
55 | return nil, err
56 | }
57 | defer rows.Close()
58 | snippets := []*Snippet{}
59 | for rows.Next() {
60 | s := &Snippet{}
61 | err = rows.Scan(&s.ID, &s.Title, &s.Content, &s.Created, &s.Expires)
62 | if err != nil {
63 | return nil, err
64 | }
65 | snippets = append(snippets, s)
66 | }
67 | if err = rows.Err(); err != nil {
68 | return nil, err
69 | }
70 | return snippets, nil
71 | }
72 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/internal/models/users.go:
--------------------------------------------------------------------------------
1 | package models
2 |
3 | import (
4 | "database/sql"
5 | "errors"
6 | "strings"
7 | "time"
8 |
9 | "github.com/go-sql-driver/mysql"
10 | "golang.org/x/crypto/bcrypt"
11 | )
12 |
13 | type User struct {
14 | ID int
15 | Name string
16 | Email string
17 | HashedPassword []byte
18 | Created time.Time
19 | }
20 |
21 | type UserModel struct {
22 | DB *sql.DB
23 | }
24 |
25 | func (m *UserModel) Authenticate(email, password string) (int, error) {
26 | var id int
27 | var hashedPassword []byte
28 |
29 | statement := "SELECT id, hashed_password FROM users WHERE email =?"
30 |
31 | err := m.DB.QueryRow(statement, email).Scan(&id, &hashedPassword)
32 | if err != nil {
33 | if errors.Is(err, sql.ErrNoRows) {
34 | return 0, ErrInvalidCredentials
35 | } else {
36 | return 0, err
37 | }
38 | }
39 |
40 | err = bcrypt.CompareHashAndPassword(hashedPassword, []byte(password))
41 | if err != nil {
42 | if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
43 | return 0, ErrInvalidCredentials
44 | } else {
45 | return 0, err
46 | }
47 | }
48 |
49 | return id, nil
50 | }
51 |
52 | func (m *UserModel) Exists(id int) (bool, error) {
53 | var exist bool
54 | statement := "SELECT EXISTS(SELECT true FROM users WHERE id =?)"
55 | err := m.DB.QueryRow(statement, id).Scan(&exist)
56 | return exist, err
57 | }
58 |
59 | func (m *UserModel) Insert(name, email, password string) error {
60 | hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 12)
61 | if err != nil {
62 | return err
63 | }
64 |
65 | statement := `INSERT INTO users (name, email, hashed_password, created)
66 | VALUES(?, ?, ?, UTC_TIMESTAMP())`
67 |
68 | _, err = m.DB.Exec(statement, name, email, string(hashedPassword))
69 | if err != nil {
70 | var mySQLError *mysql.MySQLError
71 | if errors.As(err, &mySQLError) {
72 | if mySQLError.Number == 1062 && strings.Contains(mySQLError.Message, "users_uc_email") {
73 | return ErrDuplicateEmail
74 | }
75 | }
76 | return err
77 | }
78 | return nil
79 | }
80 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/internal/validator/validator.go:
--------------------------------------------------------------------------------
1 | package validator
2 |
3 | import (
4 | "regexp"
5 | "strings"
6 | "unicode/utf8"
7 | )
8 |
9 | type Validator struct {
10 | FieldErrors map[string]string
11 | NonFieldErrors []string
12 | }
13 |
14 | func (v *Validator) AddFieldError(key, message string) {
15 | if v.FieldErrors == nil {
16 | v.FieldErrors = make(map[string]string)
17 | }
18 |
19 | if _, exists := v.FieldErrors[key]; !exists {
20 | v.FieldErrors[key] = message
21 | }
22 | }
23 |
24 | func (v *Validator) Valid() bool {
25 | return len(v.FieldErrors) == 0 && len(v.NonFieldErrors) == 0
26 | }
27 |
28 | func (v *Validator) CheckField(ok bool, key, message string) {
29 | if !ok {
30 | v.AddFieldError(key, message)
31 | }
32 | }
33 |
34 | func NotBlank(value string) bool {
35 | return strings.TrimSpace(value) != ""
36 | }
37 |
38 | func MaxChars(value string, n int) bool {
39 | return utf8.RuneCountInString(value) < n
40 | }
41 |
42 | func PermittedInt(value int, permittedValues ...int) bool {
43 | for i := range permittedValues {
44 | if value == permittedValues[i] {
45 | return true
46 | }
47 | }
48 | return false
49 | }
50 |
51 | var EmailRX = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
52 |
53 | func MinChars(value string, n int) bool {
54 | return utf8.RuneCountInString(value) >= n
55 | }
56 |
57 | func Matches(value string, rx *regexp.Regexp) bool {
58 | return rx.MatchString(value)
59 | }
60 |
61 | func (v *Validator) AddNonFieldError(message string) {
62 | v.NonFieldErrors = append(v.NonFieldErrors, message)
63 | }
64 |
--------------------------------------------------------------------------------
/LetsGo/snippetbox/ui/html/base.tmpl:
--------------------------------------------------------------------------------
1 | {{define "base"}}
2 |
3 |
4 |
5 |
6 | {{template "title" .}} - Snippetbox
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
17 | {{template "nav" .}}
18 |
19 | {{with .Flash}}
20 | {{.}}
21 | {{end}}
22 | {{template "main" .}}
23 |
24 |
25 |
26 |
27 |
28 |
29 | {{end}}
--------------------------------------------------------------------------------
/LetsGo/snippetbox/ui/html/pages/create.tmpl:
--------------------------------------------------------------------------------
1 | {{define "title"}}Create a New Snippet{{end}}
2 |
3 | {{define "main"}}
4 |
33 | {{end}}
--------------------------------------------------------------------------------
/LetsGo/snippetbox/ui/html/pages/home.tmpl:
--------------------------------------------------------------------------------
1 | {{define "title"}}Home{{end}}
2 |
3 | {{define "main"}}
4 | Latest Snippets
5 | {{if .Snippets}}
6 |
7 |
8 | Title |
9 | Created |
10 | ID |
11 |
12 | {{range .Snippets}}
13 |
14 | {{.Title}} |
15 | {{humanDate .Created}} |
16 | #{{.ID}} |
17 |
18 | {{end}}
19 |
20 | {{else}}
21 | There's nothing to see here... yet!
22 | {{end}}
23 | {{end}}
--------------------------------------------------------------------------------
/LetsGo/snippetbox/ui/html/pages/login.tmpl:
--------------------------------------------------------------------------------
1 | {{define "title"}}Login{{end}}
2 |
3 | {{define "main"}}
4 |
27 | {{end}}
--------------------------------------------------------------------------------
/LetsGo/snippetbox/ui/html/pages/signup.tmpl:
--------------------------------------------------------------------------------
1 | {{define "title"}}Signup{{end}}
2 |
3 | {{define "main"}}
4 |
31 | {{end}}
--------------------------------------------------------------------------------
/LetsGo/snippetbox/ui/html/pages/view.tmpl:
--------------------------------------------------------------------------------
1 | {{define "title"}}Snippet #{{.Snippet.ID}}{{end}}
2 |
3 | {{define "main"}}
4 | {{with .Snippet}}
5 |
6 |
7 | {{.Title}}
8 | #{{.ID}}
9 |
10 |
{{.Content}}
11 |
12 |
13 |
14 |
15 |
16 | {{end}}
17 | {{end}}
--------------------------------------------------------------------------------
/LetsGo/snippetbox/ui/html/partials/nav.tmpl:
--------------------------------------------------------------------------------
1 | {{define "nav"}}
2 |
21 | {{end}}
--------------------------------------------------------------------------------
/LetsGo/snippetbox/ui/static/css/main.css:
--------------------------------------------------------------------------------
1 | * {
2 | box-sizing: border-box;
3 | margin: 0;
4 | padding: 0;
5 | font-size: 18px;
6 | font-family: "Ubuntu Mono", monospace;
7 | }
8 |
9 | html,
10 | body {
11 | height: 100%;
12 | }
13 |
14 | body {
15 | line-height: 1.5;
16 | background-color: #F1F3F6;
17 | color: #34495E;
18 | overflow-y: scroll;
19 | }
20 |
21 | header,
22 | nav,
23 | main,
24 | footer {
25 | padding: 2px calc((100% - 800px) / 2) 0;
26 | }
27 |
28 | main {
29 | margin-top: 54px;
30 | margin-bottom: 54px;
31 | min-height: calc(100vh - 345px);
32 | overflow: auto;
33 | }
34 |
35 | h1 a {
36 | font-size: 36px;
37 | font-weight: bold;
38 | background-image: url("/static/img/logo.png");
39 | background-repeat: no-repeat;
40 | background-position: 0px 0px;
41 | height: 36px;
42 | padding-left: 50px;
43 | position: relative;
44 | }
45 |
46 | h1 a:hover {
47 | text-decoration: none;
48 | color: #34495E;
49 | }
50 |
51 | h2 {
52 | font-size: 22px;
53 | margin-bottom: 36px;
54 | position: relative;
55 | top: -9px;
56 | }
57 |
58 | a {
59 | color: #62CB31;
60 | text-decoration: none;
61 | }
62 |
63 | a:hover {
64 | color: #4EB722;
65 | text-decoration: underline;
66 | }
67 |
68 | textarea,
69 | input:not([type="submit"]) {
70 | font-size: 18px;
71 | font-family: "Ubuntu Mono", monospace;
72 | }
73 |
74 | header {
75 | background-image: -webkit-linear-gradient(left, #34495e, #34495e 25%, #9b59b6 25%, #9b59b6 35%, #3498db 35%, #3498db 45%, #62cb31 45%, #62cb31 55%, #ffb606 55%, #ffb606 65%, #e67e22 65%, #e67e22 75%, #e74c3c 85%, #e74c3c 85%, #c0392b 85%, #c0392b 100%);
76 | background-image: -moz-linear-gradient(left, #34495e, #34495e 25%, #9b59b6 25%, #9b59b6 35%, #3498db 35%, #3498db 45%, #62cb31 45%, #62cb31 55%, #ffb606 55%, #ffb606 65%, #e67e22 65%, #e67e22 75%, #e74c3c 85%, #e74c3c 85%, #c0392b 85%, #c0392b 100%);
77 | background-image: -ms-linear-gradient(left, #34495e, #34495e 25%, #9b59b6 25%, #9b59b6 35%, #3498db 35%, #3498db 45%, #62cb31 45%, #62cb31 55%, #ffb606 55%, #ffb606 65%, #e67e22 65%, #e67e22 75%, #e74c3c 85%, #e74c3c 85%, #c0392b 85%, #c0392b 100%);
78 | background-image: linear-gradient(to right, #34495e, #34495e 25%, #9b59b6 25%, #9b59b6 35%, #3498db 35%, #3498db 45%, #62cb31 45%, #62cb31 55%, #ffb606 55%, #ffb606 65%, #e67e22 65%, #e67e22 75%, #e74c3c 85%, #e74c3c 85%, #c0392b 85%, #c0392b 100%);
79 | background-size: 100% 6px;
80 | background-repeat: no-repeat;
81 | border-bottom: 1px solid #E4E5E7;
82 | overflow: auto;
83 | padding-top: 33px;
84 | padding-bottom: 27px;
85 | text-align: center;
86 | }
87 |
88 | header a {
89 | color: #34495E;
90 | text-decoration: none;
91 | }
92 |
93 | nav {
94 | border-bottom: 1px solid #E4E5E7;
95 | padding-top: 17px;
96 | padding-bottom: 15px;
97 | background: #F7F9FA;
98 | height: 60px;
99 | color: #6A6C6F;
100 | }
101 |
102 | nav a {
103 | margin-right: 1.5em;
104 | display: inline-block;
105 | }
106 |
107 | nav form {
108 | display: inline-block;
109 | margin-left: 1.5em;
110 | }
111 |
112 | nav div {
113 | width: 50%;
114 | float: left;
115 | }
116 |
117 | nav div:last-child {
118 | text-align: right;
119 | }
120 |
121 | nav div:last-child a {
122 | margin-left: 1.5em;
123 | margin-right: 0;
124 | }
125 |
126 | nav a.live {
127 | color: #34495E;
128 | cursor: default;
129 | }
130 |
131 | nav a.live:hover {
132 | text-decoration: none;
133 | }
134 |
135 | nav a.live:after {
136 | content: '';
137 | display: block;
138 | position: relative;
139 | left: calc(50% - 7px);
140 | top: 9px;
141 | width: 14px;
142 | height: 14px;
143 | background: #F7F9FA;
144 | border-left: 1px solid #E4E5E7;
145 | border-bottom: 1px solid #E4E5E7;
146 | -moz-transform: rotate(45deg);
147 | -webkit-transform: rotate(-45deg);
148 | }
149 |
150 | a.button,
151 | input[type="submit"] {
152 | background-color: #62CB31;
153 | border-radius: 3px;
154 | color: #FFFFFF;
155 | padding: 18px 27px;
156 | border: none;
157 | display: inline-block;
158 | margin-top: 18px;
159 | font-weight: 700;
160 | }
161 |
162 | a.button:hover,
163 | input[type="submit"]:hover {
164 | background-color: #4EB722;
165 | color: #FFFFFF;
166 | cursor: pointer;
167 | text-decoration: none;
168 | }
169 |
170 | form div {
171 | margin-bottom: 18px;
172 | }
173 |
174 | form div:last-child {
175 | border-top: 1px dashed #E4E5E7;
176 | }
177 |
178 | form input[type="radio"] {
179 | margin-left: 18px;
180 | }
181 |
182 | form input[type="text"],
183 | form input[type="password"],
184 | form input[type="email"] {
185 | padding: 0.75em 18px;
186 | width: 100%;
187 | }
188 |
189 | form input[type=text],
190 | form input[type="password"],
191 | form input[type="email"],
192 | textarea {
193 | color: #6A6C6F;
194 | background: #FFFFFF;
195 | border: 1px solid #E4E5E7;
196 | border-radius: 3px;
197 | }
198 |
199 | form label {
200 | display: inline-block;
201 | margin-bottom: 9px;
202 | }
203 |
204 | .error {
205 | color: #C0392B;
206 | font-weight: bold;
207 | display: block;
208 | }
209 |
210 | .error+textarea,
211 | .error+input {
212 | border-color: #C0392B !important;
213 | border-width: 2px !important;
214 | }
215 |
216 | textarea {
217 | padding: 18px;
218 | width: 100%;
219 | height: 266px;
220 | }
221 |
222 | button {
223 | background: none;
224 | padding: 0;
225 | border: none;
226 | color: #62CB31;
227 | text-decoration: none;
228 | }
229 |
230 | button:hover {
231 | color: #4EB722;
232 | text-decoration: underline;
233 | cursor: pointer;
234 | }
235 |
236 | .snippet {
237 | background-color: #FFFFFF;
238 | border: 1px solid #E4E5E7;
239 | border-radius: 3px;
240 | }
241 |
242 | .snippet pre {
243 | padding: 18px;
244 | border-top: 1px solid #E4E5E7;
245 | border-bottom: 1px solid #E4E5E7;
246 | }
247 |
248 | .snippet .metadata {
249 | background-color: #F7F9FA;
250 | color: #6A6C6F;
251 | padding: 0.75em 18px;
252 | overflow: auto;
253 | }
254 |
255 | .snippet .metadata span {
256 | float: right;
257 | }
258 |
259 | .snippet .metadata strong {
260 | color: #34495E;
261 | }
262 |
263 | .snippet .metadata time {
264 | display: inline-block;
265 | }
266 |
267 | .snippet .metadata time:first-child {
268 | float: left;
269 | }
270 |
271 | .snippet .metadata time:last-child {
272 | float: right;
273 | }
274 |
275 | div.flash {
276 | color: #FFFFFF;
277 | font-weight: bold;
278 | background-color: #34495E;
279 | padding: 18px;
280 | margin-bottom: 36px;
281 | text-align: center;
282 | }
283 |
284 | div.error {
285 | color: #FFFFFF;
286 | background-color: #C0392B;
287 | padding: 18px;
288 | margin-bottom: 36px;
289 | font-weight: bold;
290 | text-align: center;
291 | }
292 |
293 | table {
294 | background: white;
295 | border: 1px solid #E4E5E7;
296 | border-collapse: collapse;
297 | width: 100%;
298 | }
299 |
300 | td,
301 | th {
302 | text-align: left;
303 | padding: 9px 18px;
304 | }
305 |
306 | th:last-child,
307 | td:last-child {
308 | text-align: right;
309 | color: #6A6C6F;
310 | }
311 |
312 | tr {
313 | border-bottom: 1px solid #E4E5E7;
314 | }
315 |
316 | tr:nth-child(2n) {
317 | background-color: #F7F9FA;
318 | }
319 |
320 | footer {
321 | border-top: 1px solid #E4E5E7;
322 | padding-top: 17px;
323 | padding-bottom: 15px;
324 | background: #F7F9FA;
325 | height: 60px;
326 | color: #6A6C6F;
327 | text-align: center;
328 | }
329 |
330 | pre {
331 | overflow: auto;
332 | }
--------------------------------------------------------------------------------
/LetsGo/snippetbox/ui/static/img/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingWithDibesh/LearnGoLang/d3b08ad8a966a4ffc3de0b17d0c1bc83725f31de/LetsGo/snippetbox/ui/static/img/favicon.ico
--------------------------------------------------------------------------------
/LetsGo/snippetbox/ui/static/img/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodingWithDibesh/LearnGoLang/d3b08ad8a966a4ffc3de0b17d0c1bc83725f31de/LetsGo/snippetbox/ui/static/img/logo.png
--------------------------------------------------------------------------------
/LetsGo/snippetbox/ui/static/js/main.js:
--------------------------------------------------------------------------------
1 | var navLinks = document.querySelectorAll("nav a");
2 | for (var i = 0; i < navLinks.length; i++) {
3 | var link = navLinks[i]
4 | if (link.getAttribute('href') == window.location.pathname) {
5 | link.classList.add("live");
6 | break;
7 | }
8 | }
--------------------------------------------------------------------------------
/MasterGoLang/Readme.md:
--------------------------------------------------------------------------------
1 | # Go Bootcamp: Master Golang with 1000+ Exercises and Projects
2 |
3 | This document is summary of the codes under `MasterGoLang` directory and coding exercise from Udemy course [Bootcamp: Master Golang with 1000+ Exercises and Projects
4 | ](https://www.udemy.com/course/learn-go-the-complete-bootcamp-course-golang)
5 |
6 | Section 1
7 |
8 | 1. Variables
9 | - Make It Blue
10 | - Variables To Variables
11 | - Assign With Expressions
12 | - Find the Rectangle's Perimeter
13 | - Multi Assign
14 | - Multi Assign #2
15 | - Multi Short Func
16 | - Swapper
17 | - Swapper #2
18 | - Discard The File
19 | 2. Type-Conversion
20 | - Convert and Fix #1
21 | - Convert and Fix #2
22 | - Convert and Fix #3
23 | - Convert and Fix #4
24 | - Convert and Fix #5
25 | 3. Command Line Arguments
26 | - Count the Arguments
27 | - Print the Path
28 | - Print Your Name
29 | - Greet More People
30 | - Greet 5 People
31 | 4. Basic Strings
32 | - Windows Path
33 | - Print JSON
34 | - Raw Concat
35 | - Count the Chars
36 | - Improved Banger
37 | - ToLowercase
38 | - Trim It
39 | - Right Trim It
40 | 5. IOTA
41 | - Iota Months
42 | - Iota Months #2
43 | - Iota Seasons
44 | 6. PRINTF
45 | - Print Your Age
46 | - Print Your Name and LastName
47 | - False Claims
48 | - Print the Temperature
49 | - Double Quotes
50 | - Print the Type
51 | - Print the Type #2
52 | - Print the Type #3
53 | - Print the Type #4
54 | - Print Your Full name
55 | 7. If Statement
56 | - Age Seasons
57 | - Simplify It
58 | - Arg Count
59 | - Vowel or Consonant
60 | 8. Pass Me Challenges Source Code
61 | - Challenge #1
62 | - Challenge #2
63 | 9. Error Handling
64 | - Movie Ratings
65 | - Odd or Even
66 | - Leap Year
67 | - Simplify the Leap Year
68 | - Days in a Month
69 | 10. Switch Statement
70 | - Richter Scale
71 | - Richter Scale #2
72 | - Convert
73 | - String Manipulator
74 | - Days in a Month
75 | 11. LOOP
76 | - Dynamic Table
77 | - Math Table
78 | - Sum the Numbers
79 | - Sum the Numbers: Verbose Edition
80 | - Sum up to N
81 | - Only Evens
82 | - Break Up
83 | - Infinite Kill
84 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Basic Strings/01-windows-path/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Windows Path
15 | //
16 | // 1. Change the following program
17 | // 2. It should use a raw string literal instead
18 | //
19 | // HINT
20 | // Run this program first to see its output.
21 | // Then you can easily understand what it does.
22 | //
23 | // EXPECTED OUTPUT
24 | // Your solution should output the same as this program.
25 | // Only that it should use a raw string literal instead.
26 | // ---------------------------------------------------------
27 |
28 | func main() {
29 | // HINTS:
30 | // \\ equals to backslash character
31 | // \n equals to newline character
32 |
33 | path := "c:\\program files\\duper super\\fun.txt\n" +
34 | "c:\\program files\\really\\funny.png"
35 |
36 | newPath := `c:\program files\dumper super\fun.txt
37 | c:\program files\really\funny.png
38 | `
39 | fmt.Println(path)
40 | fmt.Println(newPath)
41 | }
42 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Basic Strings/02-print-json/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Print JSON
15 | //
16 | // 1. Change the following program
17 | // 2. It should use a raw string literal instead
18 | //
19 | // HINT
20 | // Run this program first to see its output.
21 | // Then you can easily understand what it does.
22 | //
23 | // EXPECTED OUTPUT
24 | // Your solution should output the same as this program.
25 | // Only that it should use a raw string literal instead.
26 | // ---------------------------------------------------------
27 |
28 | func main() {
29 | // HINTS:
30 | // \t equals to TAB character
31 | // \n equals to newline character
32 | // \" equals to double-quotes character
33 |
34 | json := "\n" +
35 | "{\n" +
36 | "\t\"Items\": [{\n" +
37 | "\t\t\"Item\": {\n" +
38 | "\t\t\t\"name\": \"Teddy Bear\"\n" +
39 | "\t\t}\n" +
40 | "\t}]\n" +
41 | "}\n"
42 |
43 | newJson := `
44 | {
45 | "Items": [{
46 | "Item": {
47 | "name": "Teddy Bear"
48 | }
49 | }]
50 | }`
51 |
52 | fmt.Println(json)
53 | fmt.Println(newJson)
54 | }
55 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Basic Strings/03-raw-concat/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Raw Concat
15 | //
16 | // 1. Initialize the name variable
17 | // by getting input from the command line
18 | //
19 | // 2. Use concatenation operator to concatenate it
20 | // with the raw string literal below
21 | //
22 | // NOTE
23 | // You should concatenate the name variable in the correct
24 | // place.
25 | //
26 | // EXPECTED OUTPUT
27 | // Let's say that you run the program like this:
28 | // go run main.go inanç
29 | //
30 | // Then it should output this:
31 | // hi inanç!
32 | // how are you?
33 | // ---------------------------------------------------------
34 |
35 | func main() {
36 | // uncomment the code below
37 | name := "and get the name from the command-line"
38 |
39 | // replace and concatenate the `name` variable
40 | // after `hi ` below
41 |
42 | msg := `hi ` + name + `!
43 | how are you?`
44 |
45 | fmt.Println(msg)
46 | }
47 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Basic Strings/04-count-the-chars/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "unicode/utf8"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // EXERCISE: Count the Chars
19 | //
20 | // 1. Change the following program to work with unicode
21 | // characters.
22 | //
23 | // INPUT
24 | // "İNANÇ"
25 | //
26 | // EXPECTED OUTPUT
27 | // 5
28 | // ---------------------------------------------------------
29 |
30 | func main() {
31 | // Currently it returns 7
32 | // Because, it counts the bytes...
33 | // It should count the runes (codepoints) instead.
34 | //
35 | // When you run it with "İNANÇ", it should return 5 not 7.
36 |
37 | length := utf8.RuneCountInString(os.Args[1])
38 | fmt.Println(length)
39 | }
40 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Basic Strings/05-improved-banger/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strings"
15 | "unicode/utf8"
16 | )
17 |
18 | // ---------------------------------------------------------
19 | // EXERCISE: Improved Banger
20 | //
21 | // Change the Banger program the work with Unicode
22 | // characters.
23 | //
24 | // INPUT
25 | // "İNANÇ"
26 | //
27 | // EXPECTED OUTPUT
28 | // İNANÇ!!!!!
29 | // ---------------------------------------------------------
30 |
31 | func main() {
32 | msg := os.Args[1]
33 |
34 | s := msg + strings.Repeat("!", utf8.RuneCountInString(msg))
35 |
36 | fmt.Println(s)
37 | }
38 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Basic Strings/06-tolowercase/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strings"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // EXERCISE: ToLowercase
19 | //
20 | // 1. Look at the documentation of strings package
21 | // 2. Find a function that changes the letters into lowercase
22 | // 3. Get a value from the command-line
23 | // 4. Print the given value in lowercase letters
24 | //
25 | // HINT
26 | // Check out the strings package from Go online documentation.
27 | // You will find the lowercase function there.
28 | //
29 | // INPUT
30 | // "SHEPARD"
31 | //
32 | // EXPECTED OUTPUT
33 | // shepard
34 | // ---------------------------------------------------------
35 |
36 | func main() {
37 | fmt.Println(strings.ToUpper(os.Args[1]))
38 | }
39 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Basic Strings/07-trim-it/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "strings"
14 | )
15 |
16 | // ---------------------------------------------------------
17 | // EXERCISE: Trim It
18 | //
19 | // 1. Look at the documentation of strings package
20 | // 2. Find a function that trims the spaces from
21 | // the given string
22 | // 3. Trim the text variable and print it
23 | //
24 | // EXPECTED OUTPUT
25 | // The weather looks good.
26 | // I should go and play.
27 | // ---------------------------------------------------------
28 |
29 | func main() {
30 | msg := `
31 |
32 | The weather looks good.
33 | I should go and play.
34 |
35 |
36 |
37 | `
38 |
39 | fmt.Println(strings.TrimSpace(msg))
40 | }
41 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Basic Strings/08-right-trim-it/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "strings"
14 | "unicode/utf8"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // EXERCISE: Right Trim It
19 | //
20 | // 1. Look at the documentation of strings package
21 | // 2. Find a function that trims the spaces from
22 | // only the right-most part of the given string
23 | // 3. Trim it from the right part only
24 | // 4. Print the number of characters it contains.
25 | //
26 | // RESTRICTION
27 | // Your program should work with unicode string values.
28 | //
29 | // EXPECTED OUTPUT
30 | // 5
31 | // ---------------------------------------------------------
32 |
33 | func main() {
34 | // currently it prints 17
35 | // it should print 5
36 |
37 | name := "inanç "
38 | fmt.Println(utf8.RuneCountInString(strings.TrimRight(name, " ")))
39 | }
40 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Command Line Arguments/01-count-arguments/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | )
15 |
16 | // ---------------------------------------------------------
17 | // EXERCISE: Count the Arguments
18 | //
19 | // Print the count of the command-line arguments
20 | //
21 | // INPUT
22 | // bilbo balbo bungo
23 | //
24 | // EXPECTED OUTPUT
25 | // There are 3 names.
26 | // ---------------------------------------------------------
27 |
28 | func main() {
29 | // UNCOMMENT & FIX THIS CODE
30 | count := len(os.Args) - 1
31 |
32 | // UNCOMMENT IT & THEN DO NOT TOUCH THIS CODE
33 | fmt.Printf("There are %d names.\n", count)
34 | }
35 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Command Line Arguments/03-print-your-name/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | )
15 |
16 | // ---------------------------------------------------------
17 | // EXERCISE: Print Your Name
18 | //
19 | // Get it from the first command-line argument
20 | //
21 | // INPUT
22 | // Call the program using your name
23 | //
24 | // EXPECTED OUTPUT
25 | // It should print your name
26 | //
27 | // EXAMPLE
28 | // go run main.go inanc
29 | //
30 | // inanc
31 | //
32 | // BONUS: Make the output like this:
33 | //
34 | // go run main.go inanc
35 | // Hi inanc
36 | // How are you?
37 | // ---------------------------------------------------------
38 |
39 | func main() {
40 | // get your name from the command-line
41 | // and print it
42 | fmt.Println("Hi", os.Args[1])
43 | fmt.Println("How are you?")
44 | }
45 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Command Line Arguments/04-greet-more-people/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | )
15 |
16 | // ---------------------------------------------------------
17 | // EXERCISE: Greet More People
18 | //
19 | // RESTRICTIONS
20 | // 1. Be sure to match the expected output below
21 | // 2. Store the length of the arguments in a variable
22 | // 3. Store all the arguments in variables as well
23 | //
24 | // INPUT
25 | // bilbo balbo bungo
26 | //
27 | // EXPECTED OUTPUT
28 | // There are 3 people!
29 | // Hello great bilbo !
30 | // Hello great balbo !
31 | // Hello great bungo !
32 | // Nice to meet you all.
33 | // ---------------------------------------------------------
34 |
35 | func main() {
36 | // TYPE YOUR CODE HERE
37 | // BONUS #1:
38 | // Observe the error if you pass less then 3 arguments.
39 | // Search on the web how to solve that.
40 |
41 | var (
42 | l = len(os.Args) - 1
43 | n1 = os.Args[1]
44 | n2 = os.Args[2]
45 | n3 = os.Args[3]
46 | )
47 |
48 | fmt.Println("There are", l, "people !")
49 | fmt.Println("Hello great", n1, "!")
50 | fmt.Println("Hello great", n2, "!")
51 | fmt.Println("Hello great", n3, "!")
52 | fmt.Println("Nice to meet you all.")
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Command Line Arguments/05-greet-5-people/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | )
15 |
16 | // ---------------------------------------------------------
17 | // EXERCISE: Greet 5 People
18 | //
19 | // Greet 5 people this time.
20 | //
21 | // Please do not copy paste from the previous exercise!
22 | //
23 | // RESTRICTION
24 | // This time do not use variables.
25 | //
26 | // INPUT
27 | // bilbo balbo bungo gandalf legolas
28 | //
29 | // EXPECTED OUTPUT
30 | // There are 5 people!
31 | // Hello great bilbo !
32 | // Hello great balbo !
33 | // Hello great bungo !
34 | // Hello great gandalf !
35 | // Hello great legolas !
36 | // Nice to meet you all.
37 | // ---------------------------------------------------------
38 |
39 | func main() {
40 | // TYPE YOUR CODE HERE
41 | names, length := os.Args, len(os.Args)-1
42 | if names != nil && length >= 3 {
43 | fmt.Printf("There are %d people!\n", length)
44 | for i := 0; i < length; i++ {
45 | fmt.Printf("Hello great %s !\n", names[i+1])
46 | }
47 | fmt.Println("Nice to meet you all.")
48 | } else {
49 | fmt.Println("You must enter at least 3 names")
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Error Handling/05-movie-ratings/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strconv"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // STORY
19 | //
20 | // Your boss wants you to create a program that will check
21 | // whether a person can watch a particular movie or not.
22 | //
23 | // Imagine that another program provides the age to your
24 | // program. Depending on what you return, the other program
25 | // will issue the tickets to the person automatically.
26 | //
27 | // EXERCISE: Movie Ratings
28 | //
29 | // 1. Get the age from the command-line.
30 | //
31 | // 2. Return one of the following messages if the age is:
32 | // -> Above 17 : "R-Rated"
33 | // -> Between 13 and 17: "PG-13"
34 | // -> Below 13 : "PG-Rated"
35 | //
36 | // RESTRICTIONS:
37 | // 1. If age data is wrong or absent let the user know.
38 | // 2. Do not accept negative age.
39 | //
40 | // BONUS:
41 | // 1. BONUS: Use if statements only twice throughout your program.
42 | // 2. BONUS: Use an if statement only once.
43 | //
44 | // EXPECTED OUTPUT
45 | // go run main.go 18
46 | // R-Rated
47 | //
48 | // go run main.go 17
49 | // PG-13
50 | //
51 | // go run main.go 12
52 | // PG-Rated
53 | //
54 | // go run main.go
55 | // Requires age
56 | //
57 | // go run main.go -5
58 | // Wrong age: "-5"
59 | // ---------------------------------------------------------
60 |
61 | func main() {
62 | args := os.Args
63 | // if len(args) != 2 {
64 | // fmt.Println("Requires age")
65 | // return
66 | // }
67 |
68 | // if n, err := strconv.Atoi(args[1]); err != nil {
69 | // fmt.Println("Error:", err)
70 | // } else if n < 1 {
71 | // fmt.Printf("Wrong age: %q\n", args[1])
72 | // } else if n < 13 {
73 | // fmt.Println("PG-Rated")
74 | // } else if n >= 13 && n <= 17 {
75 | // fmt.Println("PG-13")
76 | // } else {
77 | // fmt.Println("R-Rated")
78 | // }
79 |
80 | // Bonus:1
81 | // if len(args) != 2 {
82 | // fmt.Println("Requires age")
83 | // return
84 | // } else {
85 | // if n, err := strconv.Atoi(args[1]); err != nil {
86 | // fmt.Println("Error:", err)
87 | // } else if n < 1 {
88 | // fmt.Printf("Wrong age: %q\n", args[1])
89 | // } else if n < 13 {
90 | // fmt.Println("PG-Rated")
91 | // } else if n >= 13 && n <= 17 {
92 | // fmt.Println("PG-13")
93 | // } else {
94 | // fmt.Println("R-Rated")
95 | // }
96 | // }
97 |
98 | // Bonus:2
99 | if len(args) != 2 {
100 | fmt.Println("Requires age")
101 | } else if n, err := strconv.Atoi(args[1]); err != nil {
102 | fmt.Println("Error:", err)
103 | } else if n < 1 {
104 | fmt.Printf("Wrong age: %q\n", args[1])
105 | } else if n < 13 {
106 | fmt.Println("PG-Rated")
107 | } else if n >= 13 && n <= 17 {
108 | fmt.Println("PG-13")
109 | } else {
110 | fmt.Println("R-Rated")
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Error Handling/06-odd-even/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strconv"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // EXERCISE: Odd or Even
19 | //
20 | // 1. Get a number from the command-line.
21 | //
22 | // 2. Find whether the number is odd, even and divisible by 8.
23 | //
24 | // RESTRICTION
25 | // Handle the error. If the number is not a valid number,
26 | // or it's not provided, let the user know.
27 | //
28 | // EXPECTED OUTPUT
29 | // go run main.go 16
30 | // 16 is an even number and it's divisible by 8
31 | //
32 | // go run main.go 4
33 | // 4 is an even number
34 | //
35 | // go run main.go 3
36 | // 3 is an odd number
37 | //
38 | // go run main.go
39 | // Pick a number
40 | //
41 | // go run main.go ABC
42 | // "ABC" is not a number
43 | // ---------------------------------------------------------
44 |
45 | func main() {
46 | args := os.Args
47 |
48 | if len(args) != 2 {
49 | fmt.Println("Pick a number")
50 | } else if n, err := strconv.Atoi(args[1]); err != nil {
51 | fmt.Printf("%q is not a number\n", args[1])
52 | } else {
53 | num := 8
54 | var c string
55 | if c = "odd"; n%2 == 0 {
56 | c = "even"
57 | }
58 | if n%8 == 0 {
59 | fmt.Printf("%d is an %v number and it't divisible by %d\n", n, c, num)
60 | } else {
61 | fmt.Printf("%d is an %v number\n", n, c)
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Error Handling/07-leap-year/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strconv"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // EXERCISE: Leap Year
19 | //
20 | // Find out whether a given year is a leap year or not.
21 | //
22 | // EXPECTED OUTPUT
23 | // go run main.go
24 | // Give me a year number
25 | //
26 | // go run main.go eighties
27 | // "eighties" is not a valid year.
28 | //
29 | // go run main.go 2018
30 | // 2018 is not a leap year.
31 | //
32 | // go run main.go 2100
33 | // 2100 is not a leap year.
34 | //
35 | // go run main.go 2019
36 | // 2019 is not a leap year.
37 | //
38 | // go run main.go 2020
39 | // 2020 is a leap year.
40 | //
41 | // go run main.go 2024
42 | // 2024 is a leap year.
43 | // ---------------------------------------------------------
44 |
45 | func main() {
46 | args := os.Args
47 | if len(args) != 2 {
48 | fmt.Println("Give me a year number")
49 | return
50 | }
51 | if year, err := strconv.Atoi(args[1]); err != nil {
52 | fmt.Println("Error:", err)
53 | } else {
54 | if len(args[1]) != 4 {
55 | fmt.Printf("%q is not a valid year.\n", args[1])
56 | } else {
57 | var leap bool
58 |
59 | if year%400 == 0 {
60 | leap = true
61 | } else if year%100 == 0 {
62 | leap = false
63 | } else if year%4 == 0 {
64 | leap = true
65 | }
66 |
67 | if leap {
68 | fmt.Printf("%d is a leap year.\n", year)
69 | } else {
70 | fmt.Printf("%d is not a leap year.\n", year)
71 | }
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Error Handling/08-simplify-leap-year/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strconv"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // EXERCISE: Simplify the Leap Year
19 | //
20 | // 1. Look at the solution of "the previous exercise".
21 | //
22 | // 2. And simplify the code (especially the if statements!).
23 | //
24 | // EXPECTED OUTPUT
25 | // It's the same as the previous exercise.
26 | // ---------------------------------------------------------
27 |
28 | func main() {
29 | args := os.Args
30 | if len(args) != 2 {
31 | fmt.Println("Give me a year number")
32 | return
33 | }
34 | if year, err := strconv.Atoi(args[1]); err != nil {
35 | fmt.Println("Error:", err)
36 | } else {
37 | if len(args[1]) != 4 {
38 | fmt.Printf("%q is not a valid year.\n", args[1])
39 | } else {
40 |
41 | if year%4 == 0 && (year%400 != 0 || year%4 == 0) {
42 | fmt.Printf("%d is a leap year.\n", year)
43 | } else {
44 | fmt.Printf("%d is not a leap year.\n", year)
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Error Handling/09-days-in-month/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strings"
15 | "time"
16 | )
17 |
18 | // ---------------------------------------------------------
19 | // EXERCISE: Days in a Month
20 | //
21 | // Print the number of days in a given month.
22 | //
23 | // RESTRICTIONS
24 | // 1. On a leap year, february should print 29. Otherwise, 28.
25 | //
26 | // Set your computer clock to 2020 to see whether it works.
27 | //
28 | // 2. It should work case-insensitive. See below.
29 | //
30 | // Search on Google: golang pkg strings ToLower
31 | //
32 | // 3. Get the current year using the time.Now()
33 | //
34 | // Search on Google: golang pkg time now year
35 | //
36 | //
37 | // EXPECTED OUTPUT
38 | //
39 | // -----------------------------------------
40 | // Your solution should not accept invalid months
41 | // -----------------------------------------
42 | // go run main.go
43 | // Give me a month name
44 | //
45 | // go run main.go sheep
46 | // "sheep" is not a month.
47 | //
48 | // -----------------------------------------
49 | // Your solution should handle the leap years
50 | // -----------------------------------------
51 | // go run main.go january
52 | // "january" has 31 days.
53 | //
54 | // go run main.go february
55 | // "february" has 28 days.
56 | //
57 | // go run main.go march
58 | // "march" has 31 days.
59 | //
60 | // go run main.go april
61 | // "april" has 30 days.
62 | //
63 | // go run main.go may
64 | // "may" has 31 days.
65 | //
66 | // go run main.go june
67 | // "june" has 30 days.
68 | //
69 | // go run main.go july
70 | // "july" has 31 days.
71 | //
72 | // go run main.go august
73 | // "august" has 31 days.
74 | //
75 | // go run main.go september
76 | // "september" has 30 days.
77 | //
78 | // go run main.go october
79 | // "october" has 31 days.
80 | //
81 | // go run main.go november
82 | // "november" has 30 days.
83 | //
84 | // go run main.go december
85 | // "december" has 31 days.
86 | //
87 | // -----------------------------------------
88 | // Your solution should be case insensitive
89 | // -----------------------------------------
90 | // go run main.go DECEMBER
91 | // "DECEMBER" has 31 days.
92 | //
93 | // go run main.go dEcEmBeR
94 | // "dEcEmBeR" has 31 days.
95 | // ---------------------------------------------------------
96 |
97 | func main() {
98 | args := os.Args
99 | if len(args) != 2 {
100 | fmt.Println("Give me a month name")
101 | return
102 | }
103 |
104 | inp := args[1]
105 | includeMonth := false
106 | months := map[string]time.Month{}
107 | for i := time.January; i <= time.December; i++ {
108 | if strings.ToLower(i.String()) == strings.ToLower(inp) {
109 | includeMonth = true
110 | break
111 | }
112 | months[i.String()] = i
113 | }
114 |
115 | if !includeMonth {
116 | fmt.Printf("%q is not a month.\n", inp)
117 | return
118 | }
119 |
120 | date := time.Date(
121 | time.Now().Year(),
122 | // Month Name From time.Month
123 | months[strings.Title(inp)],
124 | 32, 0, 0, 0, 0, time.UTC)
125 | fmt.Printf("%q has %d days.\n", inp, 32-date.Day())
126 |
127 | }
128 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/IOTA/07-iota-months/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Iota Months
15 | //
16 | // 1. Initialize the constants using iota.
17 | // 2. You should find the correct formula for iota.
18 | //
19 | // RESTRICTIONS
20 | // 1. Remove the initializer values from all constants.
21 | // 2. Then use iota once for initializing one of the
22 | // constants.
23 | //
24 | // EXPECTED OUTPUT
25 | // 9 10 11
26 | // ---------------------------------------------------------
27 |
28 | func main() {
29 | const (
30 | Nov = 11 - iota
31 | Oct
32 | Sep
33 | )
34 |
35 | fmt.Println(Sep, Oct, Nov)
36 | }
37 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/IOTA/08-iota-months-2/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Iota Months #2
15 | //
16 | // 1. Initialize multiple constants using iota.
17 | // 2. Please follow the instructions inside the code.
18 | //
19 | // EXPECTED OUTPUT
20 | // 1 2 3
21 | // ---------------------------------------------------------
22 |
23 | func main() {
24 | // HINT: This is a valid constant declaration
25 | // Blank-Identifier can be used in place of a name
26 | // const _ = iota
27 | // ^- this is just a name
28 |
29 | // Now, use iota and initialize the following constants
30 | // "automatically" to 1, 2, and 3 respectively.
31 | const (
32 | _ = iota
33 | Jan
34 | Feb
35 | Mar
36 | )
37 |
38 | // This should print: 1 2 3
39 | // Not: 0 1 2
40 | fmt.Println(Jan, Feb, Mar)
41 | }
42 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/IOTA/09-iota-seasons/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Iota Seasons
15 | //
16 | // Use iota to initialize the season constants.
17 | //
18 | // HINT
19 | // You can change the order of the constants.
20 | //
21 | // EXPECTED OUTPUT
22 | // 12 3 6 9
23 | // ---------------------------------------------------------
24 |
25 | func main() {
26 | // NOTE : You should remove all the initializers below
27 | // first. Then use iota to fix it.
28 | // const (
29 | // Winter = 12
30 | // Spring = 3
31 | // Summer = 6
32 | // Fall = 9
33 | // )
34 |
35 | const (
36 | Spring = (iota + 1) * 3
37 | Summer
38 | Fall
39 | Winter
40 | )
41 |
42 | fmt.Println(Winter, Spring, Summer, Fall)
43 | }
44 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/If Statement/01-age-seasons/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Age Seasons
15 | //
16 | // Let's start simple. Print the expected outputs,
17 | // depending on the age variable.
18 | //
19 | // EXPECTED OUTPUT
20 | // If age is greater than 60, print:
21 | // Getting older
22 | // If age is greater than 30, print:
23 | // Getting wiser
24 | // If age is greater than 20, print:
25 | // Adulthood
26 | // If age is greater than 10, print:
27 | // Young blood
28 | // Otherwise, print:
29 | // Booting up
30 | // ---------------------------------------------------------
31 |
32 | func main() {
33 | // Change this accordingly to produce the expected outputs
34 | age := 10
35 |
36 | var msg string
37 | // Type your if statement here.
38 | if age > 60 {
39 | msg = "Getting older"
40 | } else if age > 30 {
41 | msg = "Getting wiser"
42 | } else if age > 20 {
43 | msg = "Adulthood"
44 | } else if age > 10 {
45 | msg = "Young blood"
46 | } else {
47 | msg = "Booting up"
48 | }
49 |
50 | fmt.Println(msg)
51 | }
52 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/If Statement/02-simplify-it/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Simplify It
15 | //
16 | // Can you simplify the if statement inside the code below?
17 | //
18 | // When:
19 | // isSphere == true and
20 | // radius is equal or greater than 200
21 | //
22 | // It will print "It's a big sphere."
23 | //
24 | // Otherwise, it will print "I don't know."
25 | //
26 | // EXPECTED OUTPUT
27 | // It's a big sphere.
28 | // ---------------------------------------------------------
29 |
30 | func main() {
31 | // DO NOT TOUCH THIS
32 | isSphere, radius := true, 200
33 |
34 | // var big bool
35 |
36 | // if radius >= 50 {
37 | // if radius >= 100 {
38 | // if radius >= 200 {
39 | // big = true
40 | // }
41 | // }
42 | // }
43 |
44 | // if big != true {
45 | // fmt.Println("I don't know.")
46 | // } else if !(isSphere == false) {
47 | // fmt.Println("It's a big sphere.")
48 | // } else {
49 | // fmt.Println("I don't know.")
50 | // }
51 |
52 | if isSphere && radius >= 200 {
53 | fmt.Println("It's a big sphere.")
54 | } else {
55 | fmt.Println("I don't know.")
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/If Statement/03-arg-count/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | )
15 |
16 | // ---------------------------------------------------------
17 | // EXERCISE: Arg Count
18 | //
19 | // 1. Get arguments from command-line.
20 | // 2. Print the expected outputs below depending on the number
21 | // of arguments.
22 | //
23 | // EXPECTED OUTPUT
24 | // go run main.go
25 | // Give me args
26 | //
27 | // go run main.go hello
28 | // There is one: "hello"
29 | //
30 | // go run main.go hi there
31 | // There are two: "hi there"
32 | //
33 | // go run main.go I wanna be a gopher
34 | // There are 5 arguments
35 | // ---------------------------------------------------------
36 |
37 | func main() {
38 | ln := len(os.Args) - 1
39 |
40 | if ln == 0 {
41 | fmt.Println("Give me args")
42 | } else if ln == 1 {
43 | fmt.Println(`There is one: "hello"`)
44 | } else if ln == 2 {
45 | fmt.Println(`There are two: "hi there"`)
46 | } else {
47 | fmt.Println(`There are 5 arguments`)
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/If Statement/04-vowel-or-cons/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strings"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // EXERCISE: Vowel or Consonant
19 | //
20 | // Detect whether a letter is vowel or consonant.
21 | //
22 | // NOTE
23 | // y or w is called a semi-vowel.
24 | // Check out: https://www.merriam-webster.com/words-at-play/why-y-is-sometimes-a-vowel-usage
25 | // Check out: https://www.dictionary.com/e/w-vowel/
26 | //
27 | // HINT
28 | // + You can find the length of an argument using the len function.
29 | //
30 | // + len(os.Args[1]) will give you the length of the 1st argument.
31 | //
32 | // BONUS
33 | // Use strings.IndexAny function to detect the vowels.
34 | // Search on Google for: golang pkg strings IndexAny
35 | //
36 | // Furthermore, you can also use strings.ContainsAny. Check out: https://golang.org/pkg/strings/#ContainsAny
37 | //
38 | // EXPECTED OUTPUT
39 | // go run main.go
40 | // Give me a letter
41 | //
42 | // go run main.go hey
43 | // Give me a letter
44 | //
45 | // go run main.go a
46 | // "a" is a vowel.
47 | //
48 | // go run main.go y
49 | // "y" is sometimes a vowel, sometimes not.
50 | //
51 | // go run main.go w
52 | // "w" is sometimes a vowel, sometimes not.
53 | //
54 | // go run main.go x
55 | // "x" is a consonant.
56 | // ---------------------------------------------------------
57 |
58 | func main() {
59 | if len(os.Args)-1 == 1 && len(os.Args[1]) == 1 {
60 | inp := os.Args[1]
61 | const v, s = "aeiouwy", "wy"
62 | if strings.Contains(v, inp) {
63 | if strings.Contains(s, inp) {
64 | fmt.Printf("%q is sometimes a vowel, sometimes not.\n", inp)
65 | return
66 | }
67 | fmt.Printf("%q is a vowel.\n", inp)
68 | } else {
69 | fmt.Printf("%q is a consonant.\n", inp)
70 | }
71 | } else {
72 | fmt.Println("Give me a letter")
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/LOOP/01-dynamic-table/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strconv"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // EXERCISE: Dynamic Table
19 | //
20 | // Get the size of the table from the command-line
21 | // Passing 5 should create a 5x5 table
22 | // Passing 10 for a 10x10 table
23 | //
24 | // RESTRICTION
25 | // Solve this exercise without looking at the original
26 | // multiplication table exercise.
27 | //
28 | // HINT
29 | // There was a max constant in the original program.
30 | // That determines the size of the table.
31 | //
32 | // EXPECTED OUTPUT
33 | //
34 | // go run main.go
35 | // Give me the size of the table
36 | //
37 | // go run main.go -5
38 | // Wrong size
39 | //
40 | // go run main.go ABC
41 | // Wrong size
42 | //
43 | // go run main.go 1
44 | // X 0 1
45 | // 0 0 0
46 | // 1 0 1
47 | //
48 | // go run main.go 2
49 | // X 0 1 2
50 | // 0 0 0 0
51 | // 1 0 1 2
52 | // 2 0 2 4
53 | //
54 | // go run main.go 3
55 | // X 0 1 2 3
56 | // 0 0 0 0 0
57 | // 1 0 1 2 3
58 | // 2 0 2 4 6
59 | // 3 0 3 6 9
60 | // ---------------------------------------------------------
61 |
62 | func main() {
63 | args := os.Args
64 |
65 | if len(args) != 2 {
66 | fmt.Println("Give me the size of the table")
67 | return
68 | }
69 |
70 | size, err := strconv.Atoi(args[1])
71 | if err != nil || size < 0 {
72 | fmt.Println("Wrong size")
73 | return
74 | }
75 |
76 | for i := 0; i <= size; i++ {
77 | if i == 0 {
78 | fmt.Printf(" X")
79 | }
80 | fmt.Printf(" %2d", i)
81 | }
82 | for j := 0; j <= size; j++ {
83 | fmt.Println()
84 | fmt.Printf("%2d", j)
85 | for k := 0; k <= size; k++ {
86 | fmt.Printf(" %2d", j*k)
87 | }
88 | }
89 | fmt.Println()
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/LOOP/01-sum-the-numbers/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Sum the Numbers
15 | //
16 | // 1. By using a loop, sum the numbers between 1 and 10.
17 | // 2. Print the sum.
18 | //
19 | // EXPECTED OUTPUT
20 | // Sum: 55
21 | // ---------------------------------------------------------
22 |
23 | func main() {
24 | sum := 0
25 | for i := 1; i <= 10; i++ {
26 | sum += i
27 | }
28 | fmt.Printf("Sum: %d", sum)
29 | }
30 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/LOOP/02-math-tables/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strconv"
15 | "strings"
16 | )
17 |
18 | // ---------------------------------------------------------
19 | // EXERCISE: Math Tables
20 | //
21 | // Create division, addition and subtraction tables
22 | //
23 | // 1. Get the math operation and
24 | // the size of the table from the user
25 | //
26 | // 2. Print the table accordingly
27 | //
28 | // 3. Correctly handle the division by zero error
29 | //
30 | //
31 | // BONUS #1
32 | //
33 | // Use strings.IndexAny function to detect
34 | // the valid operations.
35 | //
36 | // Search on Google for: golang pkg strings IndexAny
37 | //
38 | // BONUS #2
39 | //
40 | // Add remainder operation as well (remainder table using %).
41 | //
42 | //
43 | // EXPECTED OUTPUT
44 | //
45 | // go run main.go
46 | // Usage: [op=*/+-] [size]
47 | //
48 | // go run main.go "*"
49 | // Size is missing
50 | // Usage: [op=*/+-] [size]
51 | //
52 | // go run main.go "%" 4
53 | // Invalid operator.
54 | // Valid ops one of: */+-
55 | //
56 | // go run main.go "*" 4
57 | // * 0 1 2 3 4
58 | // 0 0 0 0 0 0
59 | // 1 0 1 2 3 4
60 | // 2 0 2 4 6 8
61 | // 3 0 3 6 9 12
62 | // 4 0 4 8 12 16
63 | //
64 | // go run main.go "/" 4
65 | // / 0 1 2 3 4
66 | // 0 0 0 0 0 0
67 | // 1 0 1 0 0 0
68 | // 2 0 2 1 0 0
69 | // 3 0 3 1 1 0
70 | // 4 0 4 2 1 1
71 | //
72 | // go run main.go "+" 4
73 | // + 0 1 2 3 4
74 | // 0 0 1 2 3 4
75 | // 1 1 2 3 4 5
76 | // 2 2 3 4 5 6
77 | // 3 3 4 5 6 7
78 | // 4 4 5 6 7 8
79 | //
80 | // go run main.go "-" 4
81 | // - 0 1 2 3 4
82 | // 0 0 -1 -2 -3 -4
83 | // 1 1 0 -1 -2 -3
84 | // 2 2 1 0 -1 -2
85 | // 3 3 2 1 0 -1
86 | // 4 4 3 2 1 0
87 | //
88 | // BONUS:
89 | //
90 | // go run main.go "%" 4
91 | // % 0 1 2 3 4
92 | // 0 0 0 0 0 0
93 | // 1 0 0 1 1 1
94 | // 2 0 0 0 2 2
95 | // 3 0 0 1 0 3
96 | // 4 0 0 0 1 0
97 | //
98 | // NOTES:
99 | //
100 | // When running the program in Windows Git Bash, you might need
101 | // to escape the characters like this.
102 | //
103 | // This happens because those characters have special meaning.
104 | //
105 | // Division:
106 | // go run main.go // 4
107 | //
108 | // Multiplication and others:
109 | // (this is also necessary for non-Windows bashes):
110 | //
111 | // go run main.go "*" 4
112 | // ---------------------------------------------------------
113 |
114 | func main() {
115 | args := os.Args
116 | ops := "*/+-%"
117 |
118 | if len(args) != 3 {
119 | if len(args) == 2 {
120 | fmt.Println("Size is missing")
121 | }
122 | fmt.Printf("Usage: [op=%v] [size]\n", ops)
123 | return
124 | }
125 |
126 | if strings.IndexAny(ops, args[1]) < 0 {
127 | fmt.Println("Invalid operator.")
128 | fmt.Printf("Valid ops one of: %v\n", ops)
129 | return
130 | }
131 |
132 | size, err := strconv.Atoi(args[2])
133 | if err != nil {
134 | fmt.Println("Size is missing")
135 | fmt.Printf("Usage: [op=%v] [size]\n", ops)
136 | }
137 |
138 | for i := 0; i <= size; i++ {
139 | if i == 0 {
140 | fmt.Printf(" %v", args[1])
141 | }
142 | fmt.Printf(" %2d", i)
143 | }
144 | fmt.Println()
145 | for j := 0; j <= size; j++ {
146 | fmt.Printf("%2d", j)
147 | for k := 0; k <= size; k++ {
148 | switch args[1] {
149 | case "+":
150 | fmt.Printf(" %2d", j+k)
151 | case "-":
152 | fmt.Printf(" %2d", j-k)
153 | case "*":
154 | fmt.Printf(" %2d", j*k)
155 | case "/":
156 | if k != 0 {
157 | fmt.Printf(" %2d", j/k)
158 | } else {
159 | fmt.Printf(" %2d", 0)
160 | }
161 | case "%":
162 | if k != 0 {
163 | fmt.Printf(" %2d", j%k)
164 | } else {
165 | fmt.Printf(" %2d", 0)
166 | }
167 | }
168 | }
169 | fmt.Println()
170 | }
171 | }
172 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/LOOP/02-sum-the-numbers-verbose/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Sum the Numbers: Verbose Edition
15 | //
16 | // By using a loop, sum the numbers between 1 and 10.
17 | //
18 | // HINT
19 | // 1. For printing it as in the expected output, use Print
20 | // and Printf functions. They don't print a newline
21 | // automatically (unlike a Println).
22 | //
23 | // 2. Also, you need to use an if statement to prevent
24 | // printing the last plus sign.
25 | //
26 | // EXPECTED OUTPUT
27 | // 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
28 | // ---------------------------------------------------------
29 |
30 | func main() {
31 | output, sum := "", 0
32 | for i := 1; i <= 10; i++ {
33 | if i != 10 {
34 | output += fmt.Sprintf("%d + ", i)
35 | } else {
36 | sum += i
37 | output += fmt.Sprintf("%d = %d", i, sum)
38 | }
39 | sum += i
40 | }
41 | fmt.Println(output)
42 | }
43 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/LOOP/03-sum-up-to-n/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strconv"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // EXERCISE: Sum up to N
19 | //
20 | // 1. Get two numbers from the command-line: min and max
21 | // 2. Convert them to integers (using Atoi)
22 | // 3. By using a loop, sum the numbers between min and max
23 | //
24 | // RESTRICTIONS
25 | // 1. Be sure to handle the errors. So, if a user doesn't
26 | // pass enough arguments or she passes non-numerics,
27 | // then warn the user and exit from the program.
28 | //
29 | // 2. Also, check that, min < max.
30 | //
31 | // HINT
32 | // For converting the numbers, you can use `strconv.Atoi`.
33 | //
34 | // EXPECTED OUTPUT
35 | // Let's suppose that the user runs it like this:
36 | //
37 | // go run main.go 1 10
38 | //
39 | // Then it should print:
40 | //
41 | // 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
42 | // ---------------------------------------------------------
43 |
44 | func main() {
45 | args := os.Args
46 | if len(args) != 3 {
47 | fmt.Println("Please enter min and max")
48 | fmt.Println("[min] [max]")
49 | return
50 | }
51 |
52 | min, errMin := strconv.Atoi(args[1])
53 | max, errMax := strconv.Atoi(args[2])
54 |
55 | if errMin != nil && errMax != nil {
56 | fmt.Println("[min] [max] must be numeric value")
57 | return
58 | }
59 |
60 | if min > max {
61 | fmt.Println("[min] value must be greater than [max]")
62 | return
63 | }
64 |
65 | output, sum := "", 0
66 | for ; min <= max; min++ {
67 | if min != max {
68 | output += fmt.Sprintf("%d + ", min)
69 | } else {
70 | sum += min
71 | output += fmt.Sprintf("%d = %d", min, sum)
72 | }
73 | sum += min
74 | }
75 |
76 | fmt.Println(output)
77 | }
78 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/LOOP/04-only-evens/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strconv"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // EXERCISE: Only Evens
19 | //
20 | // 1. Extend the "Sum up to N" exercise
21 | // 2. Sum only the even numbers
22 | //
23 | // RESTRICTIONS
24 | // Skip odd numbers using the `continue` statement
25 | //
26 | // EXPECTED OUTPUT
27 | // Let's suppose that the user runs it like this:
28 | //
29 | // go run main.go 1 10
30 | //
31 | // Then it should print:
32 | //
33 | // 2 + 4 + 6 + 8 + 10 = 30
34 | // ---------------------------------------------------------
35 |
36 | func main() {
37 | args := os.Args
38 | if len(args) != 3 {
39 | fmt.Println("Please enter min and max")
40 | fmt.Println("[min] [max]")
41 | return
42 | }
43 |
44 | min, errMin := strconv.Atoi(args[1])
45 | max, errMax := strconv.Atoi(args[2])
46 |
47 | if errMin != nil && errMax != nil {
48 | fmt.Println("[min] [max] must be numeric value")
49 | return
50 | }
51 |
52 | if min > max {
53 | fmt.Println("[min] value must be greater than [max]")
54 | return
55 | }
56 |
57 | output, sum := "", 0
58 | for ; min <= max; min++ {
59 | if min%2 == 0 {
60 | if min != max {
61 | output += fmt.Sprintf("%d + ", min)
62 | } else {
63 | sum += min
64 | output += fmt.Sprintf("%d = %d", min, sum)
65 | }
66 | sum += min
67 | }
68 | }
69 |
70 | fmt.Println(output)
71 | }
72 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/LOOP/05-break-up/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strconv"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // EXERCISE: Break Up
19 | //
20 | // 1. Extend the "Only Evens" exercise
21 | // 2. This time, use an infinite loop.
22 | // 3. Break the loop when it reaches to the `max`.
23 | //
24 | // RESTRICTIONS
25 | // You should use the `break` statement once.
26 | //
27 | // HINT
28 | // Do not forget incrementing the `i` before the `continue`
29 | // statement and at the end of the loop.
30 | //
31 | // EXPECTED OUTPUT
32 | // go run main.go 1 10
33 | // 2 + 4 + 6 + 8 + 10 = 30
34 | // ---------------------------------------------------------
35 |
36 | func main() {
37 | args := os.Args
38 | if len(args) != 3 {
39 | fmt.Println("Please enter min and max")
40 | fmt.Println("[min] [max]")
41 | return
42 | }
43 |
44 | min, errMin := strconv.Atoi(args[1])
45 | max, errMax := strconv.Atoi(args[2])
46 |
47 | if errMin != nil && errMax != nil {
48 | fmt.Println("[min] [max] must be numeric value")
49 | return
50 | }
51 |
52 | if min > max {
53 | fmt.Println("[min] value must be greater than [max]")
54 | return
55 | }
56 |
57 | output, sum := "", 0
58 | for {
59 | if min <= max {
60 | if min%2 == 0 {
61 | if min != max {
62 | output += fmt.Sprintf("%d + ", min)
63 | } else {
64 | sum += min
65 | output += fmt.Sprintf("%d = %d", min, sum)
66 | }
67 | sum += min
68 | }
69 | } else {
70 | break
71 | }
72 | min++
73 | }
74 |
75 | fmt.Println(output)
76 | }
77 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/LOOP/06-infinite-kill/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "math/rand"
14 | "time"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // EXERCISE: Infinite Kill
19 | //
20 | // 1. Create an infinite loop
21 | // 2. On each step of the loop print a random character.
22 | // 3. And, sleep for 250 milliseconds.
23 | // 4. Run the program and wait a couple of seconds
24 | // then kill it using CTRL+C keys
25 | //
26 | // RESTRICTIONS
27 | // 1. Print one of those characters randomly: \ / | -
28 | // 2. Before printing a character print also this
29 | // escape sequence: \r
30 | //
31 | // Like this: "\r/", or this: "\r|", and so on...
32 | //
33 | // 3. NOTE : If you're using Go Playground, use "\f" instead of "\r"
34 | //
35 | // HINTS
36 | // 1. Use `time.Sleep` to sleep.
37 | // 2. You should pass a `time.Duration` value to it.
38 | // 3. Check out the Go online documentation for the
39 | // `Millisecond` constant.
40 | // 4. When printing, do not use a newline! Or a Println!
41 | // Use Print or Printf instead.
42 | //
43 | // NOTE
44 | // If this exercise is hard for you now, wait until the
45 | // lucky number lecture. Even then so, then just skip it.
46 | //
47 | // You can return back to it afterwards.
48 | //
49 | // EXPECTED OUTPUT
50 | // - The program should display the following messages in any order.
51 | // - And, the first character (\, -, /, or |) should be randomly
52 | // displayed.
53 | // - \r or \f sequence will clear the line.
54 | //
55 | // \ Please Wait. Processing....
56 | // - Please Wait. Processing....
57 | // / Please Wait. Processing....
58 | // | Please Wait. Processing....
59 | // ---------------------------------------------------------
60 |
61 | func main() {
62 | for {
63 | var c string
64 | switch rand.Intn(4) {
65 | case 0:
66 | c = "\\"
67 | case 1:
68 | c = "-"
69 | case 2:
70 | c = "|"
71 | case 3:
72 | c = "/"
73 | }
74 | fmt.Printf("\r%s Please Wait. Processing....", c)
75 | time.Sleep(time.Millisecond * 250)
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/PRINTF/01-print-your-age/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Print Your Age
15 | //
16 | // Print your age using Printf
17 | //
18 | // EXPECTED OUTPUT
19 | // I'm 30 years old.
20 | //
21 | // NOTE
22 | // You should change 30 to your age, of course.
23 | // ---------------------------------------------------------
24 |
25 | func main() {
26 | fmt.Printf("I'm %d years old.\n", 2023-1999)
27 | }
28 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/PRINTF/02-print-your-name-and-lastname/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Print Your Name and LastName
15 | //
16 | // Print your name and lastname using Printf
17 | //
18 | // EXPECTED OUTPUT
19 | // My name is Inanc and my lastname is Gumus.
20 | //
21 | // BONUS
22 | // Store the formatting specifier (first argument of Printf)
23 | // in a variable.
24 | // Then pass it to printf
25 | // ---------------------------------------------------------
26 |
27 | func main() {
28 | const (
29 | firstName = "Dibesh"
30 | lastName = "Subedi"
31 | )
32 |
33 | fmt.Printf("My name is %v and my lastname is %v.", firstName, lastName)
34 | // BONUS: Use a variable for the format specifier
35 |
36 | msg := "My name is %v and my lastname is %v."
37 | fmt.Printf(msg, firstName, lastName)
38 | }
39 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/PRINTF/03-false-claims/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: False Claims
15 | //
16 | // Use printf to print the expected output using a variable.
17 | //
18 | // EXPECTED OUTPUT
19 | // These are false claims.
20 | // ---------------------------------------------------------
21 |
22 | func main() {
23 | // UNCOMMENT THE FOLLOWING CODE
24 | // AND DO NOT CHANGE IT AFTERWARDS
25 | tf := false
26 |
27 | // TYPE YOUR CODE HERE
28 | fmt.Printf("These are %t claims.", tf)
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/PRINTF/04-print-the-temperature/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Print the Temperature
15 | //
16 | // Print the current temperature in your area using Printf
17 | //
18 | // NOTE
19 | // Do not use %v verb
20 | // Output "shouldn't" be like 29.500000
21 | //
22 | // EXPECTED OUTPUT
23 | // Temperature is 29.5 degrees.
24 | // ---------------------------------------------------------
25 |
26 | func main() {
27 | temp := 29.500000
28 | fmt.Printf("Temperature is %.1f degrees.", temp)
29 | }
30 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/PRINTF/05-double-quotes/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Double Quotes
15 | //
16 | // Print "hello world" with double-quotes using Printf
17 | // (As you see here)
18 | //
19 | // NOTE
20 | // Output "shouldn't" be just: hello world
21 | //
22 | // EXPECTED OUTPUT
23 | // "hello world"
24 | // ---------------------------------------------------------
25 |
26 | func main() {
27 | str := "hello world"
28 | fmt.Printf("%q", str)
29 | }
30 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/PRINTF/06-print-the-type/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Print the Type
15 | //
16 | // Print the type and value of 3 using fmt.Printf
17 | //
18 | // EXPECTED OUTPUT
19 | // Type of 3 is int
20 | // ---------------------------------------------------------
21 |
22 | func main() {
23 | val := 3
24 | fmt.Printf("Type of %d is %[1]T", val)
25 | }
26 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/PRINTF/07-print-the-type-2/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Print the Type #2
15 | //
16 | // Print the type and value of 3.14 using fmt.Printf
17 | //
18 | // EXPECTED OUTPUT
19 | // Type of 3.14 is float64
20 | // ---------------------------------------------------------
21 |
22 | func main() {
23 | val := 3.14
24 | fmt.Printf("Type of %2.f is %[1]T", val)
25 | }
26 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/PRINTF/08-print-the-type-3/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Print the Type #3
15 | //
16 | // Print the type and value of "hello" using fmt.Printf
17 | //
18 | // EXPECTED OUTPUT
19 | // Type of hello is string
20 | // ---------------------------------------------------------
21 |
22 | func main() {
23 | val := "hello"
24 | fmt.Printf("Type of %v is %[1]T", val)
25 | }
26 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/PRINTF/09-print-the-type-4/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Print the Type #4
15 | // Print the type and value of true using fmt.Printf
16 | //
17 | // EXPECTED OUTPUT
18 | // Type of true is bool
19 | // ---------------------------------------------------------
20 |
21 | func main() {
22 | val := true
23 | fmt.Printf("Type of %v is %[1]T", val)
24 | }
25 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/PRINTF/10-print-your-fullname/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | )
15 |
16 | // ---------------------------------------------------------
17 | // EXERCISE: Print Your Fullname
18 | //
19 | // 1. Get your name and lastname from the command-line
20 | // 2. Print them using Printf
21 | //
22 | // EXAMPLE INPUT
23 | // Inanc Gumus
24 | //
25 | // EXPECTED OUTPUT
26 | // Your name is Inanc and your lastname is Gumus.
27 | // ---------------------------------------------------------
28 |
29 | func main() {
30 | // BONUS: Use a variable for the format specifier
31 | name, lastname := os.Args[1], os.Args[2]
32 | msg := "Your name is %v and your lastname is %v.\n"
33 | fmt.Printf(msg, name, lastname)
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Pass Me Challenges Source Code/01-challenge/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | )
15 |
16 | // ---------------------------------------------------------
17 | // CHALLENGE #1
18 | // Create a user/password protected program.
19 | //
20 | // EXAMPLE USER
21 | // username: jack
22 | // password: 1888
23 | //
24 | // EXPECTED OUTPUT
25 | // go run main.go
26 | // Usage: [username] [password]
27 | //
28 | // go run main.go albert
29 | // Usage: [username] [password]
30 | //
31 | // go run main.go hacker 42
32 | // Access denied for "hacker".
33 | //
34 | // go run main.go jack 6475
35 | // Invalid password for "jack".
36 | //
37 | // go run main.go jack 1888
38 | // Access granted to "jack".
39 | // ---------------------------------------------------------
40 |
41 | func main() {
42 | if len(os.Args) != 3 {
43 | fmt.Println("Usage: [username] [password]")
44 | return
45 | }
46 | const (
47 | user = "jack"
48 | pwd = "1888"
49 | )
50 | username, password := os.Args[1], os.Args[2]
51 | if user == username {
52 | if pwd == password {
53 | fmt.Printf("Access granted to %q.\n", user)
54 | } else {
55 | fmt.Printf("Invalid password for %q.\n", user)
56 | }
57 | } else {
58 | fmt.Printf("Access denied for %q.\n", username)
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Pass Me Challenges Source Code/02-challenge/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | )
15 |
16 | // ---------------------------------------------------------
17 | // CHALLENGE #2
18 | // Add one more user to the PassMe program below.
19 | //
20 | // EXAMPLE USERS
21 | // username: jack
22 | // password: 1888
23 | //
24 | // username: inanc
25 | // password: 1879
26 | //
27 | // EXPECTED OUTPUT
28 | // go run main.go
29 | // Usage: [username] [password]
30 | //
31 | // go run main.go hacker 42
32 | // Access denied for "hacker".
33 | //
34 | // go run main.go jack 1888
35 | // Access granted to "jack".
36 | //
37 | // go run main.go inanc 1879
38 | // Access granted to "inanc".
39 | //
40 | // go run main.go jack 1879
41 | // Invalid password for "jack".
42 | //
43 | // go run main.go inanc 1888
44 | // Invalid password for "inanc".
45 | // ---------------------------------------------------------
46 |
47 | const (
48 | usage = "Usage: [username] [password]"
49 | errUser = "Access denied for %q.\n"
50 | errPwd = "Invalid password for %q.\n"
51 | accessOK = "Access granted to %q.\n"
52 | user1, user2 = "jack", "inanc"
53 | pass1, pass2 = "1888", "1879"
54 | )
55 |
56 | func main() {
57 | args := os.Args
58 |
59 | if len(args) != 3 {
60 | fmt.Println(usage)
61 | return
62 | }
63 |
64 | u, p := args[1], args[2]
65 |
66 | if u != user1 && u != user2 {
67 | fmt.Printf(errUser, u)
68 | } else if u == user1 && p == pass1 {
69 | fmt.Printf(accessOK, u)
70 | } else if u == user2 && p == pass2 {
71 | fmt.Printf(accessOK, u)
72 | } else {
73 | fmt.Printf(errPwd, u)
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Readme.md:
--------------------------------------------------------------------------------
1 | # Section 1
2 |
3 | 1. Variables
4 | - Make It Blue
5 | - Variables To Variables
6 | - Assign With Expressions
7 | - Find the Rectangle's Perimeter
8 | - Multi Assign
9 | - Multi Assign #2
10 | - Multi Short Func
11 | - Swapper
12 | - Swapper #2
13 | - Discard The File
14 | 2. Type-Conversion
15 | - Convert and Fix #1
16 | - Convert and Fix #2
17 | - Convert and Fix #3
18 | - Convert and Fix #4
19 | - Convert and Fix #5
20 | 3. Command Line Arguments
21 | - Count the Arguments
22 | - Print the Path
23 | - Print Your Name
24 | - Greet More People
25 | - Greet 5 People
26 | 4. Basic Strings
27 | - Windows Path
28 | - Print JSON
29 | - Raw Concat
30 | - Count the Chars
31 | - Improved Banger
32 | - ToLowercase
33 | - Trim It
34 | - Right Trim It
35 | 5. IOTA
36 | - Iota Months
37 | - Iota Months #2
38 | - Iota Seasons
39 | 6. PRINTF
40 | - Print Your Age
41 | - Print Your Name and LastName
42 | - False Claims
43 | - Print the Temperature
44 | - Double Quotes
45 | - Print the Type
46 | - Print the Type #2
47 | - Print the Type #3
48 | - Print the Type #4
49 | - Print Your Full name
50 | 7. If Statement
51 | - Age Seasons
52 | - Simplify It
53 | - Arg Count
54 | - Vowel or Consonant
55 | 8. Pass Me Challenges Source Code
56 | - Challenge #1
57 | - Challenge #2
58 | 9. Error Handling
59 | - Movie Ratings
60 | - Odd or Even
61 | - Leap Year
62 | - Simplify the Leap Year
63 | - Days in a Month
64 | 10. Switch Statement
65 | - Richter Scale
66 | - Richter Scale #2
67 | - Convert
68 | - String Manipulator
69 | - Days in a Month
70 | 11. LOOP
71 | - Dynamic Table
72 | - Math Table
73 | - Sum the Numbers
74 | - Sum the Numbers: Verbose Edition
75 | - Sum up to N
76 | - Only Evens
77 | - Break Up
78 | - Infinite Kill
79 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/SWITCH/01-richter-scale/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strconv"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // STORY
19 | // You're curious about the richter scales. When reporters
20 | // say: "There's been a 5.5 magnitude earthquake",
21 | //
22 | // You want to know what that means.
23 | //
24 | // So, you've decided to write a program to do that for you.
25 | //
26 | // EXERCISE: Richter Scale
27 | //
28 | // 1. Get the earthquake magnitude from the command-line.
29 | // 2. Display its corresponding description.
30 | //
31 | // ---------------------------------------------------------
32 | // MAGNITUDE DESCRIPTION
33 | // ---------------------------------------------------------
34 | // Less than 2.0 micro
35 | // 2.0 and less than 3.0 very minor
36 | // 3.0 and less than 4.0 minor
37 | // 4.0 and less than 5.0 light
38 | // 5.0 and less than 6.0 moderate
39 | // 6.0 and less than 7.0 strong
40 | // 7.0 and less than 8.0 major
41 | // 8.0 and less than 10.0 great
42 | // 10.0 or more massive
43 | //
44 | // EXPECTED OUTPUT
45 | // go run main.go
46 | // Give me the magnitude of the earthquake.
47 | //
48 | // go run main.go ABC
49 | // I couldn't get that, sorry.
50 | //
51 | // go run main.go 0.5
52 | // 0.50 is micro
53 | //
54 | // go run main.go 2.5
55 | // 2.50 is very minor
56 | //
57 | // go run main.go 3
58 | // 3.00 is minor
59 | //
60 | // go run main.go 4.5
61 | // 4.50 is light
62 | //
63 | // go run main.go 5
64 | // 5.00 is moderate
65 | //
66 | // go run main.go 6
67 | // 6.00 is strong
68 | //
69 | // go run main.go 7
70 | // 7.00 is major
71 | //
72 | // go run main.go 8
73 | // 8.00 is great
74 | //
75 | // go run main.go 11
76 | // 11.00 is massive
77 | // ---------------------------------------------------------
78 |
79 | func main() {
80 | args := os.Args
81 | if len(args) != 2 {
82 | fmt.Println("Give me the magnitude of the earthquake.")
83 | return
84 | }
85 | input := args[1]
86 | var magnitude string
87 | richter, err := strconv.ParseFloat(input, 32)
88 | if err != nil {
89 | fmt.Println("I couldn't get that, sorry.")
90 | return
91 | }
92 | switch richter > 0 {
93 | case richter < 2:
94 | magnitude = "micro"
95 | case richter >= 2 && richter < 3:
96 | magnitude = "very minor"
97 | case richter >= 3 && richter < 4:
98 | magnitude = "minor"
99 | case richter >= 4 && richter < 5:
100 | magnitude = "light"
101 | case richter >= 5 && richter < 6:
102 | magnitude = "moderate"
103 | case richter >= 6 && richter < 7:
104 | magnitude = "strong"
105 | case richter >= 7 && richter < 8:
106 | magnitude = "major"
107 | case richter >= 8 && richter < 10:
108 | magnitude = "great"
109 | default:
110 | magnitude = "massive"
111 | }
112 | fmt.Printf("%v is %v.\n", input, magnitude)
113 |
114 | }
115 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/SWITCH/02-richter-scale-2/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strconv"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // EXERCISE: Richter Scale #2
19 | //
20 | // Repeat the previous exercise.
21 | //
22 | // But, this time, get the description and print the
23 | // corresponding richter scale.
24 | //
25 | // See the expected outputs.
26 | //
27 | // ---------------------------------------------------------
28 | // MAGNITUDE DESCRIPTION
29 | // ---------------------------------------------------------
30 | // Less than 2.0 micro
31 | // 2.0 to less than 3.0 very minor
32 | // 3.0 to less than 4.0 minor
33 | // 4.0 to less than 5.0 light
34 | // 5.0 to less than 6.0 moderate
35 | // 6.0 to less than 7.0 strong
36 | // 7.0 to less than 8.0 major
37 | // 8.0 to less than 10.0 great
38 | // 10.0 or more massive
39 | //
40 | // EXPECTED OUTPUT
41 | // go run main.go
42 | // Tell me the magnitude of the earthquake in human terms.
43 | //
44 | // go run main.go alien
45 | // alien's richter scale is unknown
46 | //
47 | // go run main.go micro
48 | // micro's richter scale is less than 2.0
49 | //
50 | // go run main.go "very minor"
51 | // very minor's richter scale is 2 - 2.9
52 | //
53 | // go run main.go minor
54 | // minor's richter scale is 3 - 3.9
55 | //
56 | // go run main.go light
57 | // light's richter scale is 4 - 4.9
58 | //
59 | // go run main.go moderate
60 | // moderate's richter scale is 5 - 5.9
61 | //
62 | // go run main.go strong
63 | // strong's richter scale is 6 - 6.9
64 | //
65 | // go run main.go major
66 | // major's richter scale is 7 - 7.9
67 | //
68 | // go run main.go great
69 | // great's richter scale is 8 - 9.9
70 | //
71 | // go run main.go massive
72 | // massive's richter scale is 10+
73 | // ---------------------------------------------------------
74 |
75 | func main() {
76 | args := os.Args
77 | if len(args) != 2 {
78 | fmt.Println("Tell me the magnitude of the earthquake in human terms.")
79 | return
80 | }
81 | input := args[1]
82 | var (
83 | magnitude string
84 | ranges string
85 | )
86 | richter, err := strconv.ParseFloat(input, 32)
87 | if err != nil {
88 | fmt.Printf("%v's richter scale is unknown.\n", input)
89 | return
90 | }
91 | switch {
92 | case richter < 2:
93 | magnitude = "micro"
94 | ranges = "less than 2.0"
95 | case richter >= 2 && richter < 3:
96 | magnitude = "very minor"
97 | ranges = "2 - 2.9"
98 | case richter >= 3 && richter < 4:
99 | magnitude = "minor"
100 | ranges = "3 - 3.9"
101 | case richter >= 4 && richter < 5:
102 | magnitude = "light"
103 | ranges = "4 - 4.9"
104 | case richter >= 5 && richter < 6:
105 | magnitude = "moderate"
106 | ranges = "5 - 5.9"
107 | case richter >= 6 && richter < 7:
108 | magnitude = "strong"
109 | ranges = "6 - 6.9"
110 | case richter >= 7 && richter < 8:
111 | magnitude = "major"
112 | ranges = "7 - 7.9"
113 | case richter >= 8 && richter < 10:
114 | magnitude = "great"
115 | ranges = "8 - 9.9"
116 | default:
117 | magnitude = "massive"
118 | ranges = "10+"
119 | }
120 | fmt.Printf("%v's richter scale is %v.\n", magnitude, ranges)
121 | }
122 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/SWITCH/03-convert/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | )
15 |
16 | // ---------------------------------------------------------
17 | // EXERCISE: Convert
18 | //
19 | // Convert the if statement to a switch statement.
20 | // ---------------------------------------------------------
21 |
22 | const (
23 | usage = "Usage: [username] [password]"
24 | errUser = "Access denied for %q.\n"
25 | errPwd = "Invalid password for %q.\n"
26 | accessOK = "Access granted to %q.\n"
27 | user, user2 = "jack", "inanc"
28 | pass, pass2 = "1888", "1879"
29 | )
30 |
31 | func main() {
32 | args := os.Args
33 |
34 | if len(args) != 3 {
35 | fmt.Println(usage)
36 | return
37 | }
38 |
39 | u, p := args[1], args[2]
40 | switch {
41 | case u != user && u != user2:
42 | fmt.Printf(errUser, u)
43 | case u == user && p == pass:
44 | fallthrough
45 | case u == user2 && p == pass2:
46 | fmt.Printf(accessOK, u)
47 | default:
48 | fmt.Printf(errPwd, u)
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/SWITCH/04-string-manipulator/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strings"
15 | )
16 |
17 | // ---------------------------------------------------------
18 | // STORY
19 | // You want to write a program that will manipulate a
20 | // given string to uppercase, lowercase, and title case.
21 | //
22 | // EXERCISE: String Manipulator
23 | //
24 | // 1. Get the operation as the first argument.
25 | //
26 | // 2. Get the string to be manipulated as the 2nd argument.
27 | //
28 | // HINT
29 | // You can find the manipulation functions in the strings
30 | // package Go documentation (ToLower, ToUpper, Title).
31 | //
32 | // EXPECTED OUTPUT
33 | //
34 | // go run main.go
35 | // [command] [string]
36 | //
37 | // Available commands: lower, upper and title
38 | //
39 | // go run main.go lower 'OMG!'
40 | // omg!
41 | //
42 | // go run main.go upper 'omg!'
43 | // OMG!
44 | //
45 | // go run main.go title "mr. charles darwin"
46 | // Mr. Charles Darwin
47 | //
48 | // go run main.go genius "mr. charles darwin"
49 | // Unknown command: "genius"
50 | // ---------------------------------------------------------
51 |
52 | func main() {
53 | args := os.Args
54 | if len(args) != 3 {
55 | fmt.Println()
56 | fmt.Println(`[command] [string]
57 | Available commands: lower, upper and title`)
58 | return
59 | }
60 | cmd, char := args[1], args[2]
61 | switch strings.ToLower(cmd) {
62 | case "lower":
63 | fmt.Printf("%v\n", strings.ToLower(char))
64 | case "upper":
65 | fmt.Printf("%v\n", strings.ToUpper(char))
66 | case "title":
67 | fmt.Printf("%v\n", strings.Title(char))
68 | default:
69 | fmt.Printf("Unknown command: %q\n", cmd)
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/SWITCH/05-days-in-month/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "os"
14 | "strings"
15 | "time"
16 | )
17 |
18 | // ---------------------------------------------------------
19 | // EXERCISE: Days in a Month
20 | //
21 | // Refactor the previous exercise from the if statement
22 | // section.
23 | //
24 | // "Print the number of days in a given month."
25 | //
26 | // Use a switch statement instead of if statements.
27 | // ---------------------------------------------------------
28 |
29 | func main() {
30 | if len(os.Args) != 2 {
31 | fmt.Println("Give me a month name")
32 | return
33 | }
34 |
35 | year := time.Now().Year()
36 | leap := year%4 == 0 && (year%100 != 0 || year%400 == 0)
37 |
38 | days, month := 28, os.Args[1]
39 |
40 | switch m := strings.ToLower(month); m {
41 | case "april", "june", "september", "november":
42 | days = 30
43 | case "january", "march", "may", "july",
44 | "august", "october", "december":
45 | days = 31
46 | case "february":
47 | if leap {
48 | days = 29
49 | }
50 | default:
51 | fmt.Printf("%q is not a month.\n", month)
52 | return
53 | }
54 |
55 | fmt.Printf("%q has %d days.\n", month, days)
56 | }
57 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Type-Conversion/01-convert-and-fix/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Convert and Fix
15 | //
16 | // Fix the code by using the conversion expression.
17 | //
18 | // EXPECTED OUTPUT
19 | // 15.5
20 | // ---------------------------------------------------------
21 |
22 | func main() {
23 | a, b := 10, 5.5
24 | fmt.Println(float64(a) + b)
25 | }
26 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Type-Conversion/02-convert-and-fix-2/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Convert and Fix #2
15 | //
16 | // Fix the code by using the conversion expression.
17 | //
18 | // EXPECTED OUTPUT
19 | // 10.5
20 | // ---------------------------------------------------------
21 |
22 | func main() {
23 | a, b := 10, 5.5
24 | a = int(b)
25 | fmt.Println(float64(a) + b)
26 | }
27 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Type-Conversion/03-convert-and-fix-3/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Convert and Fix #3
15 | //
16 | // Fix the code.
17 | //
18 | // EXPECTED OUTPUT
19 | // 5.5
20 | // ---------------------------------------------------------
21 |
22 | func main() {
23 | fmt.Println(float64(5.5))
24 | }
25 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Type-Conversion/04-convert-and-fix-4/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Convert and Fix #4
15 | //
16 | // Fix the code.
17 | //
18 | // EXPECTED OUTPUT
19 | // 9.5
20 | // ---------------------------------------------------------
21 |
22 | func main() {
23 | age := 2
24 | fmt.Println(float64(7.5) + float64(age))
25 | }
26 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Type-Conversion/05-convert-and-fix-5/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Convert and Fix #5
15 | //
16 | // Fix the code.
17 | //
18 | // HINTS
19 | // maximum of int8 can be 127
20 | // maximum of int16 can be 32767
21 | //
22 | // EXPECTED OUTPUT
23 | // 1127
24 | // ---------------------------------------------------------
25 |
26 | func main() {
27 | // DO NOT TOUCH THESE VARIABLES
28 | min := int8(127)
29 | max := int16(1000)
30 |
31 | // FIX THE CODE HERE
32 | fmt.Println(max + int16(min))
33 | }
34 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Variables/01-make-it-blue/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | // ---------------------------------------------------------
12 | // EXERCISE: Make It Blue
13 | //
14 | // 1. Change `color` variable's value to "blue"
15 | //
16 | // 2. Print it
17 | //
18 | // EXPECTED OUTPUT
19 | // blue
20 | // ---------------------------------------------------------
21 |
22 | func main() {
23 | // UNCOMMENT THE CODE BELOW:
24 | color := "green"
25 | // ADD YOUR CODE BELOW:
26 | color = "blue"
27 | println(color)
28 | }
29 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Variables/02-vars-to-vars/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Variables To Variables
15 | //
16 | // 1. Change the value of `color` variable to "dark green"
17 | //
18 | // 2. Do not assign "dark green" to `color` directly
19 | //
20 | // Instead, use the `color` variable again
21 | // while assigning to `color`
22 | //
23 | // 3. Print it
24 | //
25 | // RESTRICTIONS
26 | // WRONG ANSWER, DO NOT DO THIS:
27 | // `color = "dark green"`
28 | //
29 | // HINT
30 | // + operator can concatenate string values
31 | //
32 | // Example:
33 | //
34 | // "h" + "e" + "y" returns "hey"
35 | //
36 | // EXPECTED OUTPUT
37 | // dark green
38 | // ---------------------------------------------------------
39 |
40 | func main() {
41 |
42 | color := "green"
43 |
44 | // ADD YOUR CODE BELOW
45 |
46 | color = "dark " + color
47 |
48 | fmt.Println(color)
49 | }
50 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Variables/03-assign-with-expressions/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Assign With Expressions
15 | //
16 | // 1. Multiply 3.14 with 2 and assign it to `n` variable
17 | //
18 | // 2. Print the `n` variable
19 | //
20 | // HINT
21 | // Example: 3 * 2 = 6
22 | // * is the product operator (it multiplies numbers)
23 | //
24 | // EXPECTED OUTPUT
25 | // 6.28
26 | // ---------------------------------------------------------
27 |
28 | func main() {
29 | // DON'T TOUCH THIS
30 |
31 | // Declares a new float64 variable
32 | // 0. means 0.0
33 | n := 0.
34 |
35 | // ADD YOUR CODE BELOW
36 |
37 | n = 3.4 * 2
38 |
39 | fmt.Println(n)
40 | }
41 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Variables/04-find-the-rectangle-perimeter/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Find the Rectangle's Perimeter
15 | //
16 | // 1. Find the perimeter of a rectangle
17 | // Its width is 5
18 | // Its height is 6
19 | //
20 | // 2. Assign the result to the `perimeter` variable
21 | //
22 | // 3. Print the `perimeter` variable
23 | //
24 | // HINT
25 | // Formula = 2 times the width and height
26 | //
27 | // EXPECTED OUTPUT
28 | // 22
29 | //
30 | // BONUS
31 | // Find more formulas here and calculate them in new programs
32 | // https://www.mathsisfun.com/area.html
33 | // ---------------------------------------------------------
34 |
35 | func main() {
36 | // UNCOMMENT THE CODE BELOW:
37 |
38 | var (
39 | perimeter int
40 | width, height = 5, 6
41 | )
42 |
43 | // USE THE VARIABLES ABOVE WHEN CALCULATING YOUR RESULT
44 | perimeter = 2 * (width + height)
45 |
46 | // ADD YOUR CODE BELOW
47 | fmt.Println(perimeter)
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Variables/05-multi-assign/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Multi Assign
15 | //
16 | // 1. Assign "go" to `lang` variable
17 | // and assign 2 to `version` variable
18 | // using a multiple assignment statement
19 | //
20 | // 2. Print the variables
21 | //
22 | // EXPECTED OUTPUT
23 | // go version 2
24 | // ---------------------------------------------------------
25 |
26 | func main() {
27 | // DO NOT TOUCH THIS
28 | var (
29 | lang string
30 | version int
31 | )
32 |
33 | // ADD YOUR CODE BELOW
34 |
35 | lang, version = "go", 2
36 |
37 | // DO NOT TOUCH THIS
38 | fmt.Println(lang, "version", version)
39 | }
40 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Variables/06-multi-assign-2/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Multi Assign #2
15 | //
16 | // 1. Assign the correct values to the variables
17 | // to match to the EXPECTED OUTPUT below
18 | //
19 | // 2. Print the variables
20 | //
21 | // HINT
22 | // Use multiple Println calls to print each sentence.
23 | //
24 | // EXPECTED OUTPUT
25 | // Air is good on Mars
26 | // It's true
27 | // It is 19.5 degrees
28 | // ---------------------------------------------------------
29 |
30 | func main() {
31 | // UNCOMMENT THE CODE BELOW:
32 |
33 | var (
34 | planet string
35 | isTrue bool
36 | temp float64
37 | )
38 |
39 | // ADD YOUR CODE BELOW
40 | planet, isTrue, temp = "Mars", true, 19.5
41 |
42 | fmt.Println("Air is good on", planet)
43 | fmt.Println("It's", isTrue)
44 | fmt.Println("It is", temp, "degrees")
45 | }
46 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Variables/07-multi-short-func/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Multi Short Func
15 | //
16 | // 1. Declare two variables using multiple short declaration syntax
17 | //
18 | // 2. Initialize the variables using `multi` function below
19 | //
20 | // 3. Discard the 1st variable's value in the declaration
21 | //
22 | // 4. Print only the 2nd variable
23 | //
24 | // NOTE
25 | // You should use `multi` function
26 | // while initializing the variables
27 | //
28 | // EXPECTED OUTPUT
29 | // 4
30 | // ---------------------------------------------------------
31 |
32 | func main() {
33 | // ADD YOUR DECLARATIONS HERE
34 | _, b := multi()
35 |
36 | // THEN UNCOMMENT THE CODE BELOW
37 |
38 | fmt.Println(b)
39 | }
40 |
41 | // multi is a function that returns multiple int values
42 | func multi() (int, int) {
43 | return 5, 4
44 | }
45 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Variables/08-swapper/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Swapper
15 | //
16 | // 1. Change `color` to "orange"
17 | // and `color2` to "green" at the same time
18 | //
19 | // (use multiple-assignment)
20 | //
21 | // 2. Print the variables
22 | //
23 | // EXPECTED OUTPUT
24 | // orange green
25 | // ---------------------------------------------------------
26 |
27 | func main() {
28 | // UNCOMMENT THE CODE BELOW:
29 |
30 | color, color2 := "red", "blue"
31 |
32 | color, color2 = "orange", "green"
33 |
34 | fmt.Println(color, color2)
35 | }
36 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Variables/09-swapper-2/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import "fmt"
12 |
13 | // ---------------------------------------------------------
14 | // EXERCISE: Swapper #2
15 | //
16 | // 1. Swap the values of `red` and `blue` variables
17 | //
18 | // 2. Print them
19 | //
20 | // EXPECTED OUTPUT
21 | // blue red
22 | // ---------------------------------------------------------
23 |
24 | func main() {
25 | // UNCOMMENT THE CODE BELOW:
26 |
27 | red, blue := "red", "blue"
28 | red, blue = blue, red
29 | fmt.Println(red, blue)
30 | }
31 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 1/Variables/10-discard-the-file/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "path"
14 | )
15 |
16 | // ---------------------------------------------------------
17 | // EXERCISE: Discard The File
18 | //
19 | // 1. Print only the directory using `path.Split`
20 | //
21 | // 2. Discard the file part
22 | //
23 | // RESTRICTION
24 | // Use short declaration
25 | //
26 | // EXPECTED OUTPUT
27 | // secret/
28 | // ---------------------------------------------------------
29 |
30 | func main() {
31 | // UNCOMMENT THE CODE BELOW:
32 |
33 | dir, _ := path.Split("secret/file.txt")
34 | fmt.Println(dir)
35 | }
36 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 2/02-random-messages/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "math/rand"
14 | "os"
15 | "strconv"
16 | "time"
17 | )
18 |
19 | // ---------------------------------------------------------
20 | // EXERCISE: Random Messages
21 | //
22 | // Display a few different won and lost messages "randomly".
23 | //
24 | // HINTS
25 | // 1. You can use a switch statement to do that.
26 | // 2. Set its condition to the random number generator.
27 | // 3. I would use a short switch.
28 | //
29 | // EXAMPLES
30 | // The Player wins: then randomly print one of these:
31 | //
32 | // go run main.go 5
33 | // YOU WON
34 | // go run main.go 5
35 | // YOU'RE AWESOME
36 | //
37 | // The Player loses: then randomly print one of these:
38 | //
39 | // go run main.go 5
40 | // LOSER!
41 | // go run main.go 5
42 | // YOU LOST. TRY AGAIN?
43 | // ---------------------------------------------------------
44 |
45 | const (
46 | maxTurns = 5 // less is more difficult
47 | usage = `Welcome to the Lucky Number Game! 🍀
48 |
49 | The program will pick %d random numbers.
50 | Your mission is to guess one of those numbers.
51 |
52 | The greater your number is, harder it gets.
53 |
54 | Wanna play?
55 | `
56 | )
57 |
58 | func main() {
59 | rand.Seed(time.Now().UnixNano())
60 | args := os.Args[1:]
61 |
62 | if len(args) != 1 {
63 | fmt.Printf(usage, maxTurns)
64 | return
65 | }
66 |
67 | guess, err := strconv.Atoi(args[0])
68 | if err != nil {
69 | fmt.Println("Not a number.")
70 | return
71 | }
72 |
73 | if guess <= 0 {
74 | fmt.Println("Please pick a positive number.")
75 | return
76 | }
77 |
78 | for i := 1; i <= maxTurns; i++ {
79 | rnd := rand.Intn(guess) + 1
80 |
81 | if rnd != guess {
82 | continue
83 | }
84 |
85 | if rnd == guess {
86 | switch rand.Intn(3) {
87 | case 0:
88 | fmt.Println("🎉 YOU WIN!")
89 | case 1:
90 | fmt.Println("🎉 YOU'RE AWESOME!")
91 | case 2:
92 | fmt.Println("🎉 PERFECT!")
93 | }
94 | return
95 | }
96 | }
97 |
98 | msg := "👻 YOU LOST..."
99 | switch rand.Intn(2) {
100 | case 0:
101 | msg += "Try again?"
102 | case 1:
103 | msg += "Better Luck Next Time 😜"
104 | }
105 |
106 | fmt.Println(msg)
107 | }
108 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 2/03-double-guesses/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "math/rand"
14 | "os"
15 | "strconv"
16 | "time"
17 | )
18 |
19 | // ---------------------------------------------------------
20 | // EXERCISE: Double Guesses
21 | //
22 | // Let the player guess two numbers instead of one.
23 | //
24 | // HINT:
25 | // Generate random numbers using the greatest number
26 | // among the guessed numbers.
27 | //
28 | // EXAMPLES
29 | // go run main.go 5 6
30 | // Player wins if the random number is either 5 or 6.
31 | // ---------------------------------------------------------
32 |
33 | const (
34 | maxTurns = 5 // less is more difficult
35 | usage = `Welcome to the Lucky Number Game! 🍀
36 |
37 | The program will pick %d random numbers twice.
38 | Your mission is to guess two numbers which will match those numbers.
39 |
40 | The greater your number is, harder it gets.
41 |
42 | Wanna play?
43 | `
44 | )
45 |
46 | func main() {
47 | var guess []int
48 |
49 | rand.Seed(time.Now().UnixNano())
50 | args := os.Args[1:]
51 |
52 | if len(args) != 2 {
53 | fmt.Printf(usage, maxTurns)
54 | return
55 | }
56 |
57 | for i := 0; i < 2; i++ {
58 | g, err := strconv.Atoi(args[i])
59 | if err != nil {
60 | fmt.Println("Not a number:", err)
61 | return
62 | }
63 | if g <= 0 {
64 | fmt.Printf("%d is not a positive number.\n", g)
65 | return
66 | }
67 | guess = append(guess, g)
68 | }
69 |
70 | for i := 1; i <= maxTurns; i++ {
71 | num1 := rand.Intn(guess[0]) + 1
72 | num2 := rand.Intn(guess[1]) + 1
73 |
74 | if num1 != guess[0] || num2 != guess[1] {
75 | continue
76 | }
77 |
78 | if num1 == guess[0] || num2 == guess[0] {
79 | switch rand.Intn(3) {
80 | case 0:
81 | fmt.Println("🎉 YOU WIN!")
82 | case 1:
83 | fmt.Println("🎉 YOU'RE AWESOME!")
84 | case 2:
85 | fmt.Println("🎉 PERFECT!")
86 | }
87 | return
88 | }
89 | }
90 |
91 | msg := "👻 YOU LOST..."
92 | switch rand.Intn(2) {
93 | case 0:
94 | msg += "Try again?"
95 | case 1:
96 | msg += "Better Luck Next Time 😜"
97 | }
98 |
99 | fmt.Println(msg)
100 | }
101 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 2/04-verbose-mode/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "math/rand"
14 | "os"
15 | "strconv"
16 | "time"
17 | )
18 |
19 | // ---------------------------------------------------------
20 | // EXERCISE: Verbose Mode
21 | //
22 | // When the player runs the game like this:
23 | //
24 | // go run main.go -v 4
25 | //
26 | // Display each generated random number:
27 |
28 | // 1 3 4 🎉 YOU WIN!
29 | //
30 | // In this example, computer picks 1, 3, and 4. And the
31 | // player wins.
32 | //
33 | // HINT
34 | // You need to get and interpret the command-line arguments.
35 | // ---------------------------------------------------------
36 |
37 | const (
38 | maxTurns = 5 // less is more difficult
39 | usage = `Welcome to the Lucky Number Game! 🍀
40 |
41 | The program will pick %d random numbers.
42 | Your mission is to guess one of those numbers.
43 |
44 | The greater your number is, harder it gets.
45 |
46 | Wanna play?
47 |
48 | (Provide -v flag to see the picked numbers.)
49 | `
50 | )
51 |
52 | func main() {
53 | rand.Seed(time.Now().UnixNano())
54 | args := os.Args[1:]
55 |
56 | if len(args) != 2 {
57 | fmt.Printf(usage, maxTurns)
58 | return
59 | }
60 |
61 | v := args[0] == "-v"
62 | guess, err := strconv.Atoi(args[1])
63 | if err != nil {
64 | fmt.Println("Not a number:", err)
65 | return
66 | }
67 |
68 | if guess <= 0 {
69 | fmt.Printf("%d is not a positive number.\n", guess)
70 | return
71 | }
72 |
73 | ite := ""
74 |
75 | for i := 1; i <= maxTurns; i++ {
76 | num := rand.Intn(guess) + 1
77 | ite += " " + strconv.Itoa(num)
78 | if num != guess {
79 | continue
80 | }
81 | if num == guess {
82 | switch rand.Intn(3) {
83 | case 0:
84 | if v {
85 | fmt.Println(ite, "🎉 YOU WIN!")
86 | } else {
87 | fmt.Println("🎉 YOU WIN!")
88 | }
89 | case 1:
90 | if v {
91 | fmt.Println(ite, "🎉 YOU'RE AWESOME!")
92 | } else {
93 | fmt.Println("🎉 YOU'RE AWESOME!")
94 | }
95 | case 2:
96 | if v {
97 | fmt.Println(ite, "🎉 PERFECT!")
98 | } else {
99 | fmt.Println("🎉 PERFECT!")
100 | }
101 | }
102 | return
103 | }
104 | }
105 |
106 | msg := "👻 YOU LOST..."
107 | switch rand.Intn(2) {
108 | case 0:
109 | msg += "Try again?"
110 | case 1:
111 | msg += "Better Luck Next Time 😜"
112 | }
113 |
114 | if v {
115 | fmt.Println(ite, msg)
116 | } else {
117 | fmt.Println(msg)
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 2/05-enough-picks/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "math/rand"
14 | "os"
15 | "strconv"
16 | "time"
17 | )
18 |
19 | // ---------------------------------------------------------
20 | // EXERCISE: Enough Picks
21 | //
22 | // If the player's guess number is below 10;
23 | // then make sure that the computer generates a random
24 | // number between 0 and 10.
25 | //
26 | // However, if the guess number is above 10; then the
27 | // computer should generate the numbers
28 | // between 0 and the guess number.
29 | //
30 | // WHY?
31 | // This way the game will be harder.
32 | //
33 | // Because, in the current version of the game, if
34 | // the player's guess number is for example 3; then the
35 | // computer picks a random number between 0 and 3.
36 | //
37 | // So, currently a player can easily win the game.
38 | //
39 | // EXAMPLE
40 | // Suppose that the player runs the game like this:
41 | // go run main.go 9
42 | //
43 | // Or like this:
44 | // go run main.go 2
45 | //
46 | // Then the computer should pick a random number
47 | // between 0-10.
48 | //
49 | // Or, if the player runs it like this:
50 | // go run main.go 15
51 | //
52 | // Then the computer should pick a random number
53 | // between 0-15.
54 | // ---------------------------------------------------------
55 |
56 | const (
57 | maxTurns = 5 // less is more difficult
58 | usage = `Welcome to the Lucky Number Game! 🍀
59 |
60 | The program will pick %d random numbers.
61 | Your mission is to guess one of those numbers.
62 |
63 | The greater your number is, harder it gets.
64 |
65 | Wanna play?
66 | `
67 | )
68 |
69 | func main() {
70 | args := os.Args[1:]
71 | rand.Seed(time.Now().UnixNano())
72 |
73 | if len(args) != 1 {
74 | fmt.Println("Please Enter Number 😢.")
75 | return
76 | }
77 |
78 | guess, err := strconv.Atoi(args[0])
79 | if err != nil {
80 | fmt.Println("Please enter a numeric value.")
81 | return
82 | }
83 |
84 | if guess <= 0 {
85 | fmt.Println("Please enter a a positive number ✚.")
86 | return
87 | }
88 |
89 | max := 10
90 |
91 | if guess > max {
92 | max = guess
93 | }
94 |
95 | for i := 1; i <= guess; i++ {
96 | random := rand.Intn(max) + 1
97 | if random == guess {
98 | fmt.Println("🍀 You won!")
99 | return
100 | }
101 |
102 | }
103 |
104 | fmt.Println("☠️ YOU LOST... Try again?")
105 |
106 | }
107 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 2/06-dynamic-difficulty/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "math/rand"
14 | "os"
15 | "strconv"
16 | "time"
17 | )
18 |
19 | // ---------------------------------------------------------
20 | // EXERCISE: Dynamic Difficulty
21 | //
22 | // Current game picks only 5 numbers (5 turns).
23 | //
24 | // Make sure that the game adjust its own difficulty
25 | // depending on the guess number.
26 | //
27 | // RESTRICTION
28 | //
29 | // Do not make the game too easy. Only adjust the
30 | // difficulty if the guess is above 10.
31 | //
32 | // EXPECTED OUTPUT
33 | //
34 | // Suppose that the player runs the game like this:
35 | // go run main.go 5
36 | //
37 | // Then the computer should pick 5 random numbers.
38 | //
39 | // Or, if the player runs it like this:
40 | // go run main.go 25
41 | //
42 | // Then the computer may pick 11 random numbers
43 | // instead.
44 | //
45 | // Or, if the player runs it like this:
46 | // go run main.go 100
47 | //
48 | // Then the computer may pick 30 random numbers
49 | // instead.
50 | //
51 | // As you can see, greater guess number causes the
52 | // game to increase the game turns, which in turn
53 | // adjust the game's difficulty dynamically.
54 | //
55 | // Because, greater guess number makes it harder to win.
56 | // But, this way, game's difficulty will be dynamic.
57 | // It will adjust its own difficulty depending on the
58 | // guess number.
59 | //
60 | // ---------------------------------------------------------
61 | const (
62 | usage = `Welcome to the Lucky Number Game! 🍀
63 |
64 | The program will pick %d random numbers.
65 | Your mission is to guess one of those numbers.
66 |
67 | The greater your number is, harder it gets.
68 |
69 | Wanna play?
70 | `
71 | )
72 |
73 | func main() {
74 | rand.Seed(time.Now().UnixNano())
75 | maxTurns := 5
76 | args := os.Args[1:]
77 |
78 | if len(args) != 1 {
79 | fmt.Println("Please Enter Number 😢.")
80 | return
81 | }
82 |
83 | guess, err := strconv.Atoi(args[0])
84 | if err != nil {
85 | fmt.Println("Please enter a numeric value.")
86 | return
87 | }
88 |
89 | if guess <= 0 {
90 | fmt.Println("Please enter a a positive number ✚.")
91 | return
92 | }
93 |
94 | if guess > 10 {
95 | maxTurns = guess / 4
96 | }
97 |
98 | for i := 1; i <= guess; i++ {
99 | random := rand.Intn(maxTurns) + 1
100 | if random == guess {
101 | fmt.Println("🍀 You won!")
102 | return
103 | }
104 |
105 | }
106 |
107 | fmt.Println("☠️ YOU LOST... Try again?")
108 |
109 | }
110 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 2/Randomization/01-first-turn-winner/main.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2018 Inanc Gumus
2 | // Learn Go Programming Course
3 | // License: https://creativecommons.org/licenses/by-nc-sa/4.0/
4 | //
5 | // For more tutorials : https://learngoprogramming.com
6 | // In-person training : https://www.linkedin.com/in/inancgumus/
7 | // Follow me on twitter: https://twitter.com/inancgumus
8 |
9 | package main
10 |
11 | import (
12 | "fmt"
13 | "math/rand"
14 | "os"
15 | "strconv"
16 | "time"
17 | )
18 |
19 | // ---------------------------------------------------------
20 | // EXERCISE: First Turn Winner
21 | //
22 | // If the player wins on the first turn, then display
23 | // a special bonus message.
24 | //
25 | // RESTRICTION
26 | // The first picked random number by the computer should
27 | // match the player's guess.
28 | //
29 | // EXAMPLE SCENARIO
30 | // 1. The player guesses 6
31 | // 2. The computer picks a random number and it happens
32 | // to be 6
33 | // 3. Terminate the game and print the bonus message
34 | // ---------------------------------------------------------
35 |
36 | const (
37 | maxTurns = 5 // less is more difficult
38 | usage = `Welcome to the Lucky Number Game! 🍀
39 |
40 | The program will pick %d random numbers.
41 | Your mission is to guess one of those numbers.
42 |
43 | The greater your number is, harder it gets.
44 |
45 | Wanna play?
46 | `
47 | )
48 |
49 | func main() {
50 | rand.Seed(time.Now().UnixNano())
51 | args := os.Args[1:]
52 |
53 | if len(args) != 1 {
54 | fmt.Printf(usage, maxTurns)
55 | return
56 | }
57 |
58 | guess, err := strconv.Atoi(args[0])
59 | if err != nil {
60 | fmt.Println("Not a number.")
61 | return
62 | }
63 |
64 | if guess <= 0 {
65 | fmt.Println("Please pick a positive number.")
66 | return
67 | }
68 |
69 | for turn := 1; turn <= maxTurns; turn++ {
70 | n := rand.Intn(guess) + 1
71 |
72 | if n != guess {
73 | continue
74 | }
75 |
76 | if turn == 1 {
77 | fmt.Println("🥇 FIRST TIME WINNER!!!")
78 | } else {
79 | fmt.Println("🎉 YOU WON!")
80 | }
81 | return
82 | }
83 |
84 | fmt.Println("👻 YOU LOST... Try again?")
85 | }
86 |
--------------------------------------------------------------------------------
/MasterGoLang/Section 2/Readme.md:
--------------------------------------------------------------------------------
1 | # Section 2
2 |
3 | 1. Randomization
4 | - First Turn Winner
5 | - Random Messages
6 | - Double Guesses
7 | - Verbose Mode
8 | - Enough Picks
9 | - Dynamic Difficulty
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # LearnGoLang
2 |
3 | 
4 |
5 | This is my journey for get going in Golang. I will be sharing my findings, experience and learnings while I'm learning [GoLang](https://golang.google.cn/).
6 |
7 | `It's all about iterations with innovation`
8 |
9 |
10 |
11 |     
12 |
13 | ## Table Of Contents
14 |
15 | - [LearnGoLang](#learngolang)
16 | - [Table Of Contents](#table-of-contents)
17 | - [Practice](#practice)
18 | - [References](#references)
19 | - [Special Thanks](#special-thanks)
20 |
21 | ## Practice
22 |
23 |
24 |
25 | |SN |Practice |Area Covered |
26 | |:--|:---------|:------------|
27 | |1|[GoLangProgrammers Directory](./GoLangProgrammers/README.md)|Basics of Go|
28 | |1|[GetGoing Directory](./GetGoing/README.md)|Basics of Go, A REST API with simple CRUD |
29 | |2|[LetsGo Directory](./LetsGo/README.md)| A step by Step guide of creating a fast, secure and maintainable go application. |
30 | |3|[GoRmGin Directory](./GoRmGin/README.md)| Introduction to GORM and Gin |
31 | |4|[Master Go Lang](./MasterGoLang/Readme.md)| Go Bootcamp: Master Golang with 1000+ Exercises and Projects|
32 |
33 | ## References
34 |
35 | - [GetGoing](https://www.udemy.com/course/getgoing/) Free Course From Udemy amd its [Source Code](https://github.com/L04DB4L4NC3R/getgoing)
36 | - [LetsGo](https://alexedwards.gumroad.com/l/lets-go) Book by Alex Edwards
37 | - Articles from [Alex Edwards](https://www.alexedwards.net/blog)
38 | - Article from [Golang Docs](https://go.dev/doc/tutorial/web-service-gin)
39 | - From [GoLangPrograms web site](https://www.golangprograms.com/go-language/variables.html)
40 |
41 | ## Special Thanks
42 |
43 | I would like to specially thank [@wesionaryTeam](https://github.com/wesionaryTEAM) and all the mentors there who supported me technically, financially and emotionally to achieve this skill sets.
44 |
--------------------------------------------------------------------------------