dao.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package dao
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "net/http"
  7. "go-common/app/admin/ep/melloi/conf"
  8. "go-common/library/cache/memcache"
  9. "go-common/library/database/orm"
  10. "go-common/library/log"
  11. xhttp "go-common/library/net/http/blademaster"
  12. "go-common/library/stat/prom"
  13. "github.com/jinzhu/gorm"
  14. "gopkg.in/gomail.v2"
  15. )
  16. // Prometheus
  17. var (
  18. errorsCount = prom.BusinessErrCount
  19. )
  20. // Dao dao
  21. type Dao struct {
  22. c *conf.Config
  23. DB *gorm.DB
  24. httpClient *xhttp.Client
  25. client *http.Client
  26. MC *memcache.Pool
  27. email *gomail.Dialer
  28. }
  29. // New init mysql db
  30. func New(c *conf.Config) (dao *Dao) {
  31. dao = &Dao{
  32. c: c,
  33. httpClient: xhttp.NewClient(c.HTTPClient),
  34. email: gomail.NewDialer(c.Mail.Host, c.Mail.Port, c.Mail.Username, c.Mail.Password),
  35. client: new(http.Client),
  36. DB: orm.NewMySQL(c.ORM),
  37. MC: memcache.NewPool(c.Memcache),
  38. }
  39. return
  40. }
  41. // Ping verify server is ok.
  42. func (d *Dao) Ping(c context.Context) (err error) {
  43. if err = d.DB.DB().Ping(); err != nil {
  44. log.Error("dao.cloudDB.Ping() error(%v)", err)
  45. return
  46. }
  47. return
  48. }
  49. func (d *Dao) newRequest(method, url string, v interface{}) (req *http.Request, err error) {
  50. body := &bytes.Buffer{}
  51. if method != http.MethodGet {
  52. if err = json.NewEncoder(body).Encode(v); err != nil {
  53. log.Error("json encode value(%s), error(%v) ", v, err)
  54. return
  55. }
  56. }
  57. if req, err = http.NewRequest(method, url, body); err != nil {
  58. log.Error("http new request url(%s), error(%v)", url, err)
  59. }
  60. return
  61. }
  62. // PromError prom error
  63. func PromError(name string) {
  64. errorsCount.Incr(name)
  65. }
  66. // Close close the resource.
  67. func (d *Dao) Close() {
  68. d.DB.Close()
  69. }