我只是发表我的代码:
/*
* Role will ALWAYS reserve the session key "role".
*/
package goserver
const (
ROLE_KEY string = "role"
)
type Role string
//if index is higher or equal than role, will pass
type RolesHierarchy []Role
func (r Role) String() string {
return string(r)
}
func NewRole(session ServerSession) Role {
return session.GetValue(ROLE_KEY).(Role)
}
func (this Role) IsRole(role Role, hierarchy RolesHierarchy) bool {
if role == this {
return true
}
if len(hierarchy) == 0 {
return false
}
var thisI int = 0
var roleI int = 0
//Duped roles in hierarchy are verified in verifyConfig during parse
for i, r := range hierarchy {
if this == r {
thisI = i
}
if role == r {
roleI = i
}
}
//TODO I can probably condense what follows into one if
if thisI == 0 && roleI == 0 {
return false
}
return thisI >= roleI
}
func (this *Role) AssumeRole(session ServerSession, role Role) {
session.SetValue(ROLE_KEY, role)
*this = role
}
需要注意的是,ServerSession也是一个接口,称之为"ServerSessioner"感觉很奇怪。
我在考虑创建一个拥有IsRole()和AssumeRole()方法的接口,但是"Roler"听起来很奇怪。我开始意识到我并不真正知道或者从来没有遇到过接口命名规范,除了标准的"er"后缀以外。我似乎记得VS C++的约定就是在每个名称前面加上"I"。这种方式是否符合"惯用语"呢?
有什么建议吗?
RoleSupport
,但是前往英文论坛寻求帮助也是一个有趣的尝试。请不要使用this
来命名方法接收者:这被认为是Go语言中不符合惯用法的做法。这里有一个讨论此类问题的例子。 - kostix