Golang笔记

Golang的学习方向 区块链研发工程师, Go服务器端/游戏软件工程师, Golang分布式/云计算软件工程师 Golang的应用领域 区块链的应用开发 分布式账本技术: 去中心化, 公开透明 后台服务器应用 云计算/云服务后台应用 学习方法介绍 先整体框架, 再细节 工科 做中学 适当囫囵吞枣 讲课方式说明 通俗易懂 兼顾技术细节 Golang的概述 什么是程序 Go语言诞生的小故事 Go语言的核心开发团队-三个大牛 肯.汤姆森 罗布.派克 Google创造go语言的原因 计算机硬件更新频繁, 目前主流语言不能利用多核CPU 缺乏一个足够简单高效的编程语言 c/c++编译速度慢, 内存泄漏等困扰 Golang的发展历程 2007年三大创始人开始设计 2009年11月10日, 开源 2015年8月19日, 1.5发布, 移除最后残余的C代码 … Golang的语言特点 静态编译语言的安全和性能, 动态语言开发维护的高效率, 结合 Go = C + Python 保留了指针, 弱化的指针 引入包的概念, 一个文件都要归属于一个包 垃圾回收机制, 内存自动回收 天然并发(重要) 从语言层面支持并发, 实现简单 goroutine, 轻量级线程, 可实现大并发处理, 高效利用多核心 基于CPS并发模型实现 吸收了管道通信机制, 形成Go语言特有的管道channel, 实现不同goroutine之间相互通信 函数可以多返回值 新的创新, 比如切片slice, 延时执行defer Golang开发工具介绍 Vscode, Goland ...

2018-12-31 · 5 分钟 · 916 字 · 王站站

sentry安装和使用

官方文档 安装 mkdir -p /root/docker/sentry && cd /root/docker/sentry git clone https://github.com/getsentry/self-hosted.git ./ 配置邮件(可选) vim sentry/config.yml mail.host: 'smtp.gmail.com' mail.port: 465 mail.username: 'admin@gmail.com' mail.password: 'XXXXXXXXXXX' mail.use-ssl: true mail.from: 'Sentry <admin@gmail.com>' 部署 ./install.sh # 按提示输入 n,然后填写邮箱和密码 docker-compose up -d 初始配置 访问后设置 Root URL,如 https://sentry.example.com 设置 → 我的账户 → 修改语言和时区 创建项目 项目 → 创建项目 → Go → 填写项目名和团队 → 保存 查看 DSN:项目设置 → 客户端密钥(DSN) Go SDK 接入 err := sentry.Init(sentry.ClientOptions{ Dsn: "你的DSN", TracesSampleRate: 1.0, Release: "app:1.0", Environment: "prod", }) if err != nil { log.Fatal(err) } defer sentry.Flush(2 * time.Second) // 上报错误 sentry.CaptureMessage("自定义消息") sentry.CaptureException(err) // 上报自定义级别事件 event := sentry.NewEvent() event.Level = sentry.LevelWarning event.Message = "警告信息" sentry.CaptureEvent(event) 注:默认异步上报;将 DSN 置空可禁用上报。 ...

2018-05-21 · 1 分钟 · 105 字 · 王站站

gorm中文文档

入门指南 概述 全功能 ORM 关联 (Has One、Has Many、Belongs To、Many To Many、多态、单表继承) Create、Save、Update、Delete、Find 前/后的勾子 基于Preload、Joins的预加载 事务、嵌套事务、保存点、回滚至保存点 Context、Prepared Statment 模式、DryRun 模式 批量插入、FindInBatches、查询至 Map SQL Builder, Upsert, Locking, Optimizer/Index/Comment Hints 复合主键 自动迁移 自定义 Logger 灵活的可扩展插件 API:Database Resolver(读写分离)、Prometheus… 所有特性都通过了测试 开发者友好 快速入门 package main import ( "gorm.io/gorm" "gorm.io/driver/sqlite" ) type Product struct { gorm.Model Code string Price uint } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &amp;gorm.Config{}) if err != nil { panic("failed to connect database") } // 迁移 schema db.AutoMigrate(&amp;Product{}) // Create db.Create(&amp;Product{Code: "D42", Price: 100}) // Read var product Product db.First(&amp;product, 1) // 根据整形主键查找 db.First(&amp;product, "code = ?", "D42") // 查找 code 字段值为 D42 的记录 // Update - 将 product 的 price 更新为 200 db.Model(&amp;product).Update("Price", 200) // Update - 更新多个字段 db.Model(&amp;product).Updates(Product{Price: 200, Code: "F42"}) // 仅更新非零值字段 db.Model(&amp;product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"}) // Delete - 删除 product db.Delete(&amp;product, 1) } 声明模型 type User struct { ID uint Name string Email *string Age uint8 Birthday *time.Time MemberNumber sql.NullString ActivedAt sql.NullTime CreatedAt time.Time UpdatedAt time.Time } gorm.Model ...

