Cyan Hall C H
Created by CyanHall.com. Last updated: 11/25/2020 👉  

1. Hello

    fmt.Sprintf("hello %s! happy coding.", str)
fmt.Println("%v", bytes)
  

2. JSON

    type Config struct {
    Name bool `json:"name"` // OK

    Name bool `json: "name"` // Error
    Name bool `json:name` // Error
}
  

3. String

    import (
    "strings"
)
strings.Contains("something", "some") // true
  

4. Array

    var number_array [3]int // [0, 0, 0]
append(number_array, 1) // Error
number_array[0] = 1 // [1, 0, 0]
  

5. Slice

    var number_slice []int // []
// Recreate to append
number_slice = append(number_slice, 1) // [1]
// Create a new slice from an array
some_numbers := number_array[0:1] // [0]
  

6. Map

    your_map := make(map[string]int)
your_map["key"] = 1
fmt.Println(your_map["key"]) // 1
// Remove key
delete(elements, "key")
  

7. Loop

    names := []string{"a", "b", "c"} // [a b c]
for i, name := range names {
	fmt.Printf("%d. %s
", i+1, name)
}
// 1. a
// 2. b
// 3. c
  

8. Interface

    // res.Data is <interface {}>, res.Data > data is <[]interface {}>
items = res.Data.([]interface{})
for i, item := range response {
  data := item.(map[string]interface{})
  data["id"].(float64)
}
  

9. Debug using Delve

    # https://github.com/go-delve/delve
dlv debug app.go
  

10. Inside Debugger

    # Set breakpoint
break [path/filename].go:[line_num]

# Run and should pauses at the breakpoint
continue

# Print variable
print [variable_name]

# Move to next line in the source
next
  

11. Gin

    // Read Request Body in JSON
type GitHubInput struct {
	Zen string `json:"zen"`
}
var input GitHubInput
if err := c.ShouldBindJSON(&input); err != nil {
	c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	return
}
input.Zen

// Read Header
c.Request.Header.Get("X-GitHub-Event")

// HTTP Response
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
c.String(200, input.Zen)