1
votes

I'm trying to figure out how to set up middlewares, and right now I've got something like:

func applyMiddleware(h *Handle) *Handle {
   return a(b(c(h)))
}

Is there a way to "compose" these functions so I can just pass a list of Handle(s) and it will return the composed function?

1
Can you provide the signature for a, b, or c? - kingkupps
they must be func(*Handle) *Handle otherwise it is not valid go code. - mh-cbon
Ahh yeah you're right thanks didn't think that through.. - kingkupps

1 Answers

4
votes

use a slice

https://play.golang.org/p/DrEnGkIEbU3

package main

import (
    "fmt"
)

func main() {
    fmt.Println(v(v(v(0))))
    fmt.Println(compose(v, v, v)(0))
}
func v(i int) int {
    return i + 1
}
func compose(manyv ...func(int) int) func(int) int {
    return func(i int) int {
        for _, v := range manyv {
            i = v(i)
        }
        return i
    }
}