snippet/gin2/gin.go

87 lines
1.5 KiB
Go

package gin
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"github.com/unrolled/secure"
)
var (
rootPath string
addr string
port int
ssl string
sslPem string
sslKey string
)
func Service() {
rootPath = os.Getenv("GIN_PATH")
if rootPath == "" {
rootPath = "/"
}
addr = os.Getenv("GIN_ADDR")
if addr == "" {
addr = "0.0.0.0"
}
port, _ = strconv.Atoi(os.Getenv("GIN_PORT"))
if port == 0 {
port = 8080
}
ssl = os.Getenv("GIN_SSL")
sslPem = os.Getenv("GIN_SSL_PEM")
sslKey = os.Getenv("GIN_SSL_KEY")
go func() {
router := gin.New()
routerSetup(router, &rootPath)
if ssl == "true" {
router.Use(tlsHandler())
}
s := &http.Server{
Addr: fmt.Sprintf("%s:%d", addr, port),
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
logrus.WithFields(logrus.Fields{
"func": "Service",
}).Infof("start service on %s:%d", addr, port)
if ssl == "true" {
log.Fatal(s.ListenAndServeTLS(sslPem, sslKey))
} else {
log.Fatal(s.ListenAndServe())
}
}()
}
func tlsHandler() gin.HandlerFunc {
return func(c *gin.Context) {
secureMiddleware := secure.New(secure.Options{
SSLRedirect: true,
SSLHost: ":" + strconv.Itoa(port),
})
err := secureMiddleware.Process(c.Writer, c.Request)
// If there was an error, do not continue.
if err != nil {
return
}
c.Next()
}
}