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.
This commit is contained in:
parent
2ee6db04e5
commit
bf0f3c5eac
20
server.go
20
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)
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue