英文:
Preserve structs data for using it later
问题
我正在学习使用Golang编写小型Web博客,并编写路由器(我知道有一些可用的,如gorilla mux、martini等)。
我有一个简单的结构体:
type Routes struct {
method string
pattern string
handler Handler
}
还有一些正则表达式匹配器。但是我不明白如何将我定义的所有路由保存在一个地方。使用结构体切片(例如[]Routes
)来将它们全部保存在一起是一个好主意吗?
附注:这是为了个人理解它们如何一起工作。
英文:
I'm learning golang - coding small web blog, and writing router(I know there are available few - gorilla mux, martini, etc).
I have simple struct
type Routes struct {
method string
pattern string
handler Handler
}
and some regex matchers. But i can't understand how do i keep all routes that i will define in one place. Is using slice of structs good idea(like
[]Routes
) to keep them all together?
P.S. This is meant for personal understanding of how it all works together
答案1
得分: 1
你的问题并没有很好地定义。你告诉我们你想基于正则表达式实现路由功能,但你没有告诉我们你想要实现哪种任务,这将极大地影响到最佳的数据结构选择。
你已经提到你知道很多其他的开源实现,也许你应该查看它们的源代码。
这个答案可能对你有所帮助,它展示了一个简单的基本实现,如何使用正则表达式来实现路由功能。
如果你只想注册正则表达式,如果请求路径与之匹配,然后将服务转发给一个Handler
,那么将"规则"存储在[]Routes
中是一个可行且简单的选项。
需要注意的事项:
-
我肯定会提前编译正则表达式并存储结果,而不是每次都编译,这样会浪费大量资源。所以你的
Routes
结构应该包含一个*regexp.Regexp
类型的字段,而不是模式(你可以保留string
模式,例如用于调试目的)。 -
如果你的
Routes
结构变得更大,我会考虑在切片中存储指针而不是结构值,例如[]*Routes
,因为每次循环遍历它们(例如在每个请求中查看哪些匹配)或者每当你从其中一个Routes
创建一个局部变量时,都会复制值。与复制指针相比,复制大型结构是低效的。
英文:
Your question is not really well defined. You told us you want to implement routing functionality based on regular expressions, but you haven't told us what kind of tasks you want to achieve which greatly influence the optimal or best data structure to be used.
You already mentioned you know about a lot of other implementations which are open source, maybe you should check their sources.
This answer might also be a help to you which shows a simple implementation of a basic implementation how to do routing functionality using regular expressions.
If you just want to be able to register regular expressions which if matched by the request path and then forward the serving to a Handler
, yes, storing the "rules" in a []Routes
is a viable and simple option.
Things to keep in mind:
-
I would definitely compile the regexp in advance and store the result and not compile them each time which is an awful waste of resources. So your
Routes
struct should contain a field of type*regexp.Regexp
instead of the pattern (you can keep thestring
pattern too e.g. for debugging purposes). -
If your
Routes
struct grows bigger, I would consider storing pointers in the slice and not struct values, e.g.[]*Routes
because each time when you loop over them (e.g. in each request to see which matches) or whenever you create a local variable from one of theRoutes
, a copy is made from the values. Copying large struct is inefficient compared to copying a pointer which is fast.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论