Go笔记(8)服务

这篇记录 go 中的服务。JSON的解析

JSON的解析

内置

反射:适用于配置文件的解析,定义一个结构:
struct_def.go

1
2
3
4
5
6
7
8
9
10
11
type BasicInfo struct {
Name string `json:"name"`
Age int `json:"age"`
}
type JobInfo struct {
Skills []string `json:"skills"`
}
type Employee struct {
BasicInfo BasicInfo `json:"basic_info"`
JobInfo JobInfo `json:"job_info"`
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var jsonStr = `{
"basic_info":{
"name":"Mike",
"age":30
},
"job_info":{
"skills":["Java","Go","C"]
}
}`
func TestEmbeddedJson(t *testing.T) {
e := new(Employee)
err := json.Unmarshal([]byte(jsonStr), e)
if err != nil {
t.Error(err)
}
fmt.Println(*e)
if v, err := json.Marshal(e); err == nil {
fmt.Println(string(v))
} else {
t.Error(err)
}
}

easyJSON

最高效的JSON解析方式,提升性能

1
2
3
go get -u github.com/mailru/easyjson/...
~/go/bin/easyjson -all struct_def.go
# 执行完之后在package中根据结构自动生成代码

http 服务

  1. 路由规则:
    • URL 分为两种,末尾是 /:表示⼀个⼦树,后⾯可以跟其他⼦路径;末尾不是 /,表示⼀个叶⼦,固定的路径
    • 以 / 结尾的 URL 可以匹配它的任何⼦路径,⽐如 /images 会匹配 /images/***.jpg
    • 它采⽤最⻓匹配原则,如果有多个匹配,⼀定采⽤匹配路径最⻓的那个进⾏处理
    • 如果没有找到任何匹配项,会返回 404 错误
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello World!")
    })
    http.HandleFunc("/time/", func(w http.ResponseWriter, r *http.Request) {
    t := time.Now()
    timeStr := fmt.Sprintf("{\"time\": \"%s\"}", t)
    w.Write([]byte(timeStr))
    })
    http.ListenAndServe(":8080", nil)
    }

Restful 服务

安装 httprouter 包

1
go get https://github.com/julienschmidt/httprouter
1
2
3
4
5
6
7
8
9
10
11
12
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Welcome!\n")
}
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}
func main() {
router := httprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)
log.Fatal(http.ListenAndServe(":8080", router))
}

Go笔记(8)服务
https://guoningyan.com/2024/02/28/Go笔记(8)服务/
作者
Ningyan Guo
发布于
2024年2月28日
许可协议