all repos

onasty @ ff7bfce

a one-time notes service

onasty/internal/transport/http/apiv1/response.go (view raw)

Smirnov Oleksandr Smirnov Oleksandr
ss2316544@gmail.com
feat: impl the core of the app, notes (#5)..., 1 year ago
1
package apiv1
2
3
import (
4
	"errors"
5
	"log/slog"
6
	"net/http"
7
8
	"github.com/gin-gonic/gin"
9
	"github.com/olexsmir/onasty/internal/models"
10
)
11
12
type response struct {
13
	Message string `json:"message"`
14
}
15
16
func errorResponse(c *gin.Context, err error) {
17
	if errors.Is(err, models.ErrUserEmailIsAlreadyInUse) ||
18
		errors.Is(err, models.ErrUsernameIsAlreadyInUse) ||
19
		errors.Is(err, models.ErrNoteContentIsEmpty) ||
20
		errors.Is(err, models.ErrNoteSlugIsAlreadyInUse) {
21
		newError(c, http.StatusBadRequest, err.Error())
22
		return
23
	}
24
25
	if errors.Is(err, models.ErrNoteExpired) {
26
		newError(c, http.StatusGone, err.Error())
27
		return
28
	}
29
30
	if errors.Is(err, models.ErrNoteNotFound) {
31
		newErrorStatus(c, http.StatusNotFound, err.Error())
32
		return
33
	}
34
35
	if errors.Is(err, models.ErrUserNotFound) {
36
		newErrorStatus(c, http.StatusBadRequest, err.Error())
37
		return
38
	}
39
40
	if errors.Is(err, ErrUnauthorized) ||
41
		errors.Is(err, models.ErrUserWrongCredentials) {
42
		newErrorStatus(c, http.StatusUnauthorized, err.Error())
43
		return
44
	}
45
46
	newInternalError(c, err)
47
}
48
49
func newError(c *gin.Context, status int, msg string) {
50
	slog.Error(msg, "status", status)
51
	c.AbortWithStatusJSON(status, response{msg})
52
}
53
54
func newErrorStatus(c *gin.Context, status int, msg string) {
55
	slog.Error(msg, "status", status)
56
	c.AbortWithStatus(status)
57
}
58
59
func newInternalError(c *gin.Context, err error, msg ...string) {
60
	slog.With("status", "internal error").Error(err.Error())
61
62
	if len(msg) != 0 {
63
		c.AbortWithStatusJSON(http.StatusInternalServerError, response{
64
			Message: msg[0],
65
		})
66
		return
67
	}
68
69
	c.AbortWithStatusJSON(http.StatusInternalServerError, response{
70
		Message: "internal error",
71
	})
72
}