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}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥18 模拟电路问题解答有偿
  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题