Is it possible in go to get a "Type" without an instance? I've seen some examples that utilize reflect.TypeOf()
but they all deal with an instance.
Below is a snippet of what I am attempting to do:
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)) {
// ....
} / ....
}
An example of my usage would be
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)
}
}
Note, after writing this out, I realize I could provide a "RequireUint64"
, "RequireUint32"
, etc.. perhaps that would be the Go way?
Aucun commentaire:
Enregistrer un commentaire