Guest User

Untitled

a guest
Jul 31st, 2018
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. package common
  2.  
  3. import (
  4. "encoding/json"
  5. "log"
  6. "os"
  7. "time"
  8.  
  9. "gopkg.in/mgo.v2"
  10. )
  11.  
  12. type (
  13. configuration struct {
  14. ServerPort, MongoDBHost, MongoDBUser, MongoDBPwd, Database string
  15. }
  16. )
  17.  
  18. // AppConfig holds the configuration values from config.json file
  19. var AppConfig configuration
  20. var jsonFile string = "config.json"
  21.  
  22. // Initialize AppConfig
  23. func initConfig() {
  24. file, err := os.Open(jsonFile)
  25. defer file.Close()
  26. if err != nil {
  27. log.Fatalf("[loadConfig]: %s\n", err)
  28. }
  29. decoder := json.NewDecoder(file)
  30. AppConfig = configuration{}
  31. err = decoder.Decode(&AppConfig)
  32. if err != nil {
  33. log.Fatalf("[loadConfig]: %s\n", err)
  34. }
  35. }
  36.  
  37. // Session holds the mongodb session for database access
  38. var session *mgo.Session
  39.  
  40. // Get database session
  41. func GetSession() *mgo.Session {
  42. if session == nil {
  43. var err error
  44. session, err = mgo.DialWithInfo(&mgo.DialInfo{
  45. Addrs: []string{AppConfig.MongoDBHost},
  46. Username: AppConfig.MongoDBUser,
  47. Password: AppConfig.MongoDBPwd,
  48. Timeout: 60 * time.Second,
  49. })
  50. if err != nil {
  51. log.Fatalf("[GetSession]: %s\n", err)
  52. }
  53. }
  54. return session
  55. }
  56.  
  57. // Create database session
  58. func createDbSession() {
  59. var err error
  60. session, err = mgo.DialWithInfo(&mgo.DialInfo{
  61. Addrs: []string{AppConfig.MongoDBHost},
  62. Username: AppConfig.MongoDBUser,
  63. Password: AppConfig.MongoDBPwd,
  64. Timeout: 60 * time.Second,
  65. })
  66. if err != nil {
  67. log.Fatalf("[createDbSession]: %s\n", err)
  68. }
  69. }
  70.  
  71. func StartUp(configFile string) {
  72. if configFile != "" {
  73. jsonFile = configFile
  74. }
  75.  
  76. // Initialize AppConfig variable
  77. initConfig()
  78. // Start a MongoDB session
  79. createDbSession()
  80. }
Add Comment
Please, Sign In to add comment