-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
85 lines (69 loc) · 1.97 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
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"time"
"github.com/crownbackend/golang-api-blog/handlers"
"github.com/crownbackend/golang-api-blog/middleware"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/go-sql-driver/mysql"
)
var db *sql.DB
func main() {
// connect database
connectDb()
// config gin
r := gin.Default()
// Configuration CORS
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:5173"}, // Changez ces valeurs selon vos besoins
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"}, // Méthodes HTTP autorisées
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"}, // En-têtes autorisés
ExposeHeaders: []string{"Content-Length"}, // En-têtes exposés
AllowCredentials: true, // Permet l'envoi des cookies
MaxAge: 12 * time.Hour, // Durée de validité des pré-vols CORS
}))
// list of routes
r.GET("/", home)
r.POST("/users", handlers.CreateUser)
r.POST("/login", handlers.Login)
r.GET("/posts", handlers.GetPosts)
protected := r.Group("/users")
protected.Use(middleware.AuthMiddleware(db))
{
protected.GET("", handlers.GetUsers)
}
pProtected := r.Group("/posts/")
pProtected.Use(middleware.AuthMiddleware(db))
{
// pProtected.GET("add", handlers.GetPosts)
}
// run server
r.Run("localhost:8000")
}
func home(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"data": "testo"})
}
func connectDb() {
cfg := mysql.Config{
User: "root",
Passwd: "root",
Net: "tcp",
Addr: "127.0.0.1:3308",
DBName: "blog",
}
var err error
db, err = sql.Open("mysql", cfg.FormatDSN())
if err != nil {
log.Fatal(err)
}
pingErr := db.Ping()
if pingErr != nil {
log.Fatal(pingErr)
}
handlers.InitializeDatabase(db)
fmt.Println("Connected!")
}