Skip to content

Commit

Permalink
Refactor code to remove unnecessary package and unused imports
Browse files Browse the repository at this point in the history
  • Loading branch information
Pradumnasaraf committed Sep 12, 2024
1 parent c6ea19b commit fa27f01
Show file tree
Hide file tree
Showing 14 changed files with 199 additions and 112 deletions.
8 changes: 1 addition & 7 deletions docs/golang/concepts/0) test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1 @@
package main

import "fmt"

func main() {
fmt.Println("Hello World!")
}
package main
1 change: 1 addition & 0 deletions docs/golang/concepts/12) slices2.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ func main() {

fmt.Println(cars)
var index int = 2
// We are concatenating two slice and rewriting the 1st Slice.
cars = append(cars[:index], cars[index+1:]...) // remove the element at index 2. :index is from 0 to index-1, [index+1:] is from index+1 to end. We can append both elements as well as a slice. ... is to denote a slice
fmt.Println(cars)

Expand Down
10 changes: 5 additions & 5 deletions docs/golang/concepts/13) map.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import (
)

func main() {
// var languages = map[string]string{}
var languages = make(map[string]string, 0) // create a slice of maps with a length of 0. // map[keyType]valueType
var languages = map[string]string{}
// var languages = make(map[string]string, 0) // create a slice of maps with a length of 0. // map[keyType]valueType

//laguages[key] = value
languages["JS"] = "JavaScript"
Expand All @@ -17,10 +17,10 @@ func main() {
fmt.Println(languages)
fmt.Println(languages["JS"]) // access the value of a key

delete(languages, "RB") // delete a key from a map
delete(languages, "RB") // Deleting a Key (No key means no Value as well)
fmt.Println(languages)

for _, value := range languages {
fmt.Println(value)
for key, value := range languages {
fmt.Println(key, value)
}
}
24 changes: 14 additions & 10 deletions docs/golang/concepts/20) methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,30 @@ package main

import "fmt"

type UserData struct { // struct is a collection of fields.
type UserData struct {
fistName string
lastName string
email string
numberOfTickets int
}

/*
func (receiver Type) MethodName(parameters) returnType {
// method body
}
*/

func (u UserData) greetUser() {
fmt.Println("Hello", u.fistName, u.lastName)
}

func main() {
user := UserData{ // struct initialization
user := UserData{
fistName: "John",
lastName: "Doe",
email: "[email protected]",
numberOfTickets: 2,
}

fmt.Println(user)

user.greetUser() // Method call
}

func (u UserData) greetUser() { // method with receiver
fmt.Println("Hello", u.fistName, u.lastName)

user.greetUser() // Call the method
}
2 changes: 2 additions & 0 deletions docs/golang/concepts/21) defer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package main

import "fmt"


// Defer statements are run at the end
func main() {
defer fmt.Println("This is the first defer statement")
defer fmt.Println("This is the second defer statement")
Expand Down
6 changes: 3 additions & 3 deletions docs/golang/concepts/22) map-ad.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@ import (
)

func main() {
var bookings = make([]map[string]string, 0) // This is a slice of map.
// var bookings = []map[string]string{} // This is also valid

bookings :=[]map[string]string{} // This is a slice of map.

for i := 0; i < 1; i++ {

name := "John"
age := 32
city := "New York"

var myMap = make(map[string]string)
myMap := map[string]string{}

myMap["name"] = name
myMap["age"] = strconv.FormatInt(int64(age), 10)
Expand Down
16 changes: 12 additions & 4 deletions docs/golang/concepts/23) files.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,16 @@ import (

func main() {

// Process to create, write and read a file

content := "Hey I am Pradumna"

//"." means current directory
// Create a file
file, err := os.Create("./hello.txt")

if err != nil {
panic(err)
}

// Writing content in a file
length, err := io.WriteString(file, content)

if err != nil {
Expand All @@ -27,13 +26,22 @@ func main() {

fmt.Println("Length:", length)

// Reading a file
data, err := os.ReadFile("./hello.txt")

if err != nil {
panic(err)

}

// data is of type []byte so we need to convert it to string
// Print the read data
fmt.Println(string(data))

//Removing a file
err = os.Remove("./hello.txt")

if err != nil {
panic(err)

}
}
5 changes: 3 additions & 2 deletions docs/golang/concepts/24) handling-web-req.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ func main() {

fmt.Printf("Response is of type: %T\n", res)
fmt.Println(res.Status)
fmt.Println(res.Proto)

databytes, err := io.ReadAll(res.Body) //We can't read the response directly. So we use ioutil.ReadAll()
dataBytes, err := io.ReadAll(res.Body) //We can't read the response directly. So we use ioutil.ReadAll()
checkNilError(err)

content := string(databytes) // convert the byte array to string
content := string(dataBytes) // convert the byte array to string
fmt.Println(content)
}

Expand Down
1 change: 0 additions & 1 deletion docs/golang/concepts/26) http-requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
Expand Down
109 changes: 62 additions & 47 deletions docs/golang/concepts/27) json.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,77 +6,92 @@ import (
"log"
)

// It's important to mention `json:"key-name"` otherwise it will pick the keyword mentioned in the Struct with capitalization.
type Person struct {
Name string `json:"coursename"`
Age int `json:"age"`
DOBY int `json:"doby"`
Name string `json:"name"`
Age int `json:"age"`
Place string `json:"place"`
}

func main() {

// structToJson()
// jsonToStruct()
// letsMarshal()
// letsUnMarshal()
extractJsonData()

}

func structToJson() {
tom := []Person{
func letsUnMarshal() {
jsonData := []byte(`
{
Name: "Tom",
Age: 21,
DOBY: 199,
"name": "Pradumna Saraf",
"age": 25,
"place": "India"
}
`)

var myData Person

isJSONValid := json.Valid(jsonData)
if isJSONValid == true {
json.Unmarshal(jsonData, &myData)
} else {
fmt.Println("Invalid JSON")
}

fmt.Println(myData.Age)
fmt.Println(myData.Name)
fmt.Println(myData.Place)


}

func letsMarshal() {
myPerson := Person{
Name: "Pradumna Saraf",
Age: 25,
Place: "India",
}

myPersonSlice := []Person{
{
Name: "Pradumna Saraf",
Age: 25,
Place: "India",
},
{
Name: "Ben",
Age: 21,
DOBY: 199,
Name: "Pradumna Saraf",
Age: 25,
Place: "India",
},
{
Name: "Loft",
Age: 21,
DOBY: 199,
Name: "Pradumna Saraf",
Age: 25,
Place: "India",
},
}

// Marshal will convert the struct to json
jsonOutput, err := json.MarshalIndent(tom, "", " ")
// Single Object
data, err := json.Marshal(&myPerson)
if err != nil {
log.Fatal(err)

log.Fatal("Unable to Marshal")
}
fmt.Println(string(data))

fmt.Println(string(jsonOutput))
}

func jsonToStruct() {
jsonData := []byte(`{
"coursename": "ben",
"age": 200,
"doby": 1975
}`)

var myUser Person

validateJson := json.Valid(jsonData)
if validateJson == true {
// Unmarshal will convert the json to struct
json.Unmarshal(jsonData, &myUser)
fmt.Println(myUser)
} else {
fmt.Println("JSON is invalid")
// A list of Objects
sliceData, err := json.MarshalIndent(&myPersonSlice, "", " ")
if err != nil {
log.Fatal("Unable to Marshal")
}

fmt.Println(string(sliceData))
}

func extractJsonData() {

func extractJsonData() {
jsonData := []byte(`
{
"coursename": "Mern",
"price": 200,
"website": "yt",
"tags": [ "full-stack", "js" ]
"name": "Pradumna Saraf",
"age": 25,
"place": "India"
}
`)

Expand All @@ -89,4 +104,4 @@ func extractJsonData() {
fmt.Printf("Key is %v with the value %v and type is: %T\n", k, v, v)
}

}
}
23 changes: 3 additions & 20 deletions docs/golang/concepts/28) go-routine.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import (
)

func main() {
go greeter("Hello")
greeter("World")
go greeter("First Statement")
go greeter("Second Statement")
greeter("Third Statement")

}

Expand All @@ -17,22 +18,4 @@ func greeter(s string) {
time.Sleep(1 * time.Second)
fmt.Println(s)
}

//runThisInMain()
}

func runThisInMain() {
for {
var input string
go sayHello() // go keyword is used to create a go routine. This is a concurrent execution of the function, meaning it will run in the background and will not block the main thread.
fmt.Print("Enter Text: ")
fmt.Scanln(&input)
fmt.Println("Your Input was:", input)
}
}

func sayHello() {
time.Sleep(5 * time.Second)
fmt.Println("Hello from sayHello")

}
12 changes: 6 additions & 6 deletions docs/golang/concepts/30) waitgroup-api-eg.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import (
"sync"
)

var wg sync.WaitGroup //pointer
var mut sync.Mutex //pointer
var signals = []string{"test"}
var wg sync.WaitGroup
var mut sync.Mutex
var statusCodes = []int{}

func main() {

Expand All @@ -25,10 +25,10 @@ func main() {
for _, endpoint := range endpoints {
go checkStausCode(endpoint)
wg.Add(1)
}
}

wg.Wait()
fmt.Print(signals)
fmt.Print(statusCodes)
}

func checkStausCode(endpoint string) {
Expand All @@ -39,7 +39,7 @@ func checkStausCode(endpoint string) {
fmt.Println("Problem in the endpoint", endpoint)
} else {
mut.Lock()
signals = append(signals, endpoint)
statusCodes = append(statusCodes, res.StatusCode)
mut.Unlock()
fmt.Printf("Status code for %s is %d\n", endpoint, res.StatusCode)
}
Expand Down
Loading

0 comments on commit fa27f01

Please sign in to comment.