Commit 2726b56833ab51faf5cfcdc90f82d3fb9c9119dc

Authored by Marko Tikvić
1 parent befe8fcc1d
Exists in master

server

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