_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3
values | text stringlengths 52 85.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q170300 | RootFromDatacenter | validation | func (p RootPathParticle) RootFromDatacenter(dc *object.Datacenter) string {
return dc.InventoryPath + "/" + string(p)
} | go | {
"resource": ""
} |
q170301 | PathFromDatacenter | validation | func (p RootPathParticle) PathFromDatacenter(dc *object.Datacenter, relative string) string {
return p.RootFromDatacenter(dc) + "/" + relative
} | go | {
"resource": ""
} |
q170302 | SplitDatacenter | validation | func (p RootPathParticle) SplitDatacenter(inventoryPath string) (string, error) {
s := strings.SplitN(inventoryPath, p.Delimiter(), 2)
if len(s) != 2 {
return inventoryPath, fmt.Errorf("could not split path %q on %q", inventoryPath, p.Delimiter())
}
return s[0], nil
} | go | {
"resource": ""
} |
q170303 | SplitRelativeFolder | validation | func (p RootPathParticle) SplitRelativeFolder(inventoryPath string) (string, error) {
relative, err := p.SplitRelative(inventoryPath)
if err != nil {
return inventoryPath, err
}
return path.Dir(relative), nil
} | go | {
"resource": ""
} |
q170304 | NewRootFromPath | validation | func (p RootPathParticle) NewRootFromPath(inventoryPath string, newParticle RootPathParticle) (string, error) {
dcPath, err := p.SplitDatacenter(inventoryPath)
if err != nil {
return inventoryPath, err
}
return fmt.Sprintf("%s/%s", dcPath, newParticle), nil
} | go | {
"resource": ""
} |
q170305 | datacenterPathFromHostSystemID | validation | func datacenterPathFromHostSystemID(client *govmomi.Client, hsID string) (string, error) {
hs, err := hostsystem.FromID(client, hsID)
if err != nil {
return "", err
}
return RootPathParticleHost.SplitDatacenter(hs.InventoryPath)
} | go | {
"resource": ""
} |
q170306 | datastoreRootPathFromHostSystemID | validation | func datastoreRootPathFromHostSystemID(client *govmomi.Client, hsID string) (string, error) {
hs, err := hostsystem.FromID(client, hsID)
if err != nil {
return "", err
}
return RootPathParticleHost.NewRootFromPath(hs.InventoryPath, RootPathParticleDatastore)
} | go | {
"resource": ""
} |
q170307 | validateDatastoreFolder | validation | func validateDatastoreFolder(folder *object.Folder) (*object.Folder, error) {
ft, err := FindType(folder)
if err != nil {
return nil, err
}
if ft != VSphereFolderTypeDatastore {
return nil, fmt.Errorf("%q is not a datastore folder", folder.InventoryPath)
}
return folder, nil
} | go | {
"resource": ""
} |
q170308 | validateHostFolder | validation | func validateHostFolder(folder *object.Folder) (*object.Folder, error) {
ft, err := FindType(folder)
if err != nil {
return nil, err
}
if ft != VSphereFolderTypeHost {
return nil, fmt.Errorf("%q is not a host folder", folder.InventoryPath)
}
return folder, nil
} | go | {
"resource": ""
} |
q170309 | validateVirtualMachineFolder | validation | func validateVirtualMachineFolder(folder *object.Folder) (*object.Folder, error) {
ft, err := FindType(folder)
if err != nil {
return nil, err
}
if ft != VSphereFolderTypeVM {
return nil, fmt.Errorf("%q is not a VM folder", folder.InventoryPath)
}
log.Printf("[DEBUG] Folder located: %q", folder.InventoryPath)... | go | {
"resource": ""
} |
q170310 | validateNetworkFolder | validation | func validateNetworkFolder(folder *object.Folder) (*object.Folder, error) {
ft, err := FindType(folder)
if err != nil {
return nil, err
}
if ft != VSphereFolderTypeNetwork {
return nil, fmt.Errorf("%q is not a network folder", folder.InventoryPath)
}
return folder, nil
} | go | {
"resource": ""
} |
q170311 | NormalizePath | validation | func NormalizePath(v interface{}) string {
p := v.(string)
if PathIsEmpty(p) {
return ""
}
return strings.TrimPrefix(path.Clean(p), "/")
} | go | {
"resource": ""
} |
q170312 | MoveObjectTo | validation | func MoveObjectTo(ref types.ManagedObjectReference, folder *object.Folder) error {
ctx, cancel := context.WithTimeout(context.Background(), provider.DefaultAPITimeout)
defer cancel()
task, err := folder.MoveInto(ctx, []types.ManagedObjectReference{ref})
if err != nil {
return err
}
tctx, tcancel := context.With... | go | {
"resource": ""
} |
q170313 | Properties | validation | func Properties(folder *object.Folder) (*mo.Folder, error) {
ctx, cancel := context.WithTimeout(context.Background(), provider.DefaultAPITimeout)
defer cancel()
var props mo.Folder
if err := folder.Properties(ctx, folder.Reference(), nil, &props); err != nil {
return nil, err
}
return &props, nil
} | go | {
"resource": ""
} |
q170314 | FindType | validation | func FindType(folder *object.Folder) (VSphereFolderType, error) {
var ft VSphereFolderType
props, err := Properties(folder)
if err != nil {
return ft, err
}
// Depending on the container type, the actual folder type may be contained
// in either the first or second element, the former for clusters, datastore
... | go | {
"resource": ""
} |
q170315 | ToServerListQuery | validation | func (opts ListOpts) ToServerListQuery() (string, error) {
q, err := gophercloud.BuildQueryString(opts)
return q.String(), err
} | go | {
"resource": ""
} |
q170316 | Index | validation | func Index(vs []string, t string) int {
for i, v := range vs {
if v == t {
return i
}
}
return -1
} | go | {
"resource": ""
} |
q170317 | Any | validation | func Any(vs []string, f func(string) bool) bool {
for _, v := range vs {
if f(v) {
return true
}
}
return false
} | go | {
"resource": ""
} |
q170318 | client | validation | func client(path string) (*http.Client, error) {
if path == "" {
return google.DefaultClient(oauth2.NoContext, compute.ComputeScope)
}
key, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
jwtConfig, err := google.JWTConfigFromJSON(key, compute.ComputeScope)
if err != nil {
return nil, err
... | go | {
"resource": ""
} |
q170319 | lookupProject | validation | func lookupProject() (string, error) {
req, err := http.NewRequest("GET", "http://metadata.google.internal/computeMetadata/v1/project/project-id", nil)
if err != nil {
return "", err
}
req.Header.Add("Metadata-Flavor", "Google")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer... | go | {
"resource": ""
} |
q170320 | lookupZones | validation | func lookupZones(svc *compute.Service, project, pattern string) ([]string, error) {
call := svc.Zones.List(project)
if pattern != "" {
call = call.Filter("name eq " + pattern)
}
var zones []string
f := func(page *compute.ZoneList) error {
for _, v := range page.Items {
zones = append(zones, v.Name)
}
r... | go | {
"resource": ""
} |
q170321 | lookupAddrs | validation | func lookupAddrs(svc *compute.Service, project, zone, tag string) ([]string, error) {
var addrs []string
f := func(page *compute.InstanceList) error {
for _, v := range page.Items {
if len(v.NetworkInterfaces) == 0 || v.NetworkInterfaces[0].NetworkIP == "" {
continue
}
for _, t := range v.Tags.Items {
... | go | {
"resource": ""
} |
q170322 | New | validation | func New(opts ...Option) (*Discover, error) {
d := new(Discover)
for _, opt := range opts {
if err := opt(d); err != nil {
return nil, err
}
}
d.once.Do(d.initProviders)
return d, nil
} | go | {
"resource": ""
} |
q170323 | WithUserAgent | validation | func WithUserAgent(agent string) Option {
return func(d *Discover) error {
d.userAgent = agent
return nil
}
} | go | {
"resource": ""
} |
q170324 | WithProviders | validation | func WithProviders(m map[string]Provider) Option {
return func(d *Discover) error {
d.Providers = m
return nil
}
} | go | {
"resource": ""
} |
q170325 | Names | validation | func (d *Discover) Names() []string {
d.once.Do(d.initProviders)
var names []string
for n := range d.Providers {
names = append(names, n)
}
sort.Strings(names)
return names
} | go | {
"resource": ""
} |
q170326 | Help | validation | func (d *Discover) Help() string {
d.once.Do(d.initProviders)
h := []string{globalHelp}
for _, name := range d.Names() {
h = append(h, d.Providers[name].Help())
}
return strings.Join(h, "\n")
} | go | {
"resource": ""
} |
q170327 | Addrs | validation | func (d *Discover) Addrs(cfg string, l *log.Logger) ([]string, error) {
d.once.Do(d.initProviders)
args, err := Parse(cfg)
if err != nil {
return nil, fmt.Errorf("discover: %s", err)
}
name := args["provider"]
if name == "" {
return nil, fmt.Errorf("discover: no provider")
}
providers := d.Providers
if ... | go | {
"resource": ""
} |
q170328 | String | validation | func (c Config) String() string {
// sort 'provider' to the front and keep the keys stable.
var keys []string
for k := range c {
if k != "provider" {
keys = append(keys, k)
}
}
sort.Strings(keys)
keys = append([]string{"provider"}, keys...)
quote := func(s string) string {
if strings.ContainsAny(s, ` "... | go | {
"resource": ""
} |
q170329 | PodAddrs | validation | func PodAddrs(pods *corev1.PodList, args map[string]string, l *log.Logger) ([]string, error) {
hostNetwork := false
if v := args["host_network"]; v != "" {
var err error
hostNetwork, err = strconv.ParseBool(v)
if err != nil {
return nil, fmt.Errorf("discover-k8s: host_network must be boolean value: %s", err)... | go | {
"resource": ""
} |
q170330 | argsOrEnv | validation | func argsOrEnv(args map[string]string, key, env string) string {
if value, ok := args[key]; ok {
return value
}
return os.Getenv(env)
} | go | {
"resource": ""
} |
q170331 | Addrs | validation | func (p *Provider) Addrs(args map[string]string, l *log.Logger) ([]string, error) {
var params *m.QueryParam
var ch chan *m.ServiceEntry
var v6, v4 bool
var addrs []string
var err error
// default to null logger
if l == nil {
l = log.New(ioutil.Discard, "", 0)
}
// init params
params = new(m.QueryParam)
... | go | {
"resource": ""
} |
q170332 | setLog | validation | func setLog(l *log.Logger) {
if l != nil {
logger = l
} else {
logger = log.New(ioutil.Discard, "", 0)
}
} | go | {
"resource": ""
} |
q170333 | discoverErr | validation | func discoverErr(format string, a ...interface{}) error {
var s string
if len(a) > 1 {
s = fmt.Sprintf(format, a...)
} else {
s = format
}
return fmt.Errorf("discover-vsphere: %s", s)
} | go | {
"resource": ""
} |
q170334 | valueOrEnv | validation | func valueOrEnv(config map[string]string, key, env string) string {
if v := config[key]; v != "" {
return v
}
if v := os.Getenv(env); v != "" {
logger.Printf("[DEBUG] Using value of %s for configuration of %s", env, key)
return v
}
return ""
} | go | {
"resource": ""
} |
q170335 | newVSphereClient | validation | func newVSphereClient(ctx context.Context, host, user, password string, insecure bool) (*vSphereClient, error) {
logger.Println("[DEBUG] Connecting to vSphere client endpoints")
client := new(vSphereClient)
u, err := vimURL(host, user, password)
if err != nil {
return nil, fmt.Errorf("error generating SOAP endp... | go | {
"resource": ""
} |
q170336 | newVimSession | validation | func newVimSession(ctx context.Context, u *url.URL, insecure bool) (*govmomi.Client, error) {
logger.Printf("[DEBUG] Creating new SOAP API session on endpoint %s", u.Host)
client, err := govmomi.NewClient(ctx, u, insecure)
if err != nil {
return nil, fmt.Errorf("error setting up new vSphere SOAP client: %s", err)
... | go | {
"resource": ""
} |
q170337 | newRestSession | validation | func newRestSession(ctx context.Context, u *url.URL, insecure bool) (*tags.RestClient, error) {
logger.Printf("[DEBUG] Creating new CIS REST API session on endpoint %s", u.Host)
client := tags.NewClient(u, insecure, "")
if err := client.Login(ctx); err != nil {
return nil, fmt.Errorf("error connecting to CIS REST ... | go | {
"resource": ""
} |
q170338 | Addrs | validation | func (p *Provider) Addrs(args map[string]string, l *log.Logger) ([]string, error) {
if args["provider"] != "vsphere" {
return nil, discoverErr("invalid provider %s", args["provider"])
}
setLog(l)
tagName := args["tag_name"]
categoryName := args["category_name"]
host := valueOrEnv(args, "host", "VSPHERE_SERVER... | go | {
"resource": ""
} |
q170339 | tagIDFromName | validation | func tagIDFromName(ctx context.Context, client *tags.RestClient, name, category string) (string, error) {
logger.Printf("[DEBUG] Fetching tag ID for tag name %q and category %q", name, category)
categoryID, err := tagCategoryByName(ctx, client, category)
if err != nil {
return "", err
}
return tagByName(ctx, c... | go | {
"resource": ""
} |
q170340 | tagCategoryByName | validation | func tagCategoryByName(ctx context.Context, client *tags.RestClient, name string) (string, error) {
cats, err := client.GetCategoriesByName(ctx, name)
if err != nil {
return "", fmt.Errorf("could not get category for name %q: %s", name, err)
}
if len(cats) < 1 {
return "", fmt.Errorf("category name %q not foun... | go | {
"resource": ""
} |
q170341 | tagByName | validation | func tagByName(ctx context.Context, client *tags.RestClient, name, categoryID string) (string, error) {
tids, err := client.GetTagByNameForCategory(ctx, name, categoryID)
if err != nil {
return "", fmt.Errorf("could not get tag for name %q: %s", name, err)
}
if len(tids) < 1 {
return "", fmt.Errorf("tag name %... | go | {
"resource": ""
} |
q170342 | virtualMachineIPsForTag | validation | func virtualMachineIPsForTag(ctx context.Context, client *vSphereClient, id string) ([]string, error) {
vms, err := virtualMachinesForTag(ctx, client, id)
if err != nil {
return nil, err
}
return ipAddrsForVirtualMachines(ctx, client, vms)
} | go | {
"resource": ""
} |
q170343 | virtualMachinesForTag | validation | func virtualMachinesForTag(ctx context.Context, client *vSphereClient, id string) ([]*object.VirtualMachine, error) {
logger.Printf("[DEBUG] Locating all virtual machines under tag ID %q", id)
var vms []*object.VirtualMachine
objs, err := client.TagsClient.ListAttachedObjects(ctx, id)
if err != nil {
return nil... | go | {
"resource": ""
} |
q170344 | ipAddrsForVirtualMachines | validation | func ipAddrsForVirtualMachines(ctx context.Context, client *vSphereClient, vms []*object.VirtualMachine) ([]string, error) {
var addrs []string
for _, vm := range vms {
as, err := buildAndSelectGuestIPs(ctx, vm)
if err != nil {
return nil, err
}
addrs = append(addrs, as...)
}
return addrs, nil
} | go | {
"resource": ""
} |
q170345 | virtualMachineFromMOID | validation | func virtualMachineFromMOID(ctx context.Context, client *govmomi.Client, id string) (*object.VirtualMachine, error) {
logger.Printf("[DEBUG] Locating VM with managed object ID %q", id)
finder := find.NewFinder(client.Client, false)
ref := types.ManagedObjectReference{
Type: "VirtualMachine",
Value: id,
}
v... | go | {
"resource": ""
} |
q170346 | virtualMachineProperties | validation | func virtualMachineProperties(ctx context.Context, vm *object.VirtualMachine, keys []string) (*mo.VirtualMachine, error) {
logger.Printf("[DEBUG] Fetching properties for VM %q", vm.Name())
var props mo.VirtualMachine
if err := vm.Properties(ctx, vm.Reference(), keys, &props); err != nil {
return nil, err
}
retur... | go | {
"resource": ""
} |
q170347 | buildAndSelectGuestIPs | validation | func buildAndSelectGuestIPs(ctx context.Context, vm *object.VirtualMachine) ([]string, error) {
logger.Printf("[DEBUG] Discovering addresses for virtual machine %q", vm.Name())
var addrs []string
props, err := virtualMachineProperties(ctx, vm, []string{"guest.net"})
if err != nil {
return nil, fmt.Errorf("cannot... | go | {
"resource": ""
} |
q170348 | skipIPAddr | validation | func skipIPAddr(ip net.IP) bool {
switch {
case ip.IsLinkLocalMulticast():
fallthrough
case ip.IsLinkLocalUnicast():
fallthrough
case ip.IsLoopback():
fallthrough
case ip.IsMulticast():
return true
}
return false
} | go | {
"resource": ""
} |
q170349 | virtualMachineNames | validation | func virtualMachineNames(vms []*object.VirtualMachine) string {
var s []string
for _, vm := range vms {
s = append(s, vm.Name())
}
return strings.Join(s, ",")
} | go | {
"resource": ""
} |
q170350 | validateAndWrapHandler | validation | func validateAndWrapHandler(h Handler) Handler {
if reflect.TypeOf(h).Kind() != reflect.Func {
panic("Macaron handler must be a callable function")
}
if !inject.IsFastInvoker(h) {
switch v := h.(type) {
case func(*Context):
return ContextInvoker(v)
case func(*Context, *log.Logger):
return LoggerInvoke... | go | {
"resource": ""
} |
q170351 | validateAndWrapHandlers | validation | func validateAndWrapHandlers(handlers []Handler, wrappers ...func(Handler) Handler) []Handler {
var wrapper func(Handler) Handler
if len(wrappers) > 0 {
wrapper = wrappers[0]
}
wrappedHandlers := make([]Handler, len(handlers))
for i, h := range handlers {
h = validateAndWrapHandler(h)
if wrapper != nil && !... | go | {
"resource": ""
} |
q170352 | NewWithLogger | validation | func NewWithLogger(out io.Writer) *Macaron {
m := &Macaron{
Injector: inject.New(),
action: func() {},
Router: NewRouter(),
logger: log.New(out, "[Macaron] ", 0),
}
m.Router.m = m
m.Map(m.logger)
m.Map(defaultReturnHandler())
m.NotFound(http.NotFound)
m.InternalServerError(func(rw http.ResponseWrit... | go | {
"resource": ""
} |
q170353 | Handlers | validation | func (m *Macaron) Handlers(handlers ...Handler) {
m.handlers = make([]Handler, 0)
for _, handler := range handlers {
m.Use(handler)
}
} | go | {
"resource": ""
} |
q170354 | Use | validation | func (m *Macaron) Use(handler Handler) {
handler = validateAndWrapHandler(handler)
m.handlers = append(m.handlers, handler)
} | go | {
"resource": ""
} |
q170355 | ServeHTTP | validation | func (m *Macaron) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if m.hasURLPrefix {
req.URL.Path = strings.TrimPrefix(req.URL.Path, m.urlPrefix)
}
for _, h := range m.befores {
if h(rw, req) {
return
}
}
m.Router.ServeHTTP(rw, req)
} | go | {
"resource": ""
} |
q170356 | SetURLPrefix | validation | func (m *Macaron) SetURLPrefix(prefix string) {
m.urlPrefix = prefix
m.hasURLPrefix = len(m.urlPrefix) > 0
} | go | {
"resource": ""
} |
q170357 | SetConfig | validation | func SetConfig(source interface{}, others ...interface{}) (_ *ini.File, err error) {
cfg, err = ini.Load(source, others...)
return Config(), err
} | go | {
"resource": ""
} |
q170358 | String | validation | func (rb *RequestBody) String() (string, error) {
data, err := rb.Bytes()
return string(data), err
} | go | {
"resource": ""
} |
q170359 | RemoteAddr | validation | func (ctx *Context) RemoteAddr() string {
addr := ctx.Req.Header.Get("X-Real-IP")
if len(addr) == 0 {
addr = ctx.Req.Header.Get("X-Forwarded-For")
if addr == "" {
addr = ctx.Req.RemoteAddr
if i := strings.LastIndex(addr, ":"); i > -1 {
addr = addr[:i]
}
}
}
return addr
} | go | {
"resource": ""
} |
q170360 | HTML | validation | func (ctx *Context) HTML(status int, name string, data ...interface{}) {
ctx.renderHTML(status, DEFAULT_TPL_SET_NAME, name, data...)
} | go | {
"resource": ""
} |
q170361 | HTMLSet | validation | func (ctx *Context) HTMLSet(status int, setName, tplName string, data ...interface{}) {
ctx.renderHTML(status, setName, tplName, data...)
} | go | {
"resource": ""
} |
q170362 | Query | validation | func (ctx *Context) Query(name string) string {
ctx.parseForm()
return ctx.Req.Form.Get(name)
} | go | {
"resource": ""
} |
q170363 | QueryTrim | validation | func (ctx *Context) QueryTrim(name string) string {
return strings.TrimSpace(ctx.Query(name))
} | go | {
"resource": ""
} |
q170364 | QueryStrings | validation | func (ctx *Context) QueryStrings(name string) []string {
ctx.parseForm()
vals, ok := ctx.Req.Form[name]
if !ok {
return []string{}
}
return vals
} | go | {
"resource": ""
} |
q170365 | QueryEscape | validation | func (ctx *Context) QueryEscape(name string) string {
return template.HTMLEscapeString(ctx.Query(name))
} | go | {
"resource": ""
} |
q170366 | QueryBool | validation | func (ctx *Context) QueryBool(name string) bool {
v, _ := strconv.ParseBool(ctx.Query(name))
return v
} | go | {
"resource": ""
} |
q170367 | QueryInt | validation | func (ctx *Context) QueryInt(name string) int {
return com.StrTo(ctx.Query(name)).MustInt()
} | go | {
"resource": ""
} |
q170368 | QueryInt64 | validation | func (ctx *Context) QueryInt64(name string) int64 {
return com.StrTo(ctx.Query(name)).MustInt64()
} | go | {
"resource": ""
} |
q170369 | QueryFloat64 | validation | func (ctx *Context) QueryFloat64(name string) float64 {
v, _ := strconv.ParseFloat(ctx.Query(name), 64)
return v
} | go | {
"resource": ""
} |
q170370 | SetParams | validation | func (ctx *Context) SetParams(name, val string) {
if name != "*" && !strings.HasPrefix(name, ":") {
name = ":" + name
}
ctx.params[name] = val
} | go | {
"resource": ""
} |
q170371 | GetFile | validation | func (ctx *Context) GetFile(name string) (multipart.File, *multipart.FileHeader, error) {
return ctx.Req.FormFile(name)
} | go | {
"resource": ""
} |
q170372 | SaveToFile | validation | func (ctx *Context) SaveToFile(name, savePath string) error {
fr, _, err := ctx.GetFile(name)
if err != nil {
return err
}
defer fr.Close()
fw, err := os.OpenFile(savePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return err
}
defer fw.Close()
_, err = io.Copy(fw, fr)
return err
} | go | {
"resource": ""
} |
q170373 | GetCookie | validation | func (ctx *Context) GetCookie(name string) string {
cookie, err := ctx.Req.Cookie(name)
if err != nil {
return ""
}
val, _ := url.QueryUnescape(cookie.Value)
return val
} | go | {
"resource": ""
} |
q170374 | GetCookieInt | validation | func (ctx *Context) GetCookieInt(name string) int {
return com.StrTo(ctx.GetCookie(name)).MustInt()
} | go | {
"resource": ""
} |
q170375 | GetCookieInt64 | validation | func (ctx *Context) GetCookieInt64(name string) int64 {
return com.StrTo(ctx.GetCookie(name)).MustInt64()
} | go | {
"resource": ""
} |
q170376 | GetCookieFloat64 | validation | func (ctx *Context) GetCookieFloat64(name string) float64 {
v, _ := strconv.ParseFloat(ctx.GetCookie(name), 64)
return v
} | go | {
"resource": ""
} |
q170377 | SetSecureCookie | validation | func (ctx *Context) SetSecureCookie(name, value string, others ...interface{}) {
ctx.SetSuperSecureCookie(defaultCookieSecret, name, value, others...)
} | go | {
"resource": ""
} |
q170378 | GetSecureCookie | validation | func (ctx *Context) GetSecureCookie(key string) (string, bool) {
return ctx.GetSuperSecureCookie(defaultCookieSecret, key)
} | go | {
"resource": ""
} |
q170379 | SetSuperSecureCookie | validation | func (ctx *Context) SetSuperSecureCookie(secret, name, value string, others ...interface{}) {
key := pbkdf2.Key([]byte(secret), []byte(secret), 1000, 16, sha256.New)
text, err := com.AESGCMEncrypt(key, []byte(value))
if err != nil {
panic("error encrypting cookie: " + err.Error())
}
ctx.SetCookie(name, hex.Enco... | go | {
"resource": ""
} |
q170380 | GetSuperSecureCookie | validation | func (ctx *Context) GetSuperSecureCookie(secret, name string) (string, bool) {
val := ctx.GetCookie(name)
if val == "" {
return "", false
}
text, err := hex.DecodeString(val)
if err != nil {
return "", false
}
key := pbkdf2.Key([]byte(secret), []byte(secret), 1000, 16, sha256.New)
text, err = com.AESGCMDe... | go | {
"resource": ""
} |
q170381 | ServeContent | validation | func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
modtime := time.Now()
for _, p := range params {
switch v := p.(type) {
case time.Time:
modtime = v
}
}
ctx.setRawContentHeader()
http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
} | go | {
"resource": ""
} |
q170382 | ServeFileContent | validation | func (ctx *Context) ServeFileContent(file string, names ...string) {
var name string
if len(names) > 0 {
name = names[0]
} else {
name = path.Base(file)
}
f, err := os.Open(file)
if err != nil {
if Env == PROD {
http.Error(ctx.Resp, "Internal Server Error", 500)
} else {
http.Error(ctx.Resp, err.Er... | go | {
"resource": ""
} |
q170383 | ServeFile | validation | func (ctx *Context) ServeFile(file string, names ...string) {
var name string
if len(names) > 0 {
name = names[0]
} else {
name = path.Base(file)
}
ctx.Resp.Header().Set("Content-Description", "File Transfer")
ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
ctx.Resp.Header().Set("Content-Di... | go | {
"resource": ""
} |
q170384 | ChangeStaticPath | validation | func (ctx *Context) ChangeStaticPath(oldPath, newPath string) {
if !filepath.IsAbs(oldPath) {
oldPath = filepath.Join(Root, oldPath)
}
dir := statics.Get(oldPath)
if dir != nil {
statics.Delete(oldPath)
if !filepath.IsAbs(newPath) {
newPath = filepath.Join(Root, newPath)
}
*dir = http.Dir(newPath)
s... | go | {
"resource": ""
} |
q170385 | getNextWildcard | validation | func getNextWildcard(pattern string) (wildcard, _ string) {
pos := wildcardPattern.FindStringIndex(pattern)
if pos == nil {
return "", pattern
}
wildcard = pattern[pos[0]:pos[1]]
// Reach last character or no regexp is given.
if len(pattern) == pos[1] {
return wildcard, strings.Replace(pattern, wildcard, `(.... | go | {
"resource": ""
} |
q170386 | getRawPattern | validation | func getRawPattern(rawPattern string) string {
rawPattern = strings.Replace(rawPattern, ":int", "", -1)
rawPattern = strings.Replace(rawPattern, ":string", "", -1)
for {
startIdx := strings.Index(rawPattern, "(")
if startIdx == -1 {
break
}
closeIdx := strings.Index(rawPattern, ")")
if closeIdx > -1 {... | go | {
"resource": ""
} |
q170387 | URLPath | validation | func (l *Leaf) URLPath(pairs ...string) string {
if len(pairs)%2 != 0 {
panic("number of pairs does not match")
}
urlPath := l.rawPattern
parent := l.parent
for parent != nil {
urlPath = parent.rawPattern + "/" + urlPath
parent = parent.parent
}
for i := 0; i < len(pairs); i += 2 {
if len(pairs[i]) == 0... | go | {
"resource": ""
} |
q170388 | NewRouteMap | validation | func NewRouteMap() *routeMap {
rm := &routeMap{
routes: make(map[string]map[string]*Leaf),
}
for m := range _HTTP_METHODS {
rm.routes[m] = make(map[string]*Leaf)
}
return rm
} | go | {
"resource": ""
} |
q170389 | getLeaf | validation | func (rm *routeMap) getLeaf(method, pattern string) *Leaf {
rm.lock.RLock()
defer rm.lock.RUnlock()
return rm.routes[method][pattern]
} | go | {
"resource": ""
} |
q170390 | add | validation | func (rm *routeMap) add(method, pattern string, leaf *Leaf) {
rm.lock.Lock()
defer rm.lock.Unlock()
rm.routes[method][pattern] = leaf
} | go | {
"resource": ""
} |
q170391 | Name | validation | func (r *Route) Name(name string) {
if len(name) == 0 {
panic("route name cannot be empty")
} else if r.router.namedRoutes[name] != nil {
panic("route with given name already exists: " + name)
}
r.router.namedRoutes[name] = r.leaf
} | go | {
"resource": ""
} |
q170392 | handle | validation | func (r *Router) handle(method, pattern string, handle Handle) *Route {
method = strings.ToUpper(method)
var leaf *Leaf
// Prevent duplicate routes.
if leaf = r.getLeaf(method, pattern); leaf != nil {
return &Route{r, leaf}
}
// Validate HTTP methods.
if !_HTTP_METHODS[method] && method != "*" {
panic("unk... | go | {
"resource": ""
} |
q170393 | Handle | validation | func (r *Router) Handle(method string, pattern string, handlers []Handler) *Route {
if len(r.groups) > 0 {
groupPattern := ""
h := make([]Handler, 0)
for _, g := range r.groups {
groupPattern += g.pattern
h = append(h, g.handlers...)
}
pattern = groupPattern + pattern
h = append(h, handlers...)
ha... | go | {
"resource": ""
} |
q170394 | Combo | validation | func (r *Router) Combo(pattern string, h ...Handler) *ComboRouter {
return &ComboRouter{r, pattern, h, map[string]bool{}, nil}
} | go | {
"resource": ""
} |
q170395 | NotFound | validation | func (r *Router) NotFound(handlers ...Handler) {
handlers = validateAndWrapHandlers(handlers)
r.notFound = func(rw http.ResponseWriter, req *http.Request) {
c := r.m.createContext(rw, req)
c.handlers = make([]Handler, 0, len(r.m.handlers)+len(handlers))
c.handlers = append(c.handlers, r.m.handlers...)
c.handl... | go | {
"resource": ""
} |
q170396 | InternalServerError | validation | func (r *Router) InternalServerError(handlers ...Handler) {
handlers = validateAndWrapHandlers(handlers)
r.internalServerError = func(c *Context, err error) {
c.index = 0
c.handlers = handlers
c.Map(err)
c.run()
}
} | go | {
"resource": ""
} |
q170397 | URLFor | validation | func (r *Router) URLFor(name string, pairs ...string) string {
leaf, ok := r.namedRoutes[name]
if !ok {
panic("route with given name does not exists: " + name)
}
return leaf.URLPath(pairs...)
} | go | {
"resource": ""
} |
q170398 | Name | validation | func (cr *ComboRouter) Name(name string) {
if cr.lastRoute == nil {
panic("no corresponding route to be named")
}
cr.lastRoute.Name(name)
} | go | {
"resource": ""
} |
q170399 | NewResponseWriter | validation | func NewResponseWriter(method string, rw http.ResponseWriter) ResponseWriter {
return &responseWriter{method, rw, 0, 0, nil}
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.