主要是用 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 Sep 12, 2016
妹子,你还需要自己动手写代码?
|
2
magicdawn Sep 12, 2016
楼主估计用的女神头像
|
4
jiangbingo Sep 12, 2016
现任看到会是什么感觉?
|
5
hansnow Sep 12, 2016
已经没人关注楼主写的东西了,楼主,讲出你头像的故事吧
|
6
Lucius Sep 12, 2016
你就是我女朋友的前任啊? 世界真小
子湄是个好姑娘,我会替你照顾好她的 |
7
taresky Sep 12, 2016
|
9
Lonely Sep 12, 2016 via iPhone
楼这么快就歪了
|
10
xAx Sep 12, 2016
一帮程序员屌丝又在盗图吹女友了
|
11
xAx Sep 12, 2016
|
12
qcloud Sep 12, 2016 |
13
neoblackcap Sep 12, 2016
7 楼已经算对楼主好的了,之前我在百度里面看过扒皮扒得更惨的
|
14
SourceMan Sep 12, 2016
哟,好贴,赶紧收藏下,下午回来看
|
15
Jakesoft Sep 12, 2016
好帖(tu), mark
|
16
ICU Sep 12, 2016
好强你们,话说是怎么根据图片翻出这么多信息的?
|
17
pizida Sep 12, 2016
百度识图,谷歌识图。
楼主,我不是来拆台的... |
18
ebony0319 Sep 12, 2016
要不是看了 7 楼我就差点信了 6 楼。
|
19
god Sep 12, 2016
|
21
frozenshadow Sep 12, 2016
哈哈哈,这楼歪的可以啊。下班刷新再看看
|
22
xylitolLin Sep 12, 2016
留名看戏
|
23
chrislon OP 换头像正楼
|
24
aisk Sep 12, 2016
楼主前女友哆啦 A 梦?黑人问好.gif
|
25
frozenshadow Sep 12, 2016
@aisk 之前是六楼的妹子
|
26
weaming Sep 12, 2016
v2ex 要变发车场了吗
|
27
Karblue Sep 13, 2016
来晚了吗。我要上车。
|