Last active
June 11, 2023 08:07
-
-
Save manhdaovan/1baf5d6211a941b093eaad631d7b72be to your computer and use it in GitHub Desktop.
Simple simulation for gRPC ChainUnaryServer - interceptors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type handler func (string) string | |
type interceptor func(string, handler) string | |
func chainInterceptor(interceptors ...interceptor) interceptor { | |
interceptorsLen := len(interceptors) | |
lastIdx := interceptorsLen - 1 | |
return func(originStr string, lastHandler handler) string { | |
var ( | |
curIdx int | |
chainHandler handler | |
) | |
chainHandler = func(str string) string { | |
if curIdx == lastIdx { | |
return lastHandler(str) | |
} | |
curIdx ++ | |
r := interceptors[curIdx](str, chainHandler) | |
return r | |
} | |
return interceptors[0](originStr, chainHandler) | |
} | |
} | |
func main() { | |
interceptor1 := func(str string, handler1 handler) string { | |
str += "im in interceptor1 |" | |
fmt.Println("im in interceptor1, str = ", str) | |
return handler1(str) | |
} | |
interceptor2 := func(str string, handler2 handler) string { | |
str += "im in interceptor2 |" | |
fmt.Println("im in interceptor2, str = ", str) | |
return handler2(str) | |
} | |
interceptor3 := func(str string, handler3 handler) string { | |
str += "im in interceptor3 |" | |
fmt.Println("im in interceptor3, str = ", str) | |
return handler3(str) | |
} | |
lastHandler := func(str string) string { | |
fmt.Println("str ------- ", str) | |
return str | |
} | |
chainInterceptor(interceptor1, interceptor2, interceptor3)("aaa", lastHandler) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple HTTP handlers chain (middleware)
or even simpler for chain function