Go http handler 中间件

本文介绍了一种在HTTP handler中使用中间件的方法,通过自定义的FormatReturnHandler,实现了请求处理前后的过滤、日志记录、统计及统一的JSON响应格式。具体实现包括将处理函数的返回结果包装为标准的响应结构,再将其序列化为JSON并发送给客户端。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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 }

 

转载于:https://www.cnblogs.com/linguoguo/p/10553716.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值