load_config.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package config
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "github.com/dgrijalva/jwt-go"
  7. "github.com/mitchellh/mapstructure"
  8. "github.com/spf13/viper"
  9. )
  10. var workDir = os.Getenv("GO_WORK_DIR_TMR_GROUP")
  11. func Initialize(path string, cfgStruct interface{}) error {
  12. if workDir == "" {
  13. workDir = "."
  14. }
  15. dir := fmt.Sprintf("%s/config/%s", workDir, path)
  16. viper.SetConfigType("yaml")
  17. viper.SetConfigFile(dir)
  18. if err := viper.ReadInConfig(); err != nil {
  19. return err
  20. }
  21. if err := viper.Unmarshal(&cfgStruct, func(c *mapstructure.DecoderConfig) {
  22. c.TagName = "yaml"
  23. }); err != nil {
  24. return err
  25. }
  26. return nil
  27. }
  28. func openPrivateKey() JwtTokenKeyConfig {
  29. pathList := []string{fmt.Sprintf("%s/config/private.key", workDir), fmt.Sprintf("%s/config/public.key", workDir)}
  30. res := JwtTokenKeyConfig{PublicKey: nil, PrivateKey: nil}
  31. for i, path := range pathList {
  32. keyConfig, err := os.Open(path)
  33. if err != nil {
  34. panic(err)
  35. }
  36. b, err := ioutil.ReadAll(keyConfig)
  37. if err != nil {
  38. panic(err)
  39. }
  40. if i == 0 {
  41. parivateKey, err := jwt.ParseRSAPrivateKeyFromPEM(b)
  42. if err != nil {
  43. panic(err)
  44. }
  45. res.PrivateKey = parivateKey
  46. }
  47. if i == 1 {
  48. publicKey, err := jwt.ParseRSAPublicKeyFromPEM(b)
  49. if err != nil {
  50. panic(err)
  51. }
  52. res.PublicKey = publicKey
  53. }
  54. }
  55. return res
  56. }