Create creates the gin engine with all routes.
(db *database.GormDatabase, vInfo *model.VersionInfo, conf *config.Configuration)
| 25 | |
| 26 | // Create creates the gin engine with all routes. |
| 27 | func Create(db *database.GormDatabase, vInfo *model.VersionInfo, conf *config.Configuration) (*gin.Engine, func()) { |
| 28 | g := gin.New() |
| 29 | |
| 30 | g.RemoveExtraSlash = true |
| 31 | g.RemoteIPHeaders = []string{"X-Forwarded-For"} |
| 32 | g.SetTrustedProxies(conf.Server.TrustedProxies) |
| 33 | g.ForwardedByClientIP = true |
| 34 | |
| 35 | g.Use(func(ctx *gin.Context) { |
| 36 | // Map sockets "@" to 127.0.0.1, because gin-gonic can only trust IPs. |
| 37 | if ctx.Request.RemoteAddr == "@" { |
| 38 | ctx.Request.RemoteAddr = "127.0.0.1:65535" |
| 39 | } |
| 40 | }) |
| 41 | |
| 42 | g.Use(gin.LoggerWithFormatter(logFormatter), gin.Recovery(), gerror.Handler(), location.Default()) |
| 43 | g.NoRoute(gerror.NotFound()) |
| 44 | |
| 45 | if conf.Server.SSL.Enabled && conf.Server.SSL.RedirectToHTTPS { |
| 46 | g.Use(func(ctx *gin.Context) { |
| 47 | if ctx.Request.TLS != nil { |
| 48 | ctx.Next() |
| 49 | return |
| 50 | } |
| 51 | if ctx.Request.Method != http.MethodGet && ctx.Request.Method != http.MethodHead { |
| 52 | ctx.Data(http.StatusBadRequest, "text/plain; charset=utf-8", []byte("Use HTTPS")) |
| 53 | ctx.Abort() |
| 54 | return |
| 55 | } |
| 56 | host := ctx.Request.Host |
| 57 | if idx := strings.LastIndex(host, ":"); idx != -1 { |
| 58 | host = host[:idx] |
| 59 | } |
| 60 | if conf.Server.SSL.Port != 443 { |
| 61 | host = fmt.Sprintf("%s:%d", host, conf.Server.SSL.Port) |
| 62 | } |
| 63 | ctx.Redirect(http.StatusFound, fmt.Sprintf("https://%s%s", host, ctx.Request.RequestURI)) |
| 64 | ctx.Abort() |
| 65 | }) |
| 66 | } |
| 67 | streamHandler := stream.New( |
| 68 | time.Duration(conf.Server.Stream.PingPeriodSeconds)*time.Second, 15*time.Second, conf.Server.Stream.AllowedOrigins) |
| 69 | go func() { |
| 70 | ticker := time.NewTicker(5 * time.Minute) |
| 71 | for range ticker.C { |
| 72 | connectedTokens := streamHandler.CollectConnectedClientTokens() |
| 73 | now := time.Now() |
| 74 | db.UpdateClientTokensLastUsed(connectedTokens, &now) |
| 75 | } |
| 76 | }() |
| 77 | authentication := auth.Auth{DB: db} |
| 78 | messageHandler := api.MessageAPI{Notifier: streamHandler, DB: db} |
| 79 | healthHandler := api.HealthAPI{DB: db} |
| 80 | clientHandler := api.ClientAPI{ |
| 81 | DB: db, |
| 82 | ImageDir: conf.UploadedImagesDir, |
| 83 | NotifyDeleted: streamHandler.NotifyDeletedClient, |
| 84 | } |
searching dependent graphs…