Blame view

server.go 1.26 KB
2726b5683   Marko Tikvić   server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
  package webutility
  
  import (
  	"database/sql"
  	"fmt"
  	"net/http"
  
  	"git.to-net.rs/marko.tikvic/gologger"
  	"github.com/gorilla/mux"
  )
  
  type Server struct {
  	DB        *sql.DB
  	Router    *mux.Router
  	Logger    *gologger.Logger
  	Port      string
  	UTCOffset int64
  }
  
  func NewServer(dsn, port, logDir string, utcOffset int64) (s *Server, err error) {
  	s = new(Server)
  
  	s.Port = port
  
  	if s.DB, err = sql.Open("odbc", fmt.Sprintf("DSN=%s;", dsn)); err != nil {
  		return nil, err
  	}
  
  	s.Router = mux.NewRouter()
  
  	if s.Logger, err = gologger.New("err", logDir, gologger.MaxLogSize1MB); err != nil {
  		return nil, fmt.Errorf("can't create logger: %s", err.Error())
  	}
  
  	s.UTCOffset = utcOffset
  
  	return s, nil
  }
  
  func (s *Server) Run() {
  	s.Logger.Print("Server listening on %s", s.Port)
  	s.Logger.PrintAndTrace(http.ListenAndServe(s.Port, s.Router).Error())
  }
  
  func (s *Server) Cleanup() {
  	if s.DB != nil {
  		s.DB.Close()
  	}
  
  	if s.Logger != nil {
  		s.Logger.Close()
  	}
  }
  
  func (s *Server) StartTransaction() (*sql.Tx, error) {
  	return s.DB.Begin()
  }
  
  func CommitChanges(tx *sql.Tx, err *error, opt ...error) {
  	if *err != nil {
  		tx.Rollback()
  		return
  	}
  
  	for _, e := range opt {
  		if e != nil {
  			tx.Rollback()
  			return
  		}
  	}
  
  	if *err = tx.Commit(); *err != nil {
  		tx.Rollback()
  	}
  }