Skip to content

Commit

Permalink
docs: improve glang code formatting and add comments
Browse files Browse the repository at this point in the history
  • Loading branch information
Pradumnasaraf committed Feb 3, 2024
1 parent e1662f7 commit 9e6266a
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 90 deletions.
73 changes: 29 additions & 44 deletions Go/Concepts/26) http-requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,70 +2,55 @@ package main

import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
)

func main() {
// getRequest()
// postRequest()
postFormRequest()

}

func getRequest() {
const apiUrl = "https://opensourceapi.vercel.app/api/devtip"

res, err := http.Get(apiUrl)

if err != nil {
panic(err)
}

defer res.Body.Close()
const URL = "https://osapi.vercel.app/api/devtip"

fmt.Printf("Status code: %v\n", res.StatusCode)
func main() {

var resString strings.Builder
// getReq()
postReq()

// normal string method
content, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(content))
}

// Using the strings library
byteCount, _ := resString.Write(content)
fmt.Println(byteCount)
fmt.Println(resString.String())
func getReq() {
res, err := http.Get(URL)
checkNilErr(err)

byteData, err := io.ReadAll(res.Body)
fmt.Println(string(byteData))
}

func postRequest() {
func postReq() {
resBody := strings.NewReader(
`{
"message": "Eat good food"
}`)

const apiUrl = "https://ossapi.vercel.app/api/devtip"
req, err := http.Post(URL, "application/json", resBody)

// fake json paylaod
checkNilErr(err)
defer req.Body.Close()

reqBody := strings.NewReader(`
{
"message": "eat good food"
}
`)
dataBytes, err := io.ReadAll(req.Body)
fmt.Println("Status Code", req.StatusCode)
fmt.Println("Response Body", string(dataBytes))

res, err := http.Post(apiUrl, "application/json" , reqBody)
}

if err != nil{
panic(err)
func checkNilErr(err error) {
if err != nil {
log.Fatal(err)
}

defer res.Body.Close()

content, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(content))
}

func postFormRequest(){
func postFormRequest() {

const apiUrl = "https://ossapi.vercel.app/api/devtip"

Expand All @@ -80,7 +65,7 @@ func postFormRequest(){

defer res.Body.Close()

content, _ := ioutil.ReadAll(res.Body)
content, _ := io.ReadAll(res.Body)
fmt.Println(string(content))

}
95 changes: 50 additions & 45 deletions Go/Concepts/27) json.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,69 +3,73 @@ package main
import (
"encoding/json"
"fmt"
"log"
)

type course struct {
Name string `json:"coursename"`
Price int `json:"price"`
Platform string `json:"website"`
Password string `json:"-"`
Tags []string `json:"tags,omitempty"`
type Person struct {
Name string `json:"coursename"`
Age int `json:"age"`
DOBY int `json:"doby"`
}

func main() {

//encodeJson()
//decodeJson()
// structToJson()
// jsonToStruct()
extractJsonData()


}

func encodeJson() {

cources := []course{
{"React", 100, "yt", "nn1234", []string{"react", "js"}},
{"Mern", 200, "yt", "fgf1234", []string{"full-stack", "js"}},
{"Golang", 300, "yt", "jh1234", nil},
func structToJson() {
tom := []Person{
{
Name: "Tom",
Age: 21,
DOBY: 199,
},
{
Name: "Ben",
Age: 21,
DOBY: 199,
},
{
Name: "Loft",
Age: 21,
DOBY: 199,
},
}

finalJson, err := json.MarshalIndent(cources, "", "\t") // json.Marshal() will return byte array

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

}

fmt.Print(string(finalJson))
// or
fmt.Printf("%s",finalJson)
fmt.Println(string(jsonOutput))
}

func decodeJson() {

jsonData := []byte(`
{
"coursename": "Mern",
"price": 200,
"website": "yt",
"tags": [ "full-stack", "js" ]
},
`)

var myCourse course

checkValid := json.Valid(jsonData)
if checkValid {
json.Unmarshal(jsonData, &myCourse)
fmt.Printf("%#v\n", myCourse)
} else{
fmt.Println("JSON NOT VALID")
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")
}

}


func extractJsonData(){
func extractJsonData() {

jsonData := []byte(`
{
Expand All @@ -78,10 +82,11 @@ func extractJsonData(){

var myData map[string]interface{}
json.Unmarshal(jsonData, &myData)
fmt.Printf("%#v\n", myData) //
fmt.Printf("%#v\n", myData) //

for k, v := range myData{
// We can use range to loop through the map and print the key and value
for k, v := range myData {
fmt.Printf("Key is %v with the value %v and type is: %T\n", k, v, v)
}

}
}
3 changes: 2 additions & 1 deletion Go/Concepts/28) go-routine.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func greeter(s string) {
func runThisInMain() {
for {
var input string
go sayHello() // go keyword is used to create a go routine. It will not wait for the function to finish.
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)
Expand All @@ -34,4 +34,5 @@ func runThisInMain() {
func sayHello() {
time.Sleep(5 * time.Second)
fmt.Println("Hello from sayHello")

}

0 comments on commit 9e6266a

Please sign in to comment.