-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
74 lines (68 loc) · 1.71 KB
/
main.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
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
package main
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
"github.com/theshid/go-trok/src/models"
"github.com/theshid/go-trok/src/routes"
"net/http"
"strings"
)
func main() {
conn, err := connectDb()
if err != nil {
return
}
router := gin.Default()
router.Use(dbMiddleware(*conn))
usersGroup := router.Group("users")
{
usersGroup.POST("register", routes.UserRegister)
usersGroup.POST("login", routes.UsersLogin)
}
itemsGroup := router.Group("items")
{
itemsGroup.GET("index", routes.ItemsIndex)
itemsGroup.POST("create",authMiddleware(),routes.ItemsCreate)
itemsGroup.GET("sold_by_user",authMiddleware(),routes.ItemsForSaleByCurrentUser)
itemsGroup.PUT("update",authMiddleware(),routes.ItemsUpdate)
}
router.Run(":3000")
}
func connectDb() (c *pgx.Conn, err error) {
conn, err := pgx.Connect(context.Background(), "postgresql://postgres:@localhost:5434/trok")
if err != nil {
fmt.Println("Error connecting to DB")
fmt.Println(err.Error())
}
_ = conn.Ping(context.Background())
return conn, err
}
func dbMiddleware(conn pgx.Conn)gin.HandlerFunc{
return func (c *gin.Context){
c.Set("db",conn)
c.Next()
}
}
func authMiddleware() gin.HandlerFunc{
return func(c *gin.Context){
bearer := c.Request.Header.Get("Authorization")
split := strings.Split(bearer,"Bearer ")
if len(split)<2 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "not authenticated."})
c.Abort()
return
}
token := split[1]
//fmt.Printf("Bearer (%v) \n", token)
isValid, userID := models.IsTokenValid(token)
if isValid == false {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Not authenticated."})
c.Abort()
} else {
c.Set("user_id", userID)
c.Next()
}
}
}