Skip to content

Instantly share code, notes, and snippets.

@fotonmoton
Created October 6, 2023 19:08
Show Gist options
  • Save fotonmoton/5b5805ebab83cd0d1b3c722530032495 to your computer and use it in GitHub Desktop.
Save fotonmoton/5b5805ebab83cd0d1b3c722530032495 to your computer and use it in GitHub Desktop.
Golang Closures for decorator/middleware pattern
package main
import "fmt"
func Decorator(fn func(string)) func(string) {
return func(s string) {
fmt.Println("-----")
fn(s)
fmt.Println("-----")
}
}
func Message(message string) func(string) {
return func(s string) {
fmt.Printf("%s, %s!\n", message, s)
}
}
func Hello(something string) {
fmt.Printf("Hello, %s!\n", something)
}
func HelloWorld() {
fmt.Println("Hello, World!")
}
func main() {
fmt.Println("Hello, World!")
HelloWorld()
Hello("Mars")
Hello("Jupiter")
AnotherHello := Message("Hello")
Bye := Message("Bye")
AnotherHello("Mars")
Bye("Mars")
Bye("Jupiter")
DecoratedBye := Decorator(Bye)
DecoratedBye("Jupiter")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment