1+# How to build one effective middleware?2+3+## Consitituent part4+5+The middleware has two parts:6+7+ - part one is what is executed once, when you initalize your middleware. That's where you set up all the global objects, logicals etc. Everything that happens one per application lifetime.8+9+ - part two is what executes on every request. For example, a database middleware you simply inject your "global" database object into the context. Once it's inside the context, you can retrieve it from within other middlewares and your handler furnction.10+11+```go12+func funcName(params string) gin.HandlerFunc {13+ // <---14+ // This is part one15+ // --->16+ // The follow code is an example17+ if err := check(params); err != nil {18+ panic(err)19+ }20+21+ return func(c *gin.Context) {22+ // <---23+ // This is part two24+ // --->25+ // The follow code is an example26+ c.Set("TestVar", params)27+ c.Next() 28+ }29+}30+```31+32+## Execution process33+34+Firstly, we have the follow example code:35+36+```go37+func main() {38+ router := gin.Default()39+40+ router.Use(globalMiddleware())41+42+ router.GET("/rest/n/api/*some", mid1(), mid2(), handler)43+44+ router.Run()45+}46+47+func globalMiddleware() gin.HandlerFunc {48+ fmt.Println("globalMiddleware...1")49+50+ return func(c *gin.Context) {51+ fmt.Println("globalMiddleware...2")52+ c.Next()53+ fmt.Println("globalMiddleware...3")54+ }55+}56+57+func handler(c *gin.Context) {58+ fmt.Println("exec handler.")59+}60+61+func mid1() gin.HandlerFunc {62+ fmt.Println("mid1...1")63+64+ return func(c *gin.Context) {65+66+ fmt.Println("mid1...2")67+ c.Next()68+ fmt.Println("mid1...3")69+ }70+}71+72+func mid2() gin.HandlerFunc {73+ fmt.Println("mid2...1")74+75+ return func(c *gin.Context) {76+ fmt.Println("mid2...2")77+ c.Next()78+ fmt.Println("mid2...3")79+ }80+}81+```82+83+According to [Consitituent part](#consitituent-part) said, when we run the gin process, **part one** will execute firstly and will print the follow information:84+85+```go86+globalMiddleware...187+mid1...188+mid2...189+```90+91+And init order are:92+93+```go94+globalMiddleware...195+ |96+ v97+mid1...198+ |99+ v100+mid2...1101+```102+103+When we curl one request `curl -v localhost:8080/rest/n/api/some`, **part two** will execute their middleware and output the following information:104+105+```go106+globalMiddleware...2107+mid1...2108+mid2...2109+exec handler.110+mid2...3111+mid1...3112+globalMiddleware...3113+```114+115+In other words, run order are:116+117+```go118+globalMiddleware...2119+ |120+ v121+mid1...2122+ |123+ v124+mid2...2125+ |126+ v127+exec handler.128+ |129+ v130+mid2...3131+ |132+ v133+mid1...3134+ |135+ v136+globalMiddleware...3137+```