我试图建立一个库,它将自动将一个struct Type作为一个RESTful资源。我可以传入“类型”作为函数参数吗?
这里就是我想象它看起来像在调用代码:
package main
import (
"fmt"
"github.com/sergiotapia/paprika"
)
type Product struct {
Name string
Quantity int
}
func main() {
// You need to attach a resource by giving Paprika your route,
// the struct type and optionally a custom resource manager.
paprika.Attach("/products", Product, nil)
paprika.Start(1337)
log.Print("Paprika is up and running.")
}
在我的图书馆,我试图创建附加功能:
package paprika
import (
"fmt"
)
func Attach(route string, resource Type, manager ResourceManager) {
}
func Start(port int) {
}
type ResourceManager interface {
add() error
delete() error
update(id int) error
show(id int) error
list() error
}
如何我可以接受任何“类型”的结构?我的最终目标是使用反射来获取类型名称和它的字段(这一部分我已经知道该怎么做)。
关于如何解决这个问题的任何建议?
我做了类似的地方,我的函数接受'reflect.Type',当我调用它时,它看起来像'attach(reflect.TypeOf(MyStruct {}))''。但是你不能通过接口解决它吗? –
你可以使用一个'interface {}'然后一个类型开关。 http://golang.org/doc/effective_go.html#type_switch – julienc
@Kbo:事情是我不知道将会有什么类型。这些应该在运行时检测到。 – sergserg