JSON,路由和嵌入
这是我们目前已有的代码
// server.go
package main
import (
"fmt"
"net/http"
)
type PlayerStore interface {
GetPlayerScore(name string) int
RecordWin(name string)
}
type PlayerServer struct {
store PlayerStore
}
func (p *PlayerServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
player := r.URL.Path[len("/players/"):]
switch r.Method {
case http.MethodPost:
p.processWin(w, player)
case http.MethodGet:
p.showScore(w, player)
}
}
func (p *PlayerServer) showScore(w http.ResponseWriter, player string) {
score := p.store.GetPlayerScore(player)
if score == 0 {
w.WriteHeader(http.StatusNotFound)
}
fmt.Fprint(w, score)
}
func (p *PlayerServer) processWin(w http.ResponseWriter, player string) {
p.store.RecordWin(player)
w.WriteHeader(http.StatusAccepted)
}先写测试
尝试运行测试
编写足够的代码让它通过
重构
最后一次重构
嵌入
有任何缺点吗?
先写测试
为什么不测试 JSON 字符串?
数据建模
JSON 解码
尝试运行测试
编写足够的代码让它通过
编码和解码
重构
先写测试
尝试运行测试
编写最少量的代码让测试运行起来,然后检查错误输出
编写足够的代码让它通过
重构
先写测试
尝试运行测试
编写足够的代码让它通过
重构
先写测试
尝试运行测试
编写足够的代码让它通过
总结
Last updated