-3

我正在尝试为我的函数制作类似于用于 http.HandlerFunc 的模式的中间件,这通常有效:

func middleware(fn http.HandlerFunc) http.HandlerFunc {
    return func (wr http.ResponseWriter, r *http.Request) {
        fmt.Println("doing something before")
        fn(wr, r)
    }
}

func main() {
    middleware(func (wr http.ResponseWriter, r *http.Request) {
        wr.Write([]byte("..."))
    })
}

这不起作用:

package main

import (
    "fmt"
)

type FN func (arg int)

func myFunc(arg int) {
    fmt.Println("Arg:",arg)
}
// Logically here I am returning the function not it's value
// http package does this identically, I don't see the difference
func do(fn FN) FN {
    return func (arg int) {
        fn(arg)
    }
}

func main() {
    do(myFunc(3))
}

将返回编译错误:myFunc(3) used as value

正如你在这里看到的: https ://golang.org/src/net/http/server.go?s=64103:64150#L2055

在线 2065:

// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)

这个函数签名也不会返回一个值,但它会编译。

更新:

这种模式是我试图实现的,现在有效。

package main

import (
 "fmt"
)

type FN func (arg int)
func do(fn FN) FN {
    return func (arg int) {
    fmt.Println("executed do with arg",arg)
    // some other code ...
    fn(arg) // call wrapped function
   }
}
func something(arg int){
fmt.Println("Executed something with arg",arg)
}

func main() {
   do(something)(3)
}

输出:

executed do with arg 3
Executed something with arg 3

Program exited.
4

1 回答 1

2

您正在使用myFunc(arg int)- 它不返回任何内容,并试图将其返回值传递给do. 看起来你可能想做:

func main() {
    do(myFunc)(3)
}

但不太确定

于 2021-02-18T09:33:18.963 回答