5
0
mirror of https://github.com/wailsapp/wails.git synced 2025-05-04 01:31:54 +08:00

Update v3/examples/gin-service/services/gin_service.go

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
This commit is contained in:
Lea Anthony 2025-04-18 15:49:41 +10:00 committed by GitHub
parent e97c390f12
commit 1f5e9852e4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -137,30 +137,57 @@ func (s *GinService) setupRoutes() {
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
}) })
// Create a new user // import block (ensure this exists in your file)
users.POST("", func(c *gin.Context) { import (
var newUser User "context"
if err := c.ShouldBindJSON(&newUser); err != nil { "net/http"
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) "strconv"
return "strings"
} "sync"
"time"
)
s.mu.Lock() // ...
defer s.mu.Unlock()
// Set the ID and creation time // Create a new user
newUser.ID = s.nextID users.POST("", func(c *gin.Context) {
newUser.CreatedAt = time.Now() var newUser User
s.nextID++ if err := c.ShouldBindJSON(&newUser); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Add to the users slice // Validate required fields
s.users = append(s.users, newUser) if newUser.Name == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Name is required"})
return
}
if newUser.Email == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Email is required"})
return
}
// Basic email validation (consider using a proper validator library in production)
if !strings.Contains(newUser.Email, "@") {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid email format"})
return
}
c.JSON(http.StatusCreated, newUser) s.mu.Lock()
defer s.mu.Unlock()
// Emit an event to notify about the new user // Set the ID and creation time
s.app.EmitEvent("user-created", newUser) newUser.ID = s.nextID
}) newUser.CreatedAt = time.Now()
s.nextID++
// Add to the users slice
s.users = append(s.users, newUser)
c.JSON(http.StatusCreated, newUser)
// Emit an event to notify about the new user
s.app.EmitEvent("user-created", newUser)
})
// Delete a user // Delete a user
users.DELETE("/:id", func(c *gin.Context) { users.DELETE("/:id", func(c *gin.Context) {