utils.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Licensed under the Apache License, Version 2.0 (the "License");
  3. * you may not use this file except in compliance with the License.
  4. * You may obtain a copy of the License at
  5. *
  6. * http://www.apache.org/licenses/LICENSE-2.0
  7. *
  8. * Unless required by applicable law or agreed to in writing, software
  9. * distributed under the License is distributed on an "AS IS" BASIS,
  10. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. * See the License for the specific language governing permissions and
  12. * limitations under the License.
  13. */
  14. package utils
  15. import (
  16. "crypto/md5"
  17. "encoding/base64"
  18. "encoding/hex"
  19. "net/url"
  20. "reflect"
  21. "strconv"
  22. "time"
  23. "github.com/satori/go.uuid"
  24. )
  25. func GetUUIDV4() (uuidHex string) {
  26. uuidV4 := uuid.NewV4()
  27. uuidHex = hex.EncodeToString(uuidV4.Bytes())
  28. return
  29. }
  30. func GetMD5Base64(bytes []byte) (base64Value string) {
  31. md5Ctx := md5.New()
  32. md5Ctx.Write(bytes)
  33. md5Value := md5Ctx.Sum(nil)
  34. base64Value = base64.StdEncoding.EncodeToString(md5Value)
  35. return
  36. }
  37. func GetTimeInFormatISO8601() (timeStr string) {
  38. gmt := time.FixedZone("GMT", 0)
  39. return time.Now().In(gmt).Format("2006-01-02T15:04:05Z")
  40. }
  41. func GetTimeInFormatRFC2616() (timeStr string) {
  42. gmt := time.FixedZone("GMT", 0)
  43. return time.Now().In(gmt).Format("Mon, 02 Jan 2006 15:04:05 GMT")
  44. }
  45. func GetUrlFormedMap(source map[string]string) (urlEncoded string) {
  46. urlEncoder := url.Values{}
  47. for key, value := range source {
  48. urlEncoder.Add(key, value)
  49. }
  50. urlEncoded = urlEncoder.Encode()
  51. return
  52. }
  53. func InitStructWithDefaultTag(bean interface{}) {
  54. configType := reflect.TypeOf(bean)
  55. for i := 0; i < configType.Elem().NumField(); i++ {
  56. field := configType.Elem().Field(i)
  57. defaultValue := field.Tag.Get("default")
  58. if defaultValue == "" {
  59. continue
  60. }
  61. setter := reflect.ValueOf(bean).Elem().Field(i)
  62. switch field.Type.String() {
  63. case "int":
  64. intValue, _ := strconv.ParseInt(defaultValue, 10, 64)
  65. setter.SetInt(intValue)
  66. case "time.Duration":
  67. intValue, _ := strconv.ParseInt(defaultValue, 10, 64)
  68. setter.SetInt(intValue)
  69. case "string":
  70. setter.SetString(defaultValue)
  71. case "bool":
  72. boolValue, _ := strconv.ParseBool(defaultValue)
  73. setter.SetBool(boolValue)
  74. }
  75. }
  76. }