Add Gin framework and create REST API endpoints
Some checks failed
Release Build / release (push) Successful in 1m37s
Release Build / create-docker-image (push) Failing after 51s
Release Build / create-release (push) Has been skipped

This commit is contained in:
2025-07-27 14:42:45 +06:00
parent ee68d72fcd
commit 381eefa47b
5 changed files with 223 additions and 77 deletions

76
main.go
View File

@@ -1,23 +1,87 @@
package main
import (
"fmt"
"net/http"
"os"
"github.com/gin-gonic/gin"
)
const version = "1.0.0"
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World! (Version %s)\n", version)
// Set Gin mode
gin.SetMode(gin.ReleaseMode)
// Create router
r := gin.Default()
// Add middleware for CORS
r.Use(func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
})
// Health check endpoint
r.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"version": version,
})
})
// Main endpoint
r.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "Hello, World!",
"version": version,
})
})
// API endpoints
api := r.Group("/api/v1")
{
api.GET("/info", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"service": "hello-api",
"version": version,
"status": "running",
})
})
api.POST("/echo", func(c *gin.Context) {
var request struct {
Message string `json:"message"`
}
if err := c.ShouldBindJSON(&request); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid JSON",
})
return
}
c.JSON(http.StatusOK, gin.H{
"echo": request.Message,
"version": version,
})
})
}
// Get port from environment or use default
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Printf("Server starting on port %s...\n", port)
http.ListenAndServe(":"+port, nil)
}
// Start server
r.Run(":" + port)
}