2018-03-26 · 10 分钟 · 2019 字 · 王站站

gin中文文档

Gin 是一个高性能 Go Web 框架。GitHub 安装 go get -u github.com/gin-gonic/gin import "github.com/gin-gonic/gin" Hello World 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() // 0.0.0.0:8080 } go run main.go 路由 HTTP 方法 router.GET("/someGet", getting) router.POST("/somePost", posting) router.PUT("/somePut", putting) router.DELETE("/someDelete", deleting) router.PATCH("/somePatch", patching) 路径参数 // 匹配 /user/john,不匹配 /user/ router.GET("/user/:name", func(c *gin.Context) { name := c.Param("name") c.String(http.StatusOK, "Hello %s", name) }) // 匹配 /user/john/send 等 router.GET("/user/:name/*action", func(c *gin.Context) { name := c.Param("name") action := c.Param("action") c.String(http.StatusOK, name+" is "+action) }) Query 参数 // /welcome?firstname=Jane&lastname=Doe router.GET("/welcome", func(c *gin.Context) { firstname := c.DefaultQuery("firstname", "Guest") lastname := c.Query("lastname") c.String(http.StatusOK, "Hello %s %s", firstname, lastname) }) Post 参数 router.POST("/form_post", func(c *gin.Context) { message := c.PostForm("message") nick := c.DefaultPostForm("nick", "anonymous") c.JSON(200, gin.H{"status": "posted", "message": message, "nick": nick}) }) 路由分组 v1 := router.Group("/v1") { v1.POST("/login", loginEndpoint) v1.POST("/submit", submitEndpoint) } 中间件 r := gin.New() r.Use(gin.Logger()) r.Use(gin.Recovery()) authorized := r.Group("/") authorized.Use(AuthRequired()) { authorized.POST("/login", loginEndpoint) } 文件上传 // 单文件 router.POST("/upload", func(c *gin.Context) { file, _ := c.FormFile("file") c.SaveUploadedFile(file, "./"+file.Filename) c.String(http.StatusOK, "'%s' uploaded!", file.Filename) }) // 多文件 router.POST("/upload", func(c *gin.Context) { form, _ := c.MultipartForm() files := form.File["upload[]"] for _, file := range files { c.SaveUploadedFile(file, "./"+file.Filename) } c.String(http.StatusOK, "%d files uploaded!", len(files)) }) 模型绑定 type Login struct { User string `form:"user" json:"user" binding:"required"` Password string `form:"password" json:"password" binding:"required"` } router.POST("/login", func(c *gin.Context) { var json Login if err := c.ShouldBindJSON(&json); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, gin.H{"status": "logged in"}) }) Cookie router.GET("/cookie", func(c *gin.Context) { cookie, err := c.Cookie("gin_cookie") if err != nil { c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true) } _ = cookie }) 优雅重启 srv := &http.Server{Addr: ":8080", Handler: router} go srv.ListenAndServe() quit := make(chan os.Signal, 1) signal.Notify(quit, os.Interrupt) <-quit ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() srv.Shutdown(ctx) 测试 func TestPingRoute(t *testing.T) { router := setupRouter() w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/ping", nil) router.ServeHTTP(w, req) assert.Equal(t, 200, w.Code) assert.Equal(t, "pong", w.Body.String()) } 参考 gin 中文文档

2018-03-19 · 2 分钟 · 326 字 · 王站站