code-examples/2024/10/golang_webserver_demo1/main.go

50 lines
818 B
Go

package main
import (
"github.com/gin-gonic/gin"
"os"
"time"
)
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
"datetime": time.Now(),
})
})
r.GET("/info", func(c *gin.Context) {
var directories []map[string]string
dirs, err := os.ReadDir(".")
if err != nil {
c.JSON(500, gin.H{
"message": "it failed",
})
return
}
for _, dir := range dirs {
m := make(map[string]string)
m["name"] = dir.Name()
if dir.IsDir() {
m["dir"] = "yes"
} else {
m["dir"] = "no"
}
directories = append(directories, m)
}
c.JSON(200, gin.H{
"dirs": directories,
})
})
err := r.Run("localhost:8080")
if err != nil {
panic("Couldn't run the server. It failed with the error: " + err.Error())
}
}