主要是用 nex.Handler 把一个处理业务逻辑的 Endpoint 转成一个符合 http.Handler 接口的结构, 在请求过来的时候自动将 Request.Body 的内容 Unmarshl 为 golang 的结构, 函数返回时自动将返回的结果 Marshal 为 JSON 结构, 传回客户端.
Talk is cheap, show you the code.
package main
import (
"errors"
"fmt"
"net/http"
"github.com/chrislonng/nex"
)
type LoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type LoginResponse struct {
Result string `json:"result"`
}
type ErrorMessage struct {
Code int `json:"code"`
Error string `json:"error"`
}
func main() {
// customize error encoder
nex.SetErrorEncoder(func(err error) interface{} {
return &ErrorMessage{Code: -1, Error: err.Error()}
})
mux := http.NewServeMux()
mux.Handle("/test1", nex.Handler(test1))
mux.Handle("/test2", nex.Handler(test2))
http.ListenAndServe(":8080", mux)
}
// regular response
func test1(m *LoginRequest) (*LoginResponse, error) {
fmt.Printf("%+v\n", m)
return &LoginResponse{Result: "success"}, nil
}
// error response
func test2(m *LoginRequest) (*LoginResponse, error) {
fmt.Printf("%+v\n", m)
return nil, errors.New("error test")
}
觉得有用就 Star 一下吧
1
BMW 2016 年 9 月 12 日
妹子,你还需要自己动手写代码?
|
2
magicdawn 2016 年 9 月 12 日
楼主估计用的女神头像
|
4
jiangbingo 2016 年 9 月 12 日
现任看到会是什么感觉?
|
5
hansnow 2016 年 9 月 12 日
已经没人关注楼主写的东西了,楼主,讲出你头像的故事吧
|
6
Lucius 2016 年 9 月 12 日
你就是我女朋友的前任啊? 世界真小
子湄是个好姑娘,我会替你照顾好她的 |
7
taresky 2016 年 9 月 12 日
|
9
Lonely 2016 年 9 月 12 日 via iPhone
楼这么快就歪了
|
10
xAx 2016 年 9 月 12 日
一帮程序员屌丝又在盗图吹女友了
|
11
xAx 2016 年 9 月 12 日
|
12
qcloud 2016 年 9 月 12 日 |
13
neoblackcap 2016 年 9 月 12 日
7 楼已经算对楼主好的了,之前我在百度里面看过扒皮扒得更惨的
|
14
SourceMan 2016 年 9 月 12 日
哟,好贴,赶紧收藏下,下午回来看
|
15
Jakesoft 2016 年 9 月 12 日
好帖(tu), mark
|
16
ICU 2016 年 9 月 12 日
好强你们,话说是怎么根据图片翻出这么多信息的?
|
17
pizida 2016 年 9 月 12 日
百度识图,谷歌识图。
楼主,我不是来拆台的... |
18
ebony0319 2016 年 9 月 12 日
要不是看了 7 楼我就差点信了 6 楼。
|
19
god 2016 年 9 月 12 日
|
21
frozenshadow 2016 年 9 月 12 日
哈哈哈,这楼歪的可以啊。下班刷新再看看
|
22
xylitolLin 2016 年 9 月 12 日
留名看戏
|
23
chrislon OP 换头像正楼
|
24
aisk 2016 年 9 月 12 日
楼主前女友哆啦 A 梦?黑人问好.gif
|
25
frozenshadow 2016 年 9 月 12 日
@aisk 之前是六楼的妹子
|
26
weaming 2016 年 9 月 12 日
v2ex 要变发车场了吗
|
27
Karblue 2016 年 9 月 13 日
来晚了吗。我要上车。
|