snippet/gin/gin.go

69 lines
1.2 KiB
Go
Raw Normal View History

2021-12-03 03:36:40 +00:00
package gin
import (
"fmt"
"log"
"net/http"
2022-10-20 05:29:58 +00:00
"strconv"
2021-12-03 03:36:40 +00:00
"time"
"github.com/gin-gonic/gin"
2022-10-20 05:29:58 +00:00
"github.com/unrolled/secure"
2021-12-03 03:36:40 +00:00
)
func Service(conf *Config) {
2021-12-03 06:00:37 +00:00
if conf == nil {
2023-09-13 09:27:25 +00:00
conf = &Config{}
}
if conf.RootPath == "" {
conf.RootPath = "/"
}
if conf.Addr == "" {
conf.Addr = "0.0.0.0"
2021-12-03 06:00:37 +00:00
}
2023-09-13 09:27:25 +00:00
if conf.Port == 0 {
conf.Port = 8080
}
2021-12-03 03:36:40 +00:00
go func() {
router := gin.New()
2021-12-03 06:00:37 +00:00
routerSetup(router, &conf.RootPath)
2022-10-20 05:29:58 +00:00
if conf.Ssl {
router.Use(tlsHandler(conf))
}
2021-12-03 03:36:40 +00:00
s := &http.Server{
Addr: fmt.Sprintf("%s:%d", conf.Addr, conf.Port),
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Printf("start service on %s", fmt.Sprintf("%s:%d", conf.Addr, conf.Port))
2022-10-20 05:29:58 +00:00
if conf.Ssl {
log.Fatal(s.ListenAndServeTLS(conf.SslPem, conf.SslKey))
} else {
log.Fatal(s.ListenAndServe())
}
2021-12-03 03:36:40 +00:00
}()
}
2022-10-20 05:29:58 +00:00
func tlsHandler(conf *Config) gin.HandlerFunc {
return func(c *gin.Context) {
secureMiddleware := secure.New(secure.Options{
SSLRedirect: true,
SSLHost: ":" + strconv.Itoa(conf.Port),
})
err := secureMiddleware.Process(c.Writer, c.Request)
// If there was an error, do not continue.
if err != nil {
return
}
c.Next()
}
}