-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
78 lines (68 loc) · 1.53 KB
/
utils.go
File metadata and controls
78 lines (68 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package fsb
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"net/http"
"reflect"
)
func txBegin(ctx context.Context, pool *pgxpool.Pool) (pgx.Tx, error) {
tx, err := pool.Begin(ctx)
if err != nil {
return nil, err
}
return tx, nil
}
func txCommit(tx pgx.Tx, ctx context.Context) error {
err := tx.Commit(ctx)
if err != nil {
return err
}
return nil
}
func txDefer(tx pgx.Tx, ctx context.Context) {
err := tx.Rollback(ctx)
if err != nil {
if !errors.Is(err, pgx.ErrTxClosed) {
_ = fmt.Errorf("error rolling back transaction: %v", err)
}
}
}
type ErrResponse struct {
Error string `json:"error"`
}
func writeJSON(w http.ResponseWriter, v interface{}) {
if isNil(v) {
writeErr(w, fmt.Errorf("not found"), http.StatusNotFound)
return
}
j, err := json.MarshalIndent(v, "", "\t")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
_, err = w.Write(j)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func writeErr(w http.ResponseWriter, err error, code int) {
switch err.(type) {
default:
w.WriteHeader(code)
writeJSON(w, ErrResponse{Error: err.Error()})
}
}
func isNil(i interface{}) bool {
if i == nil {
return true
}
value := reflect.ValueOf(i)
kind := value.Kind()
return (kind == reflect.Ptr || kind == reflect.Slice || kind == reflect.Map || kind == reflect.Func || kind == reflect.Chan || kind == reflect.Interface) && value.IsNil()
}