码迷,mamicode.com
首页 > Web开发 > 详细

Go http handler 中间件

时间:2019-03-18 18:41:14      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:统一   ons   ack   ring   coding   int   lis   json   记录   

在http的handler处理中加上中间件,可以进行过滤、记录日志、统计和统一返回结果

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "net/http"
 6     "encoding/json"
 7 )
 8 
 9 func main() {
10     _ = fmt.Println
11     http.Handle("/test", FormatReturnHandler(HomeHandler))
12     http.ListenAndServe(":8000", nil)
13 }
14 
15 type normalFunc func(r *http.Request) interface{}
16 
17 type Response struct {
18     Code int         `json:"code"`
19     Data interface{} `json:"data"`
20     Msg  string         `json:"msg"`
21 }
22 
23 func FormatReturnHandler(f normalFunc) http.Handler {
24     return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
25         fmt.Println(r.URL.Path)
26 
27         ret := Response{}
28         ret.Data = f(r)
29         ret.Code = 0
30         ret.Msg = ""
31         jsonRet, _ := json.Marshal(&ret)
32 
33         w.Write(jsonRet)
34     })
35 }
36 
37 func HomeHandler(r *http.Request) interface{} {
38     return r.Host
39 }

 

Go http handler 中间件

标签:统一   ons   ack   ring   coding   int   lis   json   记录   

原文地址:https://www.cnblogs.com/linguoguo/p/10553716.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!