-
Notifications
You must be signed in to change notification settings - Fork 11
/
hello_world.go
71 lines (60 loc) · 1.36 KB
/
hello_world.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"flag"
"fmt"
"net/http"
"os"
"runtime"
"github.com/gin-gonic/gin"
ginprometheus "github.com/zsais/go-gin-prometheus"
)
func serviceInfoMiddleware() gin.HandlerFunc {
var hostname, err = os.Hostname()
if err != nil {
panic(err)
}
return func(c *gin.Context) {
c.Writer.Header().Set("X-Hostname", hostname)
c.Next()
}
}
func getVersion() string {
return "$Id$"
}
func helloFunc(c *gin.Context) {
c.String(http.StatusOK, "Hello, World!")
}
func healthFunc(c *gin.Context) {
c.String(http.StatusOK, "")
}
func versionFunc(c *gin.Context) {
c.String(http.StatusOK, getVersion())
}
func setupRouter(routePrefix string) *gin.Engine {
router := gin.Default()
ginprom := ginprometheus.NewPrometheus("gin")
ginprom.Use(router)
router.Use(serviceInfoMiddleware())
router.Use(func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
})
router.GET("/health", healthFunc)
rg := router.Group(routePrefix)
rg.GET("/", helloFunc)
rg.GET("/version", versionFunc)
return router
}
func main() {
optRoutePrefix := flag.String("route-prefix", "/", "Route prefix")
optVersion := flag.Bool("version", false, "Print version")
flag.Parse()
if *optVersion {
fmt.Fprintf(os.Stderr, "Version: %s\nArch: %s\n",
getVersion(),
runtime.GOARCH,
)
} else {
router := setupRouter(*optRoutePrefix)
_ = router.Run()
}
}