dbwriter.go 682 B

123456789101112131415161718192021222324252627282930313233343536
  1. package log
  2. import (
  3. "database/sql"
  4. "time"
  5. )
  6. type DBWriter struct {
  7. db *sql.DB
  8. stmt *sql.Stmt
  9. content chan []byte
  10. }
  11. func NewDBWriter(db *sql.DB) (*DBWriter, error) {
  12. _, err := db.Exec("CREATE TABLE IF NOT EXISTS log (id int, content text, created datetime)")
  13. if err != nil {
  14. return nil, err
  15. }
  16. stmt, err := db.Prepare("INSERT INTO log (content, created) values (?, ?)")
  17. if err != nil {
  18. return nil, err
  19. }
  20. return &DBWriter{db, stmt, make(chan []byte, 1000)}, nil
  21. }
  22. func (w *DBWriter) Write(p []byte) (n int, err error) {
  23. _, err = w.stmt.Exec(string(p), time.Now())
  24. if err == nil {
  25. n = len(p)
  26. }
  27. return
  28. }
  29. func (w *DBWriter) Close() {
  30. w.stmt.Close()
  31. }