generated from mikestefanello/pagoda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
entity.go
47 lines (38 loc) · 982 Bytes
/
entity.go
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
package middleware
import (
"database/sql"
"fmt"
"net/http"
"strconv"
"github.com/francoganga/pagoda_bun/models"
"github.com/francoganga/pagoda_bun/pkg/context"
"github.com/uptrace/bun"
"github.com/labstack/echo/v4"
)
// LoadUser loads the user based on the ID provided as a path parameter
func LoadUser(bun *bun.DB) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
userID, err := strconv.Atoi(c.Param("user"))
if err != nil {
return echo.NewHTTPError(http.StatusNotFound)
}
u := new(models.User)
err = bun.NewSelect().
Model(u).
Where("id = ?", userID).
Scan(c.Request().Context())
if err == sql.ErrNoRows {
return echo.NewHTTPError(http.StatusNotFound)
}
if err == nil {
c.Set(context.UserKey, u)
return next(c)
}
return echo.NewHTTPError(
http.StatusInternalServerError,
fmt.Sprintf("error querying user: %v", err),
)
}
}
}