Util
package revel
type ExecutableTemplate interface {
Execute(io.Writer, interface{}) error
}
func ExecuteTemplate(tmpl ExecutableTemplate, data interface{}) string {
var b bytes.Buffer
tmpl.Execute(&b, data)
return b.String()
}
func MustReadLines(filename string) []string {
r, err := ReadLines(filename)
if err != nil {
panic(err)
}
return r
}
func ReadLines(filename string) ([]string, error) {
bytes, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return strings.Split(string(bytes), "\n"), nil
}
func ContainsString(list []string, target string) bool {
for _, el := range list {
if el == target {
return true
}
}
return false
}
func FindMethod(recvType reflect.Type, funcVal reflect.Value) *reflect.Method {
for i := 0; i < recvType.NumMethod(); i++ {
method := recvType.Method(i)
if method.Func.Pointer() == funcVal.Pointer() {
return &method
}
}
return nil
}
func ParseKeyValueCookie(val string, cb func(key, val string)) {
val, _ = url.QueryUnescape(val)
if matches := cookieKeyValueParser.FindAllStringSubmatch(val, -1); matches != nil {
for _, match := range matches {
cb(match[1], match[2])
}
}
}
const DefaultFileContentType = "application/octet-stream"
func LoadMimeConfig() {
var err error
mimeConfig, err = LoadConfig("mime-types.conf")
if err != nil {
ERROR.Fatalln("Failed to load mime type config:", err)
}
}
func ContentTypeByFilename(filename string) string {
dot := strings.LastIndex(filename, ".")
if dot == -1 || dot+1 >= len(filename) {
return DefaultFileContentType
}
extension := filename[dot+1:]
contentType := mimeConfig.StringDefault(extension, "")
if contentType == "" {
return DefaultFileContentType
}
if strings.HasPrefix(contentType, "text/") {
return contentType + "; charset=utf-8"
}
return contentType
}
func DirExists(filename string) bool {
fileInfo, err := os.Stat(filename)
return err == nil && fileInfo.IsDir()
}
func FirstNonEmpty(strs ...string) string {
for _, str := range strs {
if len(str) > 0 {
return str
}
}
return ""
}
func Equal(a, b interface{}) bool {
if reflect.TypeOf(a) == reflect.TypeOf(b) {
return reflect.DeepEqual(a, b)
}
switch a.(type) {
case int, int8, int16, int32, int64:
switch b.(type) {
case int, int8, int16, int32, int64:
return reflect.ValueOf(a).Int() == reflect.ValueOf(b).Int()
}
case uint, uint8, uint16, uint32, uint64:
switch b.(type) {
case uint, uint8, uint16, uint32, uint64:
return reflect.ValueOf(a).Uint() == reflect.ValueOf(b).Uint()
}
case float32, float64:
switch b.(type) {
case float32, float64:
return reflect.ValueOf(a).Float() == reflect.ValueOf(b).Float()
}
case string:
switch b.(type) {
case []byte:
return a.(string) == string(b.([]byte))
}
case []byte:
switch b.(type) {
case string:
return b.(string) == string(a.([]byte))
}
}
return false
}