Skip to content

Commit

Permalink
Merge pull request #9 from tainguyenbp/feat/learning-hacking-with-gol…
Browse files Browse the repository at this point in the history
…ang05

learn test golang
  • Loading branch information
tainguyenbp authored Jun 5, 2024
2 parents 3c08c8e + 59c44aa commit 536cf31
Show file tree
Hide file tree
Showing 15 changed files with 755 additions and 0 deletions.
69 changes: 69 additions & 0 deletions hacking-go/learn05/array.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package main

import (
"fmt"
"strconv"
)

func array_2_map_advan() {
anArray := [4]int{1, -2, 14, 0}
aMap := make(map[string]int)

length := len(anArray)
for i := 0; i < length; i++ {
fmt.Printf("%s ", strconv.Itoa(i))
aMap[strconv.Itoa(i)] = anArray[i]
}
fmt.Printf("\n")

for key, value := range aMap {
fmt.Printf("%s: %d\n", key, value)
}
}

func array_advan() {
myArray := [4]int{1, 2, 4, -4}
length := len(myArray)
for i := 0; i < length; i++ {
fmt.Printf("%d ", myArray[i])
}
fmt.Printf("\n")

otherArray := [...]int{0, 2, -2, 6, 7, 8}
for _, number := range otherArray {
fmt.Printf("%d ", number)
}
fmt.Printf("\n")

twoD := [3][3]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
twoD[1][2] = 15

for _, number := range twoD {
for _, other := range number {
fmt.Printf("%d ", other)
}
}
fmt.Printf("\n")

threeD := [2][2][2]int{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}
threeD[0][1][1] = -1
for _, number := range threeD {
fmt.Printf("%d ", number)
}
fmt.Printf("\n")
}

func main() {
var a [5]int
a[0] = 10
a[4] = 20
fmt.Println(a) // [10 0 0 0 20]
// Array can be initialized during creation
// characters[2] is empty
characters := [2]string{"Ender", "Pentra"}
fmt.Println(characters) // [Ender Pentra ]
fmt.Println("Test Array Advance: ")
array_advan()
fmt.Println("Test Array 2 map Advance: ")
array_2_map_advan()
}
32 changes: 32 additions & 0 deletions hacking-go/learn05/defer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package main

import (
"fmt"
)

func a1() {
for i := 0; i < 3; i++ {
defer fmt.Print(i, " ")
}
}

func a2() {
for i := 0; i < 3; i++ {
defer func() { fmt.Print(i, " ") }()
}
}

func a3() {
for i := 0; i < 3; i++ {
defer func(n int) { fmt.Print(n, " ") }(i)
}
}

func main() {
a1()
fmt.Println()
a2()
fmt.Println()
a3()
fmt.Println()
}
66 changes: 66 additions & 0 deletions hacking-go/learn05/functions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package main

import (
"fmt"
)

func unnamedMinMax(x, y int) (int, int) {
if x > y {
min := y
max := x
return min, max
} else {
min := x
max := y
return min, max
}
}

func minMax(x, y int) (min, max int) {
if x > y {
min = y
max = x
} else {
min = x
max = y
}
return min, max
}

func namedMinMax(x, y int) (min, max int) {
if x > y {
min = y
max = x
} else {
min = x
max = y
}
return
}

func sort(x, y int) (int, int) {
if x > y {
return x, y
} else {
return y, x
}
}

func main() {

y := 4
square := func(s int) int {
return s * s
}
fmt.Println("The square of", y, "is", square(y))

square = func(s int) int {
return s + s
}
fmt.Println("The square of", y, "is", square(y))

fmt.Println(minMax(15, 6))
fmt.Println(namedMinMax(15, 6))
min, max := namedMinMax(12, -1)
fmt.Println(min, max)
}
27 changes: 27 additions & 0 deletions hacking-go/learn05/pointer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package main

import (
"fmt"
)

func withPointer(x *int) {
*x = *x * *x
}

type complex struct {
x, y int
}

func newComplex(x, y int) *complex {
return &complex{x, y}
}

func main() {
x := 2
withPointer(&x)
fmt.Println(x)

w := newComplex(4, -5)
fmt.Println(*w)
fmt.Println(w)
}
32 changes: 32 additions & 0 deletions hacking-go/learn05/structs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package main

import "fmt"

type Student struct {
FirstName string
LastName string
}

