func newSearchRequest(request *http.Request, params httprouter.Params) *SearchRequest { searchReq := &SearchRequest{} values, err := getRequestValues(request) if err != nil { return searchReq } formValues := TreePostFormValues(values) ordering := parseOrdering(formValues) if _, ok := formValues["columns"]; ok { columnsList := formValues["columns"].(map[string]interface{}) searchReq.Columns = make([]*ColumnDefinition, len(columnsList)) for key, column := range columnsList { searchReq.Columns[cast.ToInt(key)] = newColumnDefinition(column.(map[string]interface{}), DataTableOrder(ordering[key])) } searchReq.Draw = cast.ToInt(formValues["draw"]) searchReq.Length = cast.ToInt(formValues["length"]) searchReq.Start = cast.ToInt(formValues["start"]) searchReq.Search = newSearchDefinition(formValues["search"].(map[string]interface{})) } return searchReq }
// Get can retrieve any value given the key to use // Get returns an interface. For a specific value use one of the Get____ methods. func (c RawConfig) Get(key string) interface{} { path := strings.Split(key, keyDelim) val := c.find(strings.ToLower(key)) if val == nil { source := c.find(path[0]) if source == nil { return nil } if reflect.TypeOf(source).Kind() == reflect.Map { val = c.searchMap(cast.ToStringMap(source), path[1:]) } } switch val.(type) { case bool: return cast.ToBool(val) case string: return cast.ToString(val) case int64, int32, int16, int8, int: return cast.ToInt(val) case float64, float32: return cast.ToFloat64(val) case time.Time: return cast.ToTime(val) case time.Duration: return cast.ToDuration(val) case []string: return val } return val }
func Offset(c *gin.Context) int { curPage := cast.ToInt(c.Request.FormValue("p")) - 1 if curPage < 1 { return 0 } return pLimit * curPage }
func toSortedLanguages(l map[string]interface{}) (helpers.Languages, error) { langs := make(helpers.Languages, len(l)) i := 0 for lang, langConf := range l { langsMap, err := cast.ToStringMapE(langConf) if err != nil { return nil, fmt.Errorf("Language config is not a map: %T", langConf) } language := helpers.NewLanguage(lang) for loki, v := range langsMap { switch loki { case "title": language.Title = cast.ToString(v) case "languagename": language.LanguageName = cast.ToString(v) case "weight": language.Weight = cast.ToInt(v) } // Put all into the Params map language.SetParam(loki, v) } langs[i] = language i++ } sort.Sort(langs) return langs, nil }
func (v *Viper) Get(key string) interface{} { key = strings.ToLower(key) val := v.find(key) if val == nil { return nil } switch val.(type) { case bool: return cast.ToBool(val) case string: return cast.ToString(val) case int64, int32, int16, int8, int: return cast.ToInt(val) case float64, float32: return cast.ToFloat64(val) case time.Time: return cast.ToTime(val) case time.Duration: return cast.ToDuration(val) case []string: return val } return val }
func (v *Viper) Get(key string) interface{} { lcaseKey := strings.ToLower(key) val := v.find(lcaseKey) if val == nil { return nil } valType := val if v.typeByDefValue { // TODO(bep) this branch isn't covered by a single test. path := strings.Split(lcaseKey, v.keyDelim) defVal := v.searchMap(v.defaults, path) if defVal != nil { valType = defVal } } switch valType.(type) { case bool: return cast.ToBool(val) case string: return cast.ToString(val) case int64, int32, int16, int8, int: return cast.ToInt(val) case float64, float32: return cast.ToFloat64(val) case time.Time: return cast.ToTime(val) case time.Duration: return cast.ToDuration(val) case []string: return cast.ToStringSlice(val) } return val }
func (p *Page) getParam(key string, stringToLower bool) interface{} { v := p.Params[strings.ToLower(key)] if v == nil { return nil } switch v.(type) { case bool: return cast.ToBool(v) case string: if stringToLower { return strings.ToLower(cast.ToString(v)) } return cast.ToString(v) case int64, int32, int16, int8, int: return cast.ToInt(v) case float64, float32: return cast.ToFloat64(v) case time.Time: return cast.ToTime(v) case []string: if stringToLower { return helpers.SliceToLower(v.([]string)) } return v.([]string) case map[string]interface{}: // JSON and TOML return v case map[interface{}]interface{}: // YAML return v } jww.ERROR.Printf("GetParam(\"%s\"): Unknown type %s\n", key, reflect.TypeOf(v)) return nil }
// parseSizeInBytes converts strings like 1GB or 12 mb into an unsigned integer number of bytes func parseSizeInBytes(sizeStr string) uint { sizeStr = strings.TrimSpace(sizeStr) lastChar := len(sizeStr) - 1 multiplier := uint(1) if lastChar > 0 { if sizeStr[lastChar] == 'b' || sizeStr[lastChar] == 'B' { if lastChar > 1 { switch unicode.ToLower(rune(sizeStr[lastChar-1])) { case 'k': multiplier = 1 << 10 sizeStr = strings.TrimSpace(sizeStr[:lastChar-1]) case 'm': multiplier = 1 << 20 sizeStr = strings.TrimSpace(sizeStr[:lastChar-1]) case 'g': multiplier = 1 << 30 sizeStr = strings.TrimSpace(sizeStr[:lastChar-1]) default: multiplier = 1 sizeStr = strings.TrimSpace(sizeStr[:lastChar]) } } } } size := cast.ToInt(sizeStr) if size < 0 { size = 0 } return safeMul(uint(size), multiplier) }
// Get returns an interface.. // Must be typecast or used by something that will typecast func (manager *Config) Get(key string) interface{} { jww.TRACE.Println("Looking for", key) v := manager.Find(key) if v == nil { return nil } jww.TRACE.Println("Found value", v) switch v.(type) { case bool: return cast.ToBool(v) case string: return cast.ToString(v) case int64, int32, int16, int8, int: return cast.ToInt(v) case float64, float32: return cast.ToFloat64(v) case time.Time: return cast.ToTime(v) case []string: return v } return v }
func (c *Config) loadMaxAge(seq sequence) { c.maxAgePatterns = newGlobList(0) el, ok := seq.elForKey("max_age") if !ok { return } if defaultMaxAge := cast.ToInt(el.value); defaultMaxAge > 0 { c.maxAgePatterns.defaultValue = defaultMaxAge } else if len(el.sequence) > 0 { for _, subEl := range el.sequence { if age := cast.ToInt(subEl.value); age > 0 { c.maxAgePatterns.add(subEl.key, age) } } } }
func (v *Viper) Get(key string) interface{} { path := strings.Split(key, v.keyDelim) var val interface{} lcaseKey := strings.ToLower(key) source := v.find(path[0]) if source != nil { if reflect.TypeOf(source).Kind() == reflect.Map { val = v.searchMap(cast.ToStringMap(source), path[1:]) } } if val == nil { val = v.find(lcaseKey) } if val == nil { return nil } var valType interface{} if !v.typeByDefValue { valType = val } else { defVal, defExists := v.defaults[lcaseKey] if defExists { valType = defVal } else { valType = val } } switch valType.(type) { case bool: return cast.ToBool(val) case string: return cast.ToString(val) case int64, int32, int16, int8, int: return cast.ToInt(val) case float64, float32: return cast.ToFloat64(val) case time.Time: return cast.ToTime(val) case time.Duration: return cast.ToDuration(val) case []string: return cast.ToStringSlice(val) } return val }
func (me *MenuEntry) MarshallMap(ime map[string]interface{}) { for k, v := range ime { loki := strings.ToLower(k) switch loki { case "url": me.Url = cast.ToString(v) case "weight": me.Weight = cast.ToInt(v) case "name": me.Name = cast.ToString(v) case "parent": me.Parent = cast.ToString(v) } } }
func (v *Viper) BindPFlag(key string, flag *pflag.Flag) (err error) { if flag == nil { return fmt.Errorf("flag for %q is nil", key) } v.pflags[strings.ToLower(key)] = flag switch flag.Value.Type() { case "int", "int8", "int16", "int32", "int64": SetDefault(key, cast.ToInt(flag.Value.String())) case "bool": SetDefault(key, cast.ToBool(flag.Value.String())) default: SetDefault(key, flag.Value.String()) } return nil }
// Binds a configuration key to a command line flag: // pflag.Int("port", 8080, "The best alternative port") // confer.BindPFlag("port", pflag.Lookup("port")) func (manager *Config) BindPFlag(key string, flag *pflag.Flag) (err error) { if flag == nil { return fmt.Errorf("flag for %q is nil", key) } manager.pflags.Set(key, flag) switch flag.Value.Type() { case "int", "int8", "int16", "int32", "int64": manager.SetDefault(key, cast.ToInt(flag.Value.String())) case "bool": manager.SetDefault(key, cast.ToBool(flag.Value.String())) default: manager.SetDefault(key, flag.Value.String()) } return nil }
func doTestCaseInsensitive(t *testing.T, typ, config string) { initConfig(typ, config) Set("RfD", true) assert.Equal(t, true, Get("rfd")) assert.Equal(t, true, Get("rFD")) assert.Equal(t, 1, cast.ToInt(Get("abcd"))) assert.Equal(t, 1, cast.ToInt(Get("Abcd"))) assert.Equal(t, 2, cast.ToInt(Get("ef.gh"))) assert.Equal(t, 3, cast.ToInt(Get("ef.ijk"))) assert.Equal(t, 4, cast.ToInt(Get("ef.lm.no"))) assert.Equal(t, 5, cast.ToInt(Get("ef.lm.p.q"))) }
func (v *Viper) BindPFlags(flags *pflag.FlagSet) (err error) { flags.VisitAll(func(flag *pflag.Flag) { if err != nil { // an error has been encountered in one of the previous flags return } err = v.BindPFlag(flag.Name, flag) switch flag.Value.Type() { case "int", "int8", "int16", "int32", "int64": v.SetDefault(flag.Name, cast.ToInt(flag.Value.String())) case "bool": v.SetDefault(flag.Name, cast.ToBool(flag.Value.String())) default: v.SetDefault(flag.Name, flag.Value.String()) } }) return }
func (me *MenuEntry) MarshallMap(ime map[string]interface{}) { for k, v := range ime { loki := strings.ToLower(k) switch loki { case "url": me.URL = cast.ToString(v) case "weight": me.Weight = cast.ToInt(v) case "name": me.Name = cast.ToString(v) case "pre": me.Pre = template.HTML(cast.ToString(v)) case "post": me.Post = template.HTML(cast.ToString(v)) case "identifier": me.Identifier = cast.ToString(v) case "parent": me.Parent = cast.ToString(v) } } }
//get Config value by key func (c *Config) Get(key string) interface{} { val := c.get(key) switch val.(type) { case bool: return cast.ToBool(val) case string: return cast.ToString(val) case int64, int32, int16, int8, int: return cast.ToInt(val) case float64, float32: return cast.ToFloat64(val) case time.Time: return cast.ToTime(val) case time.Duration: return cast.ToDuration(val) case []string: return val } return val }
// ReadConfigFile read user defined hosts in .ayi.yml func ReadConfigFile() { log.Debug("Read git section in config file") hostsMap = make(map[string]Host) hostsSlice := cast.ToSlice(viper.Get("git.hosts")) for _, h := range hostsSlice { m := cast.ToStringMap(h) _, exists := m["name"] if !exists { log.Warn("Skipp host without name") continue } // TODO: more attributes, the following is not working // - http port // - support ssh name := cast.ToString(m["name"]) https := cast.ToBool(util.GetWithDefault(m, "https", true)) port := cast.ToInt(util.GetWithDefault(m, "port", DefaultSSHPort)) h := NewHost(name) h.SupportHTTPS = https h.SSHPort = port hosts = append(hosts, *h) // TODO: may add order to host hostsMap[name] = *h } // only merge default hosts that are not configed in config files for _, defaultHost := range DefaultHosts { _, exists := hostsMap[defaultHost.URL] if !exists { hosts = append(hosts, defaultHost) hostsMap[defaultHost.URL] = defaultHost } } }
func (s *SiteInfo) GetParam(key string) interface{} { v := s.Params[strings.ToLower(key)] if v == nil { return nil } switch v.(type) { case bool: return cast.ToBool(v) case string: return cast.ToString(v) case int64, int32, int16, int8, int: return cast.ToInt(v) case float64, float32: return cast.ToFloat64(v) case time.Time: return cast.ToTime(v) case []string: return v } return nil }
func (page *Page) GetParam(key string) interface{} { v := page.Params[strings.ToLower(key)] if v == nil { return nil } switch v.(type) { case bool: return cast.ToBool(v) case string: return strings.ToLower(cast.ToString(v)) case int64, int32, int16, int8, int: return cast.ToInt(v) case float64, float32: return cast.ToFloat64(v) case time.Time: return cast.ToTime(v) case []string: return sliceToLower(v.([]string)) } return nil }
// Get returns an interface.. // Must be typecast or used by something that will typecast func Get(key string) interface{} { key = strings.ToLower(key) v := find(key) if v == nil { return nil } switch v.(type) { case bool: return cast.ToBool(v) case string: return cast.ToString(v) case int64, int32, int16, int8, int: return cast.ToInt(v) case float64, float32: return cast.ToFloat64(v) case time.Time: return cast.ToTime(v) case []string: return v } return v }
func GetInt(key string) int { return cast.ToInt(Get(key)) }
func init() { funcMap = template.FuncMap{ "absURL": func(a string) template.HTML { return template.HTML(helpers.AbsURL(a)) }, "add": func(a, b interface{}) (interface{}, error) { return helpers.DoArithmetic(a, b, '+') }, "after": after, "apply": apply, "base64Decode": base64Decode, "base64Encode": base64Encode, "chomp": chomp, "countrunes": countRunes, "countwords": countWords, "default": dfault, "dateFormat": dateFormat, "delimit": delimit, "dict": dictionary, "div": func(a, b interface{}) (interface{}, error) { return helpers.DoArithmetic(a, b, '/') }, "echoParam": returnWhenSet, "emojify": emojify, "eq": eq, "findRE": findRE, "first": first, "ge": ge, "getCSV": getCSV, "getJSON": getJSON, "getenv": func(varName string) string { return os.Getenv(varName) }, "gt": gt, "hasPrefix": func(a, b string) bool { return strings.HasPrefix(a, b) }, "highlight": highlight, "humanize": humanize, "in": in, "index": index, "int": func(v interface{}) int { return cast.ToInt(v) }, "intersect": intersect, "isSet": isSet, "isset": isSet, "jsonify": jsonify, "last": last, "le": le, "lower": func(a string) string { return strings.ToLower(a) }, "lt": lt, "markdownify": markdownify, "md5": md5, "mod": mod, "modBool": modBool, "mul": func(a, b interface{}) (interface{}, error) { return helpers.DoArithmetic(a, b, '*') }, "ne": ne, "partial": partial, "plainify": plainify, "pluralize": pluralize, "querify": querify, "readDir": readDirFromWorkingDir, "readFile": readFileFromWorkingDir, "ref": ref, "relURL": func(a string) template.HTML { return template.HTML(helpers.RelURL(a)) }, "relref": relRef, "replace": replace, "replaceRE": replaceRE, "safeCSS": safeCSS, "safeHTML": safeHTML, "safeHTMLAttr": safeHTMLAttr, "safeJS": safeJS, "safeURL": safeURL, "sanitizeURL": helpers.SanitizeURL, "sanitizeurl": helpers.SanitizeURL, "seq": helpers.Seq, "sha1": sha1, "shuffle": shuffle, "singularize": singularize, "slice": slice, "slicestr": slicestr, "sort": sortSeq, "split": split, "string": func(v interface{}) string { return cast.ToString(v) }, "sub": func(a, b interface{}) (interface{}, error) { return helpers.DoArithmetic(a, b, '-') }, "substr": substr, "title": func(a string) string { return strings.Title(a) }, "trim": trim, "upper": func(a string) string { return strings.ToUpper(a) }, "urlize": helpers.URLize, "where": where, } }
func (c *Config) GetInt(key string) int { return cast.ToInt(c.get(key)) }
func (p *Page) update(f interface{}) error { if f == nil { return fmt.Errorf("no metadata found") } m := f.(map[string]interface{}) var err error var draft, published, isCJKLanguage *bool for k, v := range m { loki := strings.ToLower(k) switch loki { case "title": p.Title = cast.ToString(v) case "linktitle": p.linkTitle = cast.ToString(v) case "description": p.Description = cast.ToString(v) case "slug": p.Slug = cast.ToString(v) case "url": if url := cast.ToString(v); strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") { return fmt.Errorf("Only relative URLs are supported, %v provided", url) } p.URL = cast.ToString(v) case "type": p.contentType = cast.ToString(v) case "extension", "ext": p.extension = cast.ToString(v) case "keywords": p.Keywords = cast.ToStringSlice(v) case "date": p.Date, err = cast.ToTimeE(v) if err != nil { jww.ERROR.Printf("Failed to parse date '%v' in page %s", v, p.File.Path()) } case "lastmod": p.Lastmod, err = cast.ToTimeE(v) if err != nil { jww.ERROR.Printf("Failed to parse lastmod '%v' in page %s", v, p.File.Path()) } case "publishdate", "pubdate": p.PublishDate, err = cast.ToTimeE(v) if err != nil { jww.ERROR.Printf("Failed to parse publishdate '%v' in page %s", v, p.File.Path()) } case "draft": draft = new(bool) *draft = cast.ToBool(v) case "published": // Intentionally undocumented published = new(bool) *published = cast.ToBool(v) case "layout": p.Layout = cast.ToString(v) case "markup": p.Markup = cast.ToString(v) case "weight": p.Weight = cast.ToInt(v) case "aliases": p.Aliases = cast.ToStringSlice(v) for _, alias := range p.Aliases { if strings.HasPrefix(alias, "http://") || strings.HasPrefix(alias, "https://") { return fmt.Errorf("Only relative aliases are supported, %v provided", alias) } } case "status": p.Status = cast.ToString(v) case "sitemap": p.Sitemap = parseSitemap(cast.ToStringMap(v)) case "iscjklanguage": isCJKLanguage = new(bool) *isCJKLanguage = cast.ToBool(v) default: // If not one of the explicit values, store in Params switch vv := v.(type) { case bool: p.Params[loki] = vv case string: p.Params[loki] = vv case int64, int32, int16, int8, int: p.Params[loki] = vv case float64, float32: p.Params[loki] = vv case time.Time: p.Params[loki] = vv default: // handle array of strings as well switch vvv := vv.(type) { case []interface{}: if len(vvv) > 0 { switch vvv[0].(type) { case map[interface{}]interface{}: // Proper parsing structured array from YAML based FrontMatter p.Params[loki] = vvv case map[string]interface{}: // Proper parsing structured array from JSON based FrontMatter p.Params[loki] = vvv default: a := make([]string, len(vvv)) for i, u := range vvv { a[i] = cast.ToString(u) } p.Params[loki] = a } } else { p.Params[loki] = []string{} } default: p.Params[loki] = vv } } } } if draft != nil && published != nil { p.Draft = *draft jww.ERROR.Printf("page %s has both draft and published settings in its frontmatter. Using draft.", p.File.Path()) return ErrHasDraftAndPublished } else if draft != nil { p.Draft = *draft } else if published != nil { p.Draft = !*published } if p.Lastmod.IsZero() { p.Lastmod = p.Date } if isCJKLanguage != nil { p.isCJKLanguage = *isCJKLanguage } else if viper.GetBool("HasCJKLanguage") { if cjk.Match(p.rawContent) { p.isCJKLanguage = true } else { p.isCJKLanguage = false } } return nil }
func (manager *Config) GetInt(key string) int { return cast.ToInt(manager.Get(key)) }
func (v *Viper) GetInt(key string) int { return cast.ToInt(v.Get(key)) }
func (page *Page) update(f interface{}) error { if f == nil { return fmt.Errorf("no metadata found") } m := f.(map[string]interface{}) for k, v := range m { loki := strings.ToLower(k) switch loki { case "title": page.Title = cast.ToString(v) case "linktitle": page.linkTitle = cast.ToString(v) case "description": page.Description = cast.ToString(v) case "slug": page.Slug = helpers.Urlize(cast.ToString(v)) case "url": if url := cast.ToString(v); strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") { return fmt.Errorf("Only relative urls are supported, %v provided", url) } page.Url = helpers.Urlize(cast.ToString(v)) case "type": page.contentType = cast.ToString(v) case "keywords": page.Keywords = cast.ToStringSlice(v) case "date", "pubdate": page.Date = cast.ToTime(v) case "draft": page.Draft = cast.ToBool(v) case "layout": page.layout = cast.ToString(v) case "markup": page.Markup = cast.ToString(v) case "weight": page.Weight = cast.ToInt(v) case "aliases": page.Aliases = cast.ToStringSlice(v) for _, alias := range page.Aliases { if strings.HasPrefix(alias, "http://") || strings.HasPrefix(alias, "https://") { return fmt.Errorf("Only relative aliases are supported, %v provided", alias) } } case "status": page.Status = cast.ToString(v) case "sitemap": page.Sitemap = parseSitemap(cast.ToStringMap(v)) default: // If not one of the explicit values, store in Params switch vv := v.(type) { case bool: page.Params[loki] = vv case string: page.Params[loki] = vv case int64, int32, int16, int8, int: page.Params[loki] = vv case float64, float32: page.Params[loki] = vv case time.Time: page.Params[loki] = vv default: // handle array of strings as well switch vvv := vv.(type) { case []interface{}: var a = make([]string, len(vvv)) for i, u := range vvv { a[i] = cast.ToString(u) } page.Params[loki] = a default: page.Params[loki] = vv } } } } return nil }
// Returns the value associated with the key as an integer func (c RawConfig) GetInt(key string) int { return cast.ToInt(c.Get(key)) }