dongyi1215 2019-07-04 02:26
浏览 45
已采纳

如何使用多种方法将中间件写入接口?

I got a interface with more than one method. I wonder how to write a middleware for it.

I seek in Google but found all the answers are for interface with only one method. I found nothing for my problem. And I try to write a demo, but it does not work.

package main

import (
    "fmt"
    "strconv"
)

type ti interface {
    Say(int) string
    Eat(string) int
}

type Middleware func(ti) ti

func GetMiddleWare(t ti) ti {
    var tm ti
    t.Say = func(i int) string {
        fmt.Println("arg is " + strconv.Itoa(i))
        var ret string
        defer func() {
            fmt.Println("ret is " + ret)
        }()
        ret = t.Say(i)
        return ret
    }
    t.Eat = func(s string) int {
        fmt.Println("arg is " + s)
        var ret int
        defer func() {
            fmt.Println("ret is " + strconv.Itoa(ret))
        }()
        ret = t.Eat(s)
        return ret
    }
    return tm
}

it does not work

.\main.go:17:8: cannot assign to t.Say
.\main.go:26:8: cannot assign to t.Eat

So, how can I write a middleware for an interface with more than one method?

  • 写回答

1条回答 默认 最新

  • doulidai6316 2019-07-04 02:48
    关注

    Define a type that wraps the value. Implement the interface methods on that type.

    // Middleware wraps the value t with logging.
    type Middleware struct {
        t ti
    }
    
    func (m Middleware) Say(i int) string {
        fmt.Println("arg is " + strconv.Itoa(i))
        var ret string
        defer func() {
            fmt.Println("ret is " + ret)
        }()
        ret = m.t.Say(i)
        return ret
    }
    
    func (m Middleware) Eat(s string) int {
        fmt.Println("arg is " + s)
        var ret int
        defer func() {
            fmt.Println("ret is " + strconv.Itoa(ret))
        }()
        ret = m.t.Eat(s)
        return ret
    }
    
    func GetMiddleWare(t ti) ti {
        return Middleware{t}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?