首页 > 其他分享 >Go - Web Application 4

Go - Web Application 4

时间:2024-09-04 19:03:27浏览次数:11  
标签:Web http middleware next Application myMiddleware handler Go your

How middleware works

In fact, we’re actually already using some middleware in our application — the http.StripPrefix() function from serving static files, which removes a specific prefix from the request’s URL path before passing the request on to the file server.

 

The pattern

The standard pattern for creating your own middleware looks like this:

func myMiddleware(next http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        // TODO: Execute our middleware logic here...
        next.ServeHTTP(w, r)
    }
    return http.HandlerFunc(fn)
}

The code itself is pretty succinct, but there’s quite a lot in it to get your head around.

  • The myMiddleware() function is essentially a wrapper around the next handler, which we pass to it as a parameter.
  • It establishes a function fn which closes over the next handler to form a closure. When fn is run it executes our middleware logic and then transfers control to the next handler by calling it’s ServeHTTP() method.
  • Regardless of what you do with a closure it will always be able to access the variables that are local to the scope it was created in — which in this case means that fn will always have access to the next variable.
  • In the final line of code, we then convert this closure to a http.Handler and return it using the http.HandlerFunc() adapter.

If this feels confusing, you can think of it more simply: myMiddleware() is a function that accepts the next handler in a chain as a parameter. It returns a handler which executes some logic and then calls the next handler.

 

Simplifying the middleware

A tweak to this pattern is to use an anonymous function inside myMiddleware() middleware, like so:

func myMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // TODO: Execute our middleware logic here...
        next.ServeHTTP(w, r)
    })
}

 

Positioning the middleware

It’s important to explain that where you position the middleware in the chain of handlers will affect the behavior of your application.

If you position your middleware before the servemux in the chain then it will act on every request that your application receives.

myMiddleware → servemux → application handler

A good example of where this would be useful is middleware to log requests — as that’s typically something you would want to do for all requests.

Alternatively, you can position the middleware after the servemux in the chain — by wrapping a specific application handler. This would cause your middleware to only be executed for a specific route.

servemux → myMiddleware → application handler

An example of this would be something like authorization middleware, which you may only want to run on specific routes.

标签:Web,http,middleware,next,Application,myMiddleware,handler,Go,your
From: https://www.cnblogs.com/zhangzhihui/p/18397194

相关文章

  • 基于Javaweb实现的物流管理系统设计与实现(源码+数据库+论文+部署+文档+讲解视频等)
    文章目录1.前言2.系统演示录像3.论文参考4.代码运行展示图5.技术框架5.1SpringBoot技术介绍5.2Vue技术介绍6.可行性分析7.系统测试7.1系统测试的目的7.2系统功能测试8.数据库表设计9.代码参考10.数据库脚本11.找我做程序,有什么保障?12.联系我们1.前......
  • VSCode Webview 插件开发的模板的踩坑记录
    问题CSP:refusedxxxxxx常见的几类报错(打开开发者工具,在控制台就会自动输出)refusedtoapplyinlinestylebecauseitviolatesthefollowingContentSecurityPolicydirectivexxxxxxrefusedtoloadthescript''becauseitviolatesthefollowingContentSecuri......
  • 动态引入模块:Webpack require.context 的灵活运用
    require.context是一个非常有用的WebpackAPI,它允许我们在编译时动态地引入模块。这个功能在一些场景下非常有用,比如需要动态加载模块、实现国际化、主题切换等功能时会经常用到。require.contextAPI说明官方文档:依赖管理|webpack中文文档首先,让我们了解一下require......
  • fatal: unable to access 'https://aomedia.googlesource.com/aom.git/': Failed to c
     低版本的Mac安装PHP就是受罪brewinstallshivammathur/php/[email protected]:YouareusingmacOS11.We(andApple)donotprovidesupportforthisoldversion.Itisexpectedbehaviourthatsomeformulaewillfailtobuildinthisoldversion.Itisexpec......
  • JavaWeb
    JavaWeb1.Servlet<?xmlversion="1.0"encoding="UTF-8"?><web-appxmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="......
  • C# WebSocket高并发通信阻塞问题
    项目上遇到使用WebSocket超时问题,具体情况是这样的,OTA升级过程中,解压zip文件会有解压进度事件,将解压进度通过进程通信传给另一进程,通信提示超时异常小伙伴堂园发现大文件使用Zip解压,解压进度事件间隔竟然是1ms,简直超大频率啊但是,解压事件超频也不应该通信异常啊,于是我通过1ms定......
  • mac 上golang编译 安卓系统的so 错误 'android/log.h' file not found
    lib.gopackagemainimport"C"//exportSpeedTestfuncSpeedTest(config*C.char){ configContent:=C.GoString(config) run(configContent)}funcmain(){}需要安装NDK,用Androidstudio安装,在SDKManeger的SDKTool里选择安装NDK(sidebyside),成功后一般在......
  • django空巢老人志愿服务系统-计算机毕业设计源码58726
    摘 要随着社会老龄化问题日益突出,空巢老人群体的关注和关怀日益重要。本研究设计并实现了基于Python的空巢老人志愿服务系统,旨在利用技术手段提供更多关爱和支持给空巢老人群体。该系统结合Python编程语言的灵活性和易用性,实现了慈善捐赠、医院信息查询、志愿活动发布、志......
  • 国产化:springboot项目TongWeb替换tomcat踩坑实录
    前言全流程记录Tongweb替换Tomcat过程,最终实现为使用内嵌的Tongweb依赖替换SpringBoot默认的Tomcat,所以可直接从第5节开始看如何使用内嵌TongWeb替换Tomcat。1背景国产化浪潮下,项目要求实现web服务器的国产化,使用Tongweb替换Tomcat,商业版的Tongweb是单独启动的一个服务,需要......
  • 通过引人入胜的Web故事,从Google Discover获取自然流量
    通过研究热门话题并创建引人入胜的网页故事,AatifMohd在6个月内通过GoogleDiscover提升了220万的自然流量。这让我们不禁想到,这些成功是否也能应用到AI驱动的流量增长中呢?例如,光年AI平台提供了一种简单易上手的工作流机制,可以帮助企业轻松创建引人入胜的内容,并将它们高效地......