IO 和排序
目前为止的代码
// server.go
package main
import (
"encoding/json"
"fmt"
"net/http"
)
// PlayerStore stores score information about players
type PlayerStore interface {
GetPlayerScore(name string) int
RecordWin(name string)
GetLeague() []Player
}
// Player stores a name with a number of wins
type Player struct {
Name string
Wins int
}
// PlayerServer is a HTTP interface for player information
type PlayerServer struct {
store PlayerStore
http.Handler
}
const jsonContentType = "application/json"
// NewPlayerServer creates a PlayerServer with routing configured
func NewPlayerServer(store PlayerStore) *PlayerServer {
p := new(PlayerServer)
p.store = store
router := http.NewServeMux()
router.Handle("/league", http.HandlerFunc(p.leagueHandler))
router.Handle("/players/", http.HandlerFunc(p.playersHandler))
p.Handler = router
return p
}
func (p *PlayerServer) leagueHandler(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(p.store.GetLeague())
w.Header().Set("content-type", jsonContentType)
w.WriteHeader(http.StatusOK)
}
func (p *PlayerServer) playersHandler(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)
}存储数据
首先编写测试
尝试运行测试
编写最少量的代码让测试运行起来,然后检查错误输出
编写足够的代码使测试通过
重构
寻找问题
首先编写测试
尝试运行测试
编写最少量的代码让测试运行起来,然后检查错误输出
编写足够的代码使测试通过
重构
首先编写测试
尝试运行测试
编写最少量的代码让测试运行起来,然后检查错误输出
编写足够的代码使测试通过
重构
首先编写测试
尝试并运行测试
编写足够的代码使测试通过
更多的重构和性能问题
另一个问题
首先编写测试
尝试运行测试
编写足够的代码使测试通过
一个另外的小重构
刚刚我们不是打破了一些规则?测试私有的东西?没有接口?
测试私有的类型
接口
错误处理
首先编写测试
尝试运行测试
编写足够的代码使测试通过
重构
排序
首先编写测试
尝试运行测试
编写足够的代码使测试通过
总结
讨论的内容
打破规则
软件的功能
Last updated