From ebbb02156279c4838ded37884fde4eaae9407d06 Mon Sep 17 00:00:00 2001 From: sidharthchadha2 Date: Mon, 21 Apr 2025 11:46:37 +0900 Subject: [PATCH] excercises commit --- docs/http/main.go | 77 ++++++++++++++++++++++ docs/http/main_1.go | 112 ++++++++++++++++++++++++++++++++ docs/testing/palindrome_test.go | 33 ++++++++++ 3 files changed, 222 insertions(+) create mode 100644 docs/http/main.go create mode 100644 docs/http/main_1.go create mode 100644 docs/testing/palindrome_test.go diff --git a/docs/http/main.go b/docs/http/main.go new file mode 100644 index 0000000..b4ff8c9 --- /dev/null +++ b/docs/http/main.go @@ -0,0 +1,77 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "net/http" +) + + +type UserResponse struct { + Attributes User `json:"attributes"` +} + +// here its used by json := exported +type User struct { + ID int `json:"id"` + Name string `json:"name"` + AccountIDs []int `json:"account_ids"` +} +// array_of_ints = {array_of_strings}.map(:to_s) +// convert an array into something else +// 1. create a second array variable +// arrayOfInts := make([]int, len(arrayOfStrings)) +// 2. iterate and convert each element +// for i, v := range arrayOfStrings { +// arrayOfInts[i] = .... +// } + +func main() { + url := "https://sample-accounts-api.herokuapp.com/users/1" + // no underscore in golang + resp, err := http.Get(url) + // best practice to check and write defer code nearby to original code + defer resp.Body.Close() // defer here vs derer after error handling is same in this case + + if err != nil { + fmt.Println("error found %v", err) // shadowing error variable... [ from interface error{}] -> avoid naming conflicts with packages + return + } + // return fmt.Errorf("http get %w", err) + //error handlling missing + + // defer resp.Body.Close() + // defer will be skipped here, but it's ok because an error occurred, so there is no body to close + + body, err := io.ReadAll(resp.Body) + if err != nil { + fmt.Println("error found %v", err) + return + } + + // var result map[string]any + // err = json.Unmarshal(body, &result) + + // if err != nil { + // fmt.Println("error found") + // } + // const attr = "attributes" + // optimization + safety [ type safety ] + // attributes, _ := result["attributes"].(map[string]any) + // attributesJSON, _ := json.Marshal(attributes) + var user UserResponse // dont use same var name as struct type name + err = json.Unmarshal(body, &user) + + if err != nil { + fmt.Println("error found") + } + + fmt.Println("User: ", user.Attributes.AccountIDs) + // fmt.Printf("ID: %d, Account IDs: %v\n", user.ID, user.AccountIDs) + + // user.Attributes.AccountIDs is slice of ints + // convert to slice of strings by using strconv.Itoa + // use strings.Join() to join the elements with "," + +} \ No newline at end of file diff --git a/docs/http/main_1.go b/docs/http/main_1.go new file mode 100644 index 0000000..2aaf785 --- /dev/null +++ b/docs/http/main_1.go @@ -0,0 +1,112 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "net/http" +) + +type UserResponse struct { + Attributes User `json:"attributes"` +} + +type User struct { + ID int `json:"id"` + Name string `json:"name"` + AccountIDs []int `json:"account_ids"` +} + +type AccountResponse struct { + Attributes Account `json:"attributes"` +} + +type Account struct { + ID int `json:"id"` + UserID int `json:"user_id"` + Name string `json:"name"` + Balance int `json:"balance"` +} + +func getUser(userID int) (User, error) { + url := fmt.Sprintf("https://sample-accounts-api.herokuapp.com/users/%d", userID) + resp, err := http.Get(url) + if err != nil { + return User{}, err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return User{}, err + } + + var userResponse UserResponse + err = json.Unmarshal(body, &userResponse) + if err != nil { + return User{}, err + } + + return userResponse.Attributes, nil +} + +func getAccounts(userID int) ([]Account, error) { + url := fmt.Sprintf("https://sample-accounts-api.herokuapp.com/users/%d/accounts", userID) + resp, err := http.Get(url) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + var accountResponses []AccountResponse + err = json.Unmarshal(body, &accountResponses) + if err != nil { + return nil, err + } + + accounts := make([]Account, len(accountResponses)) + for i, accountResponse := range accountResponses { + accounts[i] = accountResponse.Attributes + } + + return accounts, nil +} + +func displayUser(user User, accounts []Account) { + fmt.Printf("User: %s\n", user.Name) + fmt.Println("Accounts:") + totalBalance := 0 + for _, account := range accounts { + fmt.Printf(" - %s: %d\n", account.Name, account.Balance) + totalBalance += account.Balance + } + fmt.Printf("Total Balance: %d\n", totalBalance) +} + +func main() { + var userID int + _, err := fmt.Scanln(&userID) + if err != nil { + fmt.Println("Invalid input") + return + } + + user, err := getUser(userID) + if err != nil { + fmt.Println("error found") + return + } + + accounts, err := getAccounts(userID) + if err != nil { + fmt.Println("error found") + return + } + + displayUser(user, accounts) +} diff --git a/docs/testing/palindrome_test.go b/docs/testing/palindrome_test.go new file mode 100644 index 0000000..aaef158 --- /dev/null +++ b/docs/testing/palindrome_test.go @@ -0,0 +1,33 @@ +package stringutils + +import ( + "testing" +) + +func TestReverse(t *testing.T) { + testCases := []struct { + name string + input string + expected string + }{ + {"empty string", "", ""}, + {"single character", "x", "x"}, + {"palindrome", "aba", "aba"}, + {"simple string", "qwe", "ewq"}, + {"with spaces", "qwe rt", "tr ewq"}, + {"with numbers", "12345", "54321"}, + {"with special characters", "!@#$%^&*()", ")(*&^%$#@!"}, + {"with mixed case", "Hello World", "dlroW olleH"}, + {"with unicode", "こんにちは", "はちにんこ"}, + {"with emojis", "😀😃😄", "😄😃😀"}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + actual := Reverse(tc.input) + if actual != tc.expected { + t.Errorf("Reverse(%q) = %q; expected %q", tc.input, actual, tc.expected) + } + }) + } +} \ No newline at end of file