server.go 1.35 KB
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
	DBs       map[string]*sql.DB
}

func NewODBCServer(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

	s.DBs = make(map[string]*sql.DB)
	s.DBs["default"] = s.DB

	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()
	}
}