github.com/zhongdalu/gf@v1.0.0/g/util/gutil/gutil.go (about) 1 // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 7 // Package gutil provides utility functions. 8 package gutil 9 10 import ( 11 "bytes" 12 "encoding/json" 13 "fmt" 14 "os" 15 16 "github.com/zhongdalu/gf/g/internal/empty" 17 "github.com/zhongdalu/gf/g/util/gconv" 18 ) 19 20 // Dump prints variables <i...> to stdout with more manually readable. 21 func Dump(i ...interface{}) { 22 s := Export(i...) 23 if s != "" { 24 fmt.Println(s) 25 } 26 } 27 28 // Export returns variables <i...> as a string with more manually readable. 29 func Export(i ...interface{}) string { 30 buffer := bytes.NewBuffer(nil) 31 for _, v := range i { 32 if b, ok := v.([]byte); ok { 33 buffer.Write(b) 34 } else { 35 if m := gconv.Map(v); m != nil { 36 v = m 37 } 38 encoder := json.NewEncoder(buffer) 39 encoder.SetEscapeHTML(false) 40 encoder.SetIndent("", "\t") 41 if err := encoder.Encode(v); err != nil { 42 fmt.Fprintln(os.Stderr, err.Error()) 43 } 44 } 45 } 46 return buffer.String() 47 } 48 49 // Throw throws out an exception, which can be caught be TryCatch or recover. 50 func Throw(exception interface{}) { 51 panic(exception) 52 } 53 54 // TryCatch implements try...catch... logistics. 55 func TryCatch(try func(), catch ...func(exception interface{})) { 56 if len(catch) > 0 { 57 // If <catch> is given, it's used to handle the exception. 58 defer func() { 59 if e := recover(); e != nil { 60 catch[0](e) 61 } 62 }() 63 } else { 64 // If no <catch> function passed, it filters the exception. 65 defer func() { 66 recover() 67 }() 68 } 69 try() 70 } 71 72 // IsEmpty checks given <value> empty or not. 73 // It returns false if <value> is: integer(0), bool(false), slice/map(len=0), nil; 74 // or else returns true. 75 func IsEmpty(value interface{}) bool { 76 return empty.IsEmpty(value) 77 }