func main() {
// Make an instance
studentOne := Student{"Ender", "Wiggin"}
// Now we can access fields
fmt.Println(studentOne.FirstName)
// We can just assign fields using names, anything not assigned will be
// initialized with "zero" as we have seen before
studentTwo := Student{FirstName: "Petra"}
// We will print "{Petra }" notice the space after Petra which is supposed
// to be the delimiter between the fields, LastName is nil because it is not
// given a value
fmt.Println(studentTwo)
// Can also make a pointer to a struct
p := &studentOne
// Now instead of *p.LastName (doesn't work) we can just use p.LastName
// fmt.Println((*p).LastName) will not work with error message: invalid indirect o
fmt.Println(p.LastName)
// Which is the same as
fmt.Println(studentOne.LastName)
// We can just create a pointer out of the blue
p2 := &Student{"Hercule", "Poirot"}
fmt.Println(p2)
}
24 changes: 24 additions & 0 deletions hacking-go/learn06/api-test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package main

import (
"fmt"

"github.com/gin-gonic/gin"
)

func Hello(ctx *gin.Context) {
name := ctx.Param("name")
ctx.JSON(200, gin.H{"message": fmt.Sprintf("Hello %s!", name)})
}

func Engine() *gin.Engine {
engine := gin.Default()
engine.GET("/hello/:name", Hello)
return engine
}

func main() {
if err := Engine().Run(); err != nil {
println("ERROR running server:", err.Error())
}
}
17 changes: 17 additions & 0 deletions hacking-go/learn06/api-test1.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package main

import (
"net/http"

"github.com/gin-gonic/gin"
)

func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
73 changes: 73 additions & 0 deletions hacking-go/learn06/api-test2/api-test2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package main

import (
"fmt"
"net/http"

"github.com/gin-gonic/gin"
)

type user struct {
User_ID string `json:"user_id"`
Title string `json:"title"`
Name string `json:"name"`
Role string `json:"role"`
Teams string `json:"teams"`
Salary float64 `json:"salary"`
}

// users slice to seed record user data.
var users = []user{
{User_ID: "1", Title: "Platform Engineer", Name: "Tai Nguyen", Role: "Platform", Teams: "SRE Teams", Salary: 56.99},
{User_ID: "2", Title: "System Engineer", Name: "TaiNN", Role: "System", Teams: "SRE Teams", Salary: 17.99},
{User_ID: "3", Title: "Linux Engineer", Name: "t2jnn", Role: "Linux", Teams: "SRE Teams", Salary: 39.99},
{User_ID: "4", Title: "System Admin", Name: "T2jNN", Role: "System", Teams: "SRE Teams", Salary: 39.99},
{User_ID: "5", Title: "Cloud Engineer", Name: "l30nt2j", Role: "Cloud", Teams: "SRE Teams", Salary: 39.99},
{User_ID: "6", Title: "DevOps Engineer", Name: "tainnsre", Role: "DevOps", Teams: "SRE Teams", Salary: 39.99},
{User_ID: "7", Title: "SysOps Engineer", Name: "t2jnnsr3", Role: "SysOps", Teams: "SRE Teams", Salary: 20.99},
}

func getUsers(c *gin.Context) {
c.IndentedJSON(http.StatusOK, users)
}

// postUsers adds an user from JSON received in the request body.
func postUsers(c *gin.Context) {
var newUser user

// Call BindJSON to bind the received JSON to
// newUser.
if err := c.BindJSON(&newUser); err != nil {
return
}

// Add the new user to the slice.
users = append(users, newUser)
c.IndentedJSON(http.StatusCreated, newUser)
}

// getUserByuser_id locates the user whose user_id value matches the id
// parameter sent by the client, then returns that user as a response.
func getUserByuser_id(c *gin.Context) {
user_id := c.Param("user_id")

// Loop over the list of users, looking for
// an user whose user_id value matches the parameter.
for _, a := range users {
if a.User_ID == user_id {
c.IndentedJSON(http.StatusOK, a)
fmt.Println("status 200 for this user ", a.User_ID)
return
}
}
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "user not found"})
}

func main() {
router := gin.Default()
router.GET("/users", getUsers)
router.POST("/users", postUsers)
router.GET("/users/:user_id", getUserByuser_id)

router.Run("localhost:8080")
}
36 changes: 36 additions & 0 deletions hacking-go/learn06/api-test2/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
module github.com/c4s4/go-rest-api

go 1.17

require github.com/gin-gonic/gin v1.10.0

require (
github.com/bytedance/sonic v1.11.8 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.4 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.21.0 // indirect
github.com/goccy/go-json v0.10.3 // indirect
github.com/golang/protobuf v1.5.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.24.0 // indirect
golang.org/x/net v0.26.0 // indirect
golang.org/x/sys v0.21.0 // indirect
golang.org/x/text v0.16.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v2 v2.2.8 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
Loading

0 comments on commit 536cf31

Please sign in to comment.