From 09146887b25cc94e7f5eece58f0cc87b9fb35f29 Mon Sep 17 00:00:00 2001 From: jotty Date: Sat, 23 May 2026 17:11:30 +0200 Subject: [PATCH] html form example --- main.go | 18 +++++++++++------- templates/index.html | 12 ++++++++++++ 2 files changed, 23 insertions(+), 7 deletions(-) create mode 100644 templates/index.html diff --git a/main.go b/main.go index 4d5caa8..8c8cb3e 100644 --- a/main.go +++ b/main.go @@ -7,24 +7,28 @@ import ( ) type EchoRequest struct { - Message string `json:"message" binding:"required"` + Message string `form:"message" json:"message" binding:"required"` } func main() { r := gin.Default() - // GET /ping + r.LoadHTMLGlob("templates/*") + r.GET("/ping", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "pong"}) }) - // POST /echo + + r.GET("/", func(c *gin.Context) { + c.HTML(http.StatusOK, "index.html", nil) + }) + r.POST("/echo", func(c *gin.Context) { var req EchoRequest - if err := c.ShouldBindJSON(&req); err != nil { + if err := c.ShouldBind(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - return + } else { + c.JSON(http.StatusOK, gin.H{"echo": req.Message}) } - c.JSON(http.StatusOK, gin.H{"echo": req.Message}) }) - // Server starten auf Port 8080 r.Run(":8080") } diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..e05395c --- /dev/null +++ b/templates/index.html @@ -0,0 +1,12 @@ + + + + + Ping
+
+ + +
+ + + \ No newline at end of file