【发布时间】:2018-08-03 00:17:09
【问题描述】:
是否有可能在没有实例的情况下获得“类型”?我见过一些使用reflect.TypeOf() 的示例,但它们都处理一个实例。
下面是我正在尝试做的一个 sn-p:
import (
"net/http"
)
type ParamReader struct {
// The request from which to extract parameters
context *http.Request
}
// Initialize the ParamReader with a specific http request. This serves
// as the 'context' of our param reader. All subsequent calls will validate
// the params that are present on this assigned http.Request
func (p *ParamReader) Context(r *http.Request) {
p.context = r
}
// Validate that a given param 's' is both present and a valid
// value of type 't'. A value is demeed valid if a conversion from
// its string representation to 't' is possible
func(p *ParamReader) Require(s string, t Type) {
// if context not have 's'
// addError('s' is not present)
// return
if( t == typeof(uint64)) {
// If not s -> uint64
// addError('s' is not a valid uint64)
} else if (t == typeof(uint32)) {
// ....
} / ....
}
我的用法是
func (h *Handler) OnRequest(r *http.Request) {
h.ParamReader.Context(r)
h.ParamReader.Require("age", uint16)
h.ParamReader.Require("name", string)
h.ParamReader.Require("coolfactor", uint64)
h.ParamReader.Optional("email", string, "unspecified")
h.ParamReader.Optional("money", uint64, "0")
if h.ParamReader.HasErrors() {
// Iterate or do something about the errors
} else {
coolness := h.ParamReader.ReadUint64("coolfactor")
email := h.ParamReader.ReadString("email")
money := h.ParamReader.ReadUint64(0)
}
}
注意,写完后,我意识到我可以提供"RequireUint64"、"RequireUint32" 等。也许这就是 Go 方式?
【问题讨论】:
-
@tkausl,这个例子几乎就像我想要完成的那样。唯一的区别是他们传入
"hello"的地方,我想传入typeof(string)之类的东西。我的用例是我实际上没有该示例所示的实例。
标签: go reflection types