commit c92ba81367032b79166d3eb69ec685d9dc7b2f98 Author: opencode Date: Sun Feb 22 16:15:38 2026 +0000 feat: initial Gin-Go web app scaffold diff --git a/README.md b/README.md new file mode 100644 index 0000000..3f51e18 --- /dev/null +++ b/README.md @@ -0,0 +1,19 @@ +# Gin + Go Web App + +This is a minimal, functional Go application using the Gin web framework. +Features: +- Basic REST endpoints +- HTML page rendering with templates +- In-memory data store for demonstration + +How to run +- Install Go (1.20+) +- go mod download +- go run main.go +- Open http://localhost:8080 + +Structure +- main.go: application entry and routes +- templates/index.html: HTML template for root page +- static/style.css: simple CSS +- go.mod: module declaration diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..886295a --- /dev/null +++ b/go.mod @@ -0,0 +1,2 @@ +module example.com/ginapp +go 1.20 diff --git a/main.go b/main.go new file mode 100644 index 0000000..477f488 --- /dev/null +++ b/main.go @@ -0,0 +1,65 @@ +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") +} diff --git a/static/style.css b/static/style.css new file mode 100644 index 0000000..2d2034c --- /dev/null +++ b/static/style.css @@ -0,0 +1,3 @@ +body { font-family: Arial, sans-serif; padding: 2rem; background: #f7f9fc; color: #333; } +h1 { color: #2c3e50; } +#app { max-width: 800px; margin: 0 auto; } diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..f3f22b3 --- /dev/null +++ b/templates/index.html @@ -0,0 +1,56 @@ + + + + + {{ .title }} + + + +

{{ .title }}

+

{{ .message }}

+ +
+

Users

+ +
+ + + +
+
+ + + +