Files
opencode-cs/main.go
2026-02-22 16:15:38 +00:00

66 lines
1.2 KiB
Go

package main
import (
"net/http"
"sync"
"github.com/gin-gonic/gin"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
var (
users = []User{
{ID: 1, Name: "Alice", Email: "alice@example.com"},
{ID: 2, Name: "Bob", Email: "bob@example.com"},
}
nextID = 3
mu sync.Mutex
)
func main() {
r := gin.Default()
// HTML 模板
r.LoadHTMLGlob("templates/*.html")
// 静态资源
r.Static("/static", "./static")
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"title": "Gin Web App",
"message": "Welcome to Gin with Go",
})
})
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "pong"})
})
r.GET("/users", func(c *gin.Context) {
mu.Lock()
defer mu.Unlock()
c.JSON(http.StatusOK, users)
})
r.POST("/users", func(c *gin.Context) {
var newUser User
if err := c.ShouldBindJSON(&newUser); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
mu.Lock()
newUser.ID = nextID
nextID++
users = append(users, newUser)
mu.Unlock()
c.JSON(http.StatusCreated, newUser)
})
r.Run(":8080")
}