mgutz / dat

Go Postgres Data Access Toolkit
Other
612 stars 62 forks source link

Panic in HTTP handler? #38

Open sbowman opened 8 years ago

sbowman commented 8 years ago

When I include code like the following in an HTTP HandlerFunc (or its ilk), and an error occurs in the database layer (e.g. "pq: duplicate key value violates unique constraint "feeds_pkey""), the DB session doesn't close and dat panics after around 60s (killing the application):

    tx, err := svc.DB.Begin()
    if err != nil {
        http.Error(out, err.Error(), http.StatusInternalServerError)
        return
    }
    defer tx.AutoRollback()

        // "feed" was unmarshaled from a JSON document...
    if err := feed.Insert(tx); err != nil {
        http.Error(out, err.Error(), http.StatusBadRequest)
        return
    }

    if err := tx.Commit(); err != nil {
        http.Error(out, err.Error(), http.StatusInternalServerError)
        return
    }

        out.WriteHeader(http.StatusNoContent)

But if I move the transaction inside the functions, everything is fine when the error occurs (this doesn't panic):

        // "DB" is a *dat.DB
    if err := feed.Insert(DB); err != nil {
        http.Error(out, err.Error(), http.StatusBadRequest)
        return
    }

        out.WriteHeader(http.StatusNoContent)

Why isn't the "defer tx.AutoRollback()" firing and releasing the session when it's in an HTTP handler?