Cyan Hall C H
CyanHall.com 创建。上次更新:12/03/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. 字符串

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

4. 数组

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

5. 切片

    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. 字典

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

7. 循环

    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. 接口

    // 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. 使用 Delve 调试

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

10. 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)