0%

Go Note

bing

文章主要涉及 Go,以及 Gin、Gorm、Thrift 等 Go 框架的知识点,作为快速索引和查缺补漏的笔记。文章主要记录学习工作过程中容易遗忘的知识点,不会覆盖所有知识面。学到什么就记什么,故文章内容比较杂。

Go

Go 安装

Go 官网 下载并安装 Go。若使用 VS Code,可在 VS Code 中安装 Go 辅助工具。在 VS Code 中按 ctrl + shift + p,输入 go install,全部勾选后按 enter 键即可。

Go 命令

go get

go get 命令可以借助代码管理工具通过远程拉取或更新代码包及其依赖包,并自动完成编译和安装。go get 具有很多参数:

  • -d 只下载不安装
  • -f 不让 -u 验证 import 中的每一个都已经获取,对本地 fork 的包特别有用,只有在包含 -u 参数时才有效
  • -t 同时下载需要为运行测试所需要的包
  • -u 强制使用网络去更新包和它的依赖包
  • -v 显示执行的命令

Go 语法

  1. Go 没有 enum 定义,可以使用 iota 实现一组自增常量值作为枚举类型,iota 是以行计数的。如果不指定类型和初始化值,则与上一行非空常量右值(表达式文本)相同。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    func TestConst(t *testing.T) {
    const (
    a = iota
    b
    c = "100"
    d
    e, f = iota, iota
    g, h // 没有 h 会报错
    i = iota
    )
    fmt.Println(a, b, c, d, e, f, g, h, i)
    // 0 1 100 100 4 4 5 5
    }
  2. continue

Gin

Gin 相关知识点可以在 官网 查询。

Gin 安装

1
go get -u github.com/gin-gonic/gin

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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()
}

Gorm

Gorm 安装

1
go get -u github.com/jinzhu/gorm

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main

import (
"fmt"

"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)

func main() {
db, err := gorm.Open("mysql",
"root:123456@(localhost)/apathy?charset=utf8&parseTime=True&loc=Local")
defer db.Close()
if err != nil {
fmt.Printf("mysql connection error: %v", err)
}
fmt.Println("mysql connection success")
}