ETCD后台服务
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.5 KiB

3 years ago
  1. package common
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "errors"
  6. "etcd/etcdsdk/model"
  7. "fmt"
  8. "os"
  9. "path/filepath"
  10. "strconv"
  11. "github.com/gin-gonic/gin"
  12. )
  13. // GetRootDir 获取执行路径
  14. func GetRootDir() string {
  15. // 文件不存在获取执行路径
  16. file, err := filepath.Abs(filepath.Dir(os.Args[0]))
  17. if err != nil {
  18. file = fmt.Sprintf(".%s", string(os.PathSeparator))
  19. } else {
  20. file = fmt.Sprintf("%s%s", file, string(os.PathSeparator))
  21. }
  22. return file
  23. }
  24. // PathExists 判断文件或目录是否存在
  25. func PathExists(path string) (bool, error) {
  26. _, err := os.Stat(path)
  27. if err == nil {
  28. return true, nil
  29. }
  30. if os.IsNotExist(err) {
  31. return false, nil
  32. }
  33. return false, err
  34. }
  35. // GetEtcdClientByGinContext 获取一个etcd客户端 从gin请求上下文
  36. func GetEtcdClientByGinContext(c *gin.Context) (client model.EtcdSdk, err error) {
  37. clientI, exists := c.Get("CLIENT")
  38. if exists == false || clientI == nil {
  39. err = errors.New("Etcd service connection error")
  40. return
  41. }
  42. client = clientI.(model.EtcdSdk)
  43. return
  44. }
  45. // Md5Password 密码生成
  46. func Md5Password(password string) string {
  47. salt := "etcd-manage"
  48. return Md5(Md5(password) + Md5(salt))
  49. }
  50. // Md5 计算字符串md5值
  51. func Md5(s string) string {
  52. h := md5.New()
  53. h.Write([]byte(s))
  54. return hex.EncodeToString(h.Sum(nil))
  55. }
  56. // GetHttpToInt 获取请求参数,转为int
  57. func GetHttpToInt(c *gin.Context, name string) int {
  58. valStr := c.Query(name)
  59. val, _ := strconv.Atoi(valStr)
  60. return val
  61. }