问题描述
好的,我有,或者正在编写一个名为mao的web框架包。
我希望在控制器中定义我的Route。(
$ b
)
type(
Controller struct {
Route Route
路由结构{
名称,主机,路径,方法字符串
}
)
in mao import package
controller / default.go
类型DefaultController结构{
mao.Controller
}
func(this * DefaultController)Index()Response {
this.Route =maro.Route {default_index,localhost,/,GET}
}
现在因为我想在控制器中定义我的路由,所以路由器在instanced时应该读取所有控制器。这就是问题所在。
如何将包名称传递给我的路由器,以便能够获取该包中的所有结构和函数?它甚至有可能吗?
你在Go中不可能的,因为它没有办法枚举所有类型都在包/程序中。
另一种方法是遵循 database / sql
包,并且有一个系统,其他软件包可以在导入时注册。
例如,要将PostgreSQL驱动程序与该软件包配合使用,您可以:
import(
_github.com/lib/pq
database / sql
)
...
db,err:= sql.Open(postgres,dbname = test)
postgres驱动程序在初始化 github.com/lib/pq
包期间注册。以下是该软件包的相关代码(省略了一些不相关的部分):
软件包pq
导入(
数据库/ sql
)
类型drv结构{}
func(d * drv)打开(名称字符串)(driver.Conn,error){
return Open(name)
}
func init(){
sql.Register(postgres,& drv {})
}
也许你可以创建一个这样的注册API来找到程序中有多种实现?
Ok.. I have, or am writing a web framework package, called mao.
I'd like to have my Route defined in the controller.
in mao
type (
Controller struct {
Route Route
}
Route struct {
Name, Host, Path, Method string
}
)
in mao importing package
controller/default.go
type DefaultController struct {
mao.Controller
}
func (this *DefaultController) Index() Response {
this.Route = mao.Route{"default_index","localhost","/", "GET"}
}
Now since I'd like to define my route inside the controller, the router, when instanced should read all controllers. That's the problem.
How do I pass the package name to my router so it's able to get all structs and functions in that package? Is it even possible?
What you ask isn't possible in Go, since it doesn't have a way to enumerate all types in a package/program.
One alternative would be to follow the lead of the database/sql
package, and have a system where other packages can register with it when imported.
For example, to use the PostgreSQL driver with that package, you might do:
import (
_ "github.com/lib/pq"
"database/sql"
)
...
db, err := sql.Open("postgres", "dbname=test")
The postgres driver is registered during initialisation of the github.com/lib/pq
package. Here is the relevant code from that package (eliding some parts that aren't relevant):
package pq
import (
"database/sql"
)
type drv struct{}
func (d *drv) Open(name string) (driver.Conn, error) {
return Open(name)
}
func init() {
sql.Register("postgres", &drv{})
}
Perhaps you could create a registration API like this to find the various implementations available in the program?
这篇关于去:反思catch22反映包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!