2022-06-06 08:47:38 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
|
|
|
|
|
|
|
type App struct {
|
|
|
|
router *gin.Engine
|
|
|
|
srv *http.Server
|
|
|
|
bind string
|
2022-06-06 09:02:35 +00:00
|
|
|
ips []string
|
2022-06-06 08:47:38 +00:00
|
|
|
}
|
|
|
|
|
2022-06-06 09:02:35 +00:00
|
|
|
func NewApp(htpasswd_file *string, restrict_to_ips *string, baseURL string, bind string) App {
|
2022-06-06 08:47:38 +00:00
|
|
|
gin.ForceConsoleColor()
|
|
|
|
router := gin.Default()
|
|
|
|
|
|
|
|
var baserouter *gin.RouterGroup
|
|
|
|
if len(baseURL) > 1 {
|
|
|
|
router.GET("/", func(c *gin.Context) {
|
|
|
|
c.Redirect(http.StatusFound, baseURL)
|
|
|
|
})
|
|
|
|
|
|
|
|
baserouter = router.Group(baseURL)
|
|
|
|
} else {
|
|
|
|
baserouter = router.Group("")
|
|
|
|
}
|
2022-06-06 08:48:06 +00:00
|
|
|
|
|
|
|
if htpasswd_file != nil && len(*htpasswd_file) > 0 {
|
|
|
|
baserouter.Use(Htpassword(*htpasswd_file))
|
|
|
|
}
|
|
|
|
|
2022-06-06 08:47:38 +00:00
|
|
|
app := App{
|
|
|
|
router: router,
|
|
|
|
bind: bind,
|
|
|
|
}
|
|
|
|
|
2022-06-06 09:02:35 +00:00
|
|
|
if restrict_to_ips != nil && len(*restrict_to_ips) > 0 {
|
2022-06-06 09:26:23 +00:00
|
|
|
app.loadAndWatchIPs(*restrict_to_ips)
|
2022-06-06 09:02:35 +00:00
|
|
|
baserouter.Use(app.Restrict2IPs)
|
|
|
|
}
|
|
|
|
|
|
|
|
declareStaticRoutes(baserouter, baseURL)
|
|
|
|
|
2022-06-06 08:47:38 +00:00
|
|
|
return app
|
|
|
|
}
|
|
|
|
|
|
|
|
func (app *App) Start() {
|
|
|
|
app.srv = &http.Server{
|
2023-07-14 14:37:00 +00:00
|
|
|
Addr: app.bind,
|
|
|
|
Handler: app.router,
|
|
|
|
ReadHeaderTimeout: 15 * time.Second,
|
|
|
|
ReadTimeout: 15 * time.Second,
|
|
|
|
WriteTimeout: 10 * time.Second,
|
|
|
|
IdleTimeout: 30 * time.Second,
|
2022-06-06 08:47:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("Ready, listening on %s\n", app.bind)
|
|
|
|
if err := app.srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
|
|
log.Fatalf("listen: %s\n", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (app *App) Stop() {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
if err := app.srv.Shutdown(ctx); err != nil {
|
|
|
|
log.Fatal("Server Shutdown:", err)
|
|
|
|
}
|
|
|
|
}
|