这是我参与「第三届青训营 -后端场」笔记创作活动的第6篇笔记
Json
package main
import (
"encoding/json"
"fmt"
)
type Order struct { //tag
ID string `json:"id"` //不能小写,小写不是public的
Name string `json:"name,omitempty"`
Quantity int `json:"quantity"`
TotalPrice float64 `json:"total_price"`
}
func main() {
o := Order{
ID: "1234",
Name: "learn go",
Quantity: 3,
TotalPrice: 30,
}
b, err := json.Marshal(o)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", b)
}
Json 约定俗成小写还有__
定义结构体是加tag 处理字段名
json.Marshal json.Unmarshal
Golang 常用工具链/Test
go build
go install
go get -u
go test
go env
go fmt
go mod
注意: test文件下的每一个test case均必须以TestXxx形式,否则go test 会直接跳过测试不执行
t *testing.T / b *testing.B
t.SkipNow() 写在test case第一行 跳过测试
使用TestMain 要在其中使用m.Run()确保其他test正常执行
Benchmark中的 需要处于稳态的数据(n < b.N)
架构及API实现
Why choose Video Website?
- Go是一门网络编程语言
- 优良的native http库以及模板引擎
什么是前后端解耦?
- 前后端解耦是时下流行的web网站架构
- 前端页面和服务通过普通的web引擎渲染
- 后端数据通过渲染后的页面脚本调用后处理和呈现
优势:解放生产力,架构更灵活,部署更方便,更符合微服务的特征,性能提升
缺点:工作量大,团队学习成本加大,系统复杂度大
API
REST API (Representational Status Transfer)API
REST 是一种设计风格,不是任何架构标准
RESTful 通常用HTTP作为通信协议, JSON作为数据格式
- 统一接口Uniform Interface
- 无状态Stateless
- 可缓存Cacheable
- 分层Layered System
- CS模式Client-server Atchitecture
API 设计原则
- 以URL(统一资源定位符)风格设计API
- 通过不同的METHOD(GET,POST,PUT,DELETE)来区分对资源的CRUD
- 返回码Status Code符合HTTP资源描述的规定
handler -> validation{1. request, 2.user} -> business logic -> response.
- data model
- error handling
- session
代码分层结构