From bf0f3c5eac1d89ba486bd190b059ef21879730e6 Mon Sep 17 00:00:00 2001 From: Gibheer Date: Wed, 21 Apr 2021 21:50:46 +0200 Subject: [PATCH] add transaction to context This adds the transaction handling to the connection and context handling. It will raise an error and inform the client if anything is going wrong with the transaction. --- server.go | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/server.go b/server.go index 037cc0c..1b6a416 100644 --- a/server.go +++ b/server.go @@ -10,6 +10,7 @@ import ( ) const ( + LevelFatal = `FATAL` LevelError = `ERROR` LevelInfo = `INFO` ) @@ -35,7 +36,7 @@ type ( w http.ResponseWriter username string - tx *sql.DB + tx *sql.Tx } // Request contains the method name and parameters requested by the client. @@ -46,6 +47,7 @@ type ( // Response can have messages and/or a result to return the to client. Response struct { + ID string `json:"id"` Messages map[string][]string `json:"messages,omitempty"` Result map[string]interface{} `json:"result,omitempty"` } @@ -95,10 +97,22 @@ func (s *Server) Handle(w http.ResponseWriter, r *http.Request) { req := Request{} res := &Response{ + ID: c.id, Messages: map[string][]string{}, Result: map[string]interface{}{}, } + tx, err := s.db.Begin() + if err != nil { + c.Logf(LevelError, "could not create transaction: %s", err) + w.WriteHeader(http.StatusInternalServerError) + res.AddMessage(LevelFatal, "database problems occured") + c.render(res) + return + } + defer tx.Rollback() // make a rollback, just in case something goes wrong + c.tx = tx + dec := json.NewDecoder(r.Body) defer r.Body.Close() if err := dec.Decode(&req); err != nil { @@ -119,6 +133,10 @@ func (s *Server) Handle(w http.ResponseWriter, r *http.Request) { if err := handler(c, req, res); err != nil { c.Logf(LevelError, "method '%s' returned an error: %s", req.Method, err) } + if err := tx.Commit(); err != nil { + c.Logf(LevelFatal, "could not commit changes: %s", err) + res.AddMessage(LevelError, "changes were not committed") + } c.render(res) }