"fmt"
"io"
)
type MCResponse struct {
//命令
Opcoed CommandCode
//返回状态
Status Status
//key
Key string
//返回内容
Value []byte
//返回标识
Flags int
//错误
Fatal bool
}
//解析response 并把返回结果写入socket链接
func (res *MCResponse) Transmit(w io.Writer) (err error) {
switch res.Opcoed {
case STATS:
_, err = w.Write(res.Value)
case GET:
if res.Status == SUCCESS {
rs := fmt.Sprintf("VALUE %s %d %drn%srnENDrn", res.Key, res.Flags, len(res.Value), res.Value)
_, err = w.Write([]byte(rs))
} else {
_, err = w.Write([]byte(res.Status.ToString()))
}
case SET, REPLACE:
_, err = w.Write([]byte(res.Status.ToString()))
case DELETE:
_, err = w.Write([]byte("DELETEDrn"))
}
return
}
3. Go语言代码如下:
package memcachep
import (
"fmt"
)
type action func(req *MCRequest, res *MCResponse)
var actions = map[CommandCode]action{
STATS: StatsAction,
}
//等待分发处理
func waitDispatch(rc chan chanReq) {
for {
input := <-rc
input.response <- dispatch(input.request)
}
}
//分发请求到响应的action操作函数上去
func dispatch(req *MCRequest) (res *MCResponse) {
if h, ok := actions[req.Opcode]; ok {
res = &MCResponse{}
h(req, res)
} else {
return notFound(req)
}
return
}
//未支持命令
func notFound(req *MCRequest) *MCResponse {
var response MCResponse
response.Status = UNKNOWN_COMMAND
return &response
}









