当前位置:网站首页>Use of go language web Middleware
Use of go language web Middleware
2022-04-23 02:30:00 【Tian Tudou】
A summary of the premises
Undertake the last time Use Go Language construction Web The server , We implemented a simple application HelloWorld, By listening to local 8080 port , Provide web service . Client access through http://127.0.0.1:8080/ Can get the return value “Hello World!”
The story background
Now the server wants to count the time consumed in each response to the request ( It's just about app Time spent processing requests , Other times such as link communication are not included ), We can HelloWorld Make the following simple modifications
func HelloWorld(w http.ResponseWriter, r *http.Request) {
timeStart := time.Now()
_, err := fmt.Fprintf(w, "Hello World!")
if err != nil {
log.Panic(err)
}
timeElapse := time.Since(timeStart)
log.Println(timeElapse)
}
Now if there is a second , The third application , We can also add simple code . But if there are many applications ,30 individual 、100 individual , This method obviously won't work . The key to the problem is business code and non business code ( Time statistics ) Mixed together
The introduction of middleware
The idea is simple , Is what the server will get request The request is first passed to the middleware of time statistics timeMiddleware, Then it is passed to the application by the middleware HelloWorld, Here is timeMiddleware Simple implementation
func timeMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
timeStart := time.Now()
// Pass parameters to the next http.Handler
next.ServeHTTP(w, r)
timeElapse := time.Since(timeStart)
log.Println(timeElapse)
})
}
stay main Function
func main() {
http.Handle("/", timeMiddleware(http.HandlerFunc(HelloWorld)))
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Panic(err)
}
}
It needs to be added here http.Handler、http.HandlerFunc、ServeHttp The relationship between
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
type HandlerFunc func(ResponseWriter, *Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
Handler It's an interface , There is only one way ServeHttp,HandlerFunc Is a function type , Realized Handler Interface , So in timeMiddleware By calling next.ServeHTTP(w, r) Is to pass parameters to execute app
Now expand , If you want to continue adding a log function , We can do this
// Add a middleware for log Generation
func logMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
file, _ := os.OpenFile("test.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
logger := log.New(file, "", log.Llongfile|log.LstdFlags)
// take w,r Pass to next handler
h.ServeHTTP(w, r)
logger.Println(" Request processing complete ")
})
}
func main() {
http.Handle("/", logMiddleware(timeMiddleware(http.HandlerFunc(HelloWorld))))
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Panic(err)
}
}
After accessing through the browser , The following information can be obtained in the background log Information :
2022/04/16 19:32:07 E:/goland-workspace/goRestful/httptest/main.go:38: Request processing complete
2022/04/16 19:32:07 E:/goland-workspace/goRestful/httptest/main.go:38: Request processing complete
版权声明
本文为[Tian Tudou]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230226013636.html
边栏推荐
- 双亲委派模型【理解】
- 【ValueError: math domain error】
- 类初始化和实例初始化面试题
- Consider defining a bean of type 'com netflix. discovery. AbstractDiscoveryClientOptionalArgs‘
- They are all intelligent in the whole house. What's the difference between aqara and homekit?
- Applet reads files
- 89 régression logistique prédiction de la réponse de l'utilisateur à l'image de l'utilisateur
- How to recognize products from the perspective of Dialectics
- SO库依赖问题
- 想用Mac学习sql,主要给自己个充足理由买Mac听听意见
猜你喜欢
If 404 page is like this | daily anecdotes
006_redis_jedis快速入门
LeetCode 447. Number of boomerangs (permutation and combination problem)
Leetcode40 - total number of combinations II
012_ Access denied for user ‘root‘@‘localhost‘ (using password: YES)
RT_ Thread ask and answer
Heap overflow of kernel PWN basic tutorial
So library dependency
002_ Redis_ Common operation commands of string type
PTA: Romantic reflection [binary tree reconstruction] [depth first traversal]
随机推荐
C # import details
Program design: l1-49 ladder race, allocation of seats (simulation), Buxiang pill hot
Applet reads files
PTA: 点赞狂魔
OJ daily practice - Finish
每日一题冲刺大厂第十六天 NOIP普及组 三国游戏
Daily question (April 22, 2022) - rotation function
Go语言web中间件的使用
How to recognize products from the perspective of Dialectics
Class initialization and instance initialization interview questions
程序设计天梯赛 L1-49 天梯赛分配座位(模拟),布响丸辣
Hyperscan -- 2 compilation
Dynamic batch processing and static batch processing of unity
hack the box optimum靶机
Go language ⌈ mutex and state coordination ⌋
Open3d point cloud processing
If 404 page is like this | daily anecdotes
Latin goat (20204-2022) - daily question 1
[assembly language] understand "stack" from the lowest point of view
每日一题(2022-04-21)——山羊拉丁文