66 lines
1.2 KiB
Go
66 lines
1.2 KiB
Go
package gin
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/unrolled/secure"
|
|
)
|
|
|
|
func Service(conf *Config) {
|
|
if conf == nil {
|
|
conf = &Config{
|
|
RootPath: "/",
|
|
Addr: "0.0.0.0",
|
|
Port: 80,
|
|
Ssl: false,
|
|
SslPem: "server.pem",
|
|
SslKey: "server.key",
|
|
}
|
|
}
|
|
go func() {
|
|
router := gin.New()
|
|
routerSetup(router, &conf.RootPath)
|
|
|
|
if conf.Ssl {
|
|
router.Use(tlsHandler(conf))
|
|
}
|
|
|
|
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))
|
|
|
|
if conf.Ssl {
|
|
log.Fatal(s.ListenAndServeTLS(conf.SslPem, conf.SslKey))
|
|
} else {
|
|
log.Fatal(s.ListenAndServe())
|
|
}
|
|
}()
|
|
}
|
|
|
|
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()
|
|
}
|
|
}
|