我正在Go中实现一个简单的路由器。当没有为该终结点实现调用的方法时,我曾经为每个终结点返回一个错误而使用大量冗余代码。我重构并制作了一个“基本”类型,该类型为每种请求类型提供了默认功能,这些功能仅返回未实现的错误。现在,我要做的就是为我要实现的给定端点重写特定的方法功能。在给定端点变量的情况下,直到我想弄清楚哪些方法已被覆盖,这一切都是有趣的游戏。
省略无关的细节,这是我现在想到的一个简单示例:
package main
import (
"fmt"
)
// Route defines the HTTP method handlers.
type Route interface {
Get() string
Post() string
}
// BaseRoute is the "fallback" handlers,
// if those handlers aren't defined later.
type BaseRoute struct{}
func (BaseRoute) Get() string {
return "base get"
}
func (BaseRoute) Post() string {
return "base post"
}
// Endpoint holds a route for handling the HTTP request,
// and some other metadata related to that request.
type Endpoint struct …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 go 中实现一组功能。上下文是一个事件服务器;我想防止(或至少警告)为一个事件多次添加相同的处理程序。
我读过,地图通常用作集合,因为可以轻松检查成员资格:
if _, ok := set[item]; ok {
// don't add item
} else {
// do add item
}
Run Code Online (Sandbox Code Playgroud)
不过,我在使用这种函数范式时遇到了一些麻烦。这是我的第一次尝试:
// this is not the actual signature
type EventResponse func(args interface{})
type EventResponseSet map[*EventResponse]struct{}
func (ers EventResponseSet) Add(r EventResponse) {
if _, ok := ers[&r]; ok {
// warn here
return
}
ers[&r] = struct{}{}
}
func (ers EventResponseSet) Remove(r EventResponse) {
// if key is not there, doesn't matter
delete(ers, &r)
}
Run Code Online (Sandbox Code Playgroud)
很明显为什么这行不通:函数不是 Go 中的引用类型,尽管有些人会告诉你它们是。 …
是否可以在Go中获取函数引用的地址?
就像是
func myFunction() {
}
// ...
unsafe.Pointer(&myFunction)
Run Code Online (Sandbox Code Playgroud)
只是那是行不通的。我的猜测是不可能的,但是我还没有找到任何证据。
编辑:背景
我的问题的背景来自于处理CGO和C函数指针。这有效:
/*
void go_myFunction();
typedef void (*myFunction_f)();
myFunction_f pMyFunction;
*/
import "C"
//export go_myFunction
func go_myFunction() {
// ...
}
func SetupFp() {
C.pMyFunction = (*[0]byte)(unsafe.Pointer(C.go_myFunction))
}
Run Code Online (Sandbox Code Playgroud)
我也知道文档说明将指针传递给go函数不起作用。但是上面的代码似乎离它没有那么远。我只是想知道是否可以以某种方式跳过导出步骤。