func()

in internal/router/ui.go [73:168]


func (a *UIRouter) Register(r *gin.Engine, baseURLPath string) {
	staticPath := os.Getenv("ANSWER_STATIC_PATH")

	// if ANSWER_STATIC_PATH is set and not empty, ignore embed resource
	if staticPath != "" {
		info, err := os.Stat(staticPath)

		if err != nil || !info.IsDir() {
			log.Error(err)
		} else {
			log.Debugf("registering static path %s", staticPath)

			r.LoadHTMLGlob(staticPath + "/*.html")
			r.Static(baseURLPath+"/static", staticPath+"/static")
			r.NoRoute(func(c *gin.Context) {
				c.HTML(http.StatusOK, "index.html", gin.H{})
			})

			// return immediately if the static path is set
			return
		}
	}

	// handle the static file by default ui static files
	r.StaticFS(baseURLPath+"/static", http.FS(&_resource{
		fs: ui.Build,
	}))

	// specify the not router for default routes and redirect
	r.NoRoute(func(c *gin.Context) {
		urlPath := c.Request.URL.Path
		if len(baseURLPath) > 0 {
			urlPath = strings.TrimPrefix(urlPath, baseURLPath)
		}
		filePath := ""
		switch urlPath {
		case "/favicon.ico":
			branding, err := a.siteInfoService.GetSiteBranding(c)
			if err != nil {
				log.Error(err)
			}
			if branding.Favicon != "" {
				c.String(http.StatusOK, htmltext.GetPicByUrl(branding.Favicon))
				return
			} else if branding.SquareIcon != "" {
				c.String(http.StatusOK, htmltext.GetPicByUrl(branding.SquareIcon))
				return
			} else {
				c.Header("content-type", "image/vnd.microsoft.icon")
				filePath = UIRootFilePath + urlPath
			}
		case "/manifest.json":
			a.siteInfoController.GetManifestJson(c)
			return
		case "/install":
			// if answer is running by run command user can not access install page.
			c.Redirect(http.StatusFound, "/")
			return
		default:
			filePath = UIIndexFilePath
			c.Header("content-type", "text/html;charset=utf-8")
			c.Header("X-Frame-Options", "DENY")
		}
		file, err := ui.Build.ReadFile(filePath)
		if err != nil {
			log.Error(err)
			c.Status(http.StatusNotFound)
			return
		}

		cdnPrefix := ""
		_ = plugin.CallCDN(func(fn plugin.CDN) error {
			cdnPrefix = fn.GetStaticPrefix()
			return nil
		})
		if cdnPrefix != "" {
			if cdnPrefix[len(cdnPrefix)-1:] == "/" {
				cdnPrefix = strings.TrimSuffix(cdnPrefix, "/")
			}
			c.String(http.StatusOK, strings.ReplaceAll(string(file), "/static", cdnPrefix+"/static"))
			return
		}

		// This part is to solve the problem of returning 404 when the access path does not exist.
		// However, there is no way to check whether the current route exists in the frontend.
		// We can only hand over the route to the frontend for processing.
		// And the plugin, frontend routes can now be dynamically registered,
		// so there's no good way to get all frontend routes
		//if filePath == UIIndexFilePath {
		//	c.String(http.StatusNotFound, string(file))
		//	return
		//}

		c.String(http.StatusOK, string(file))
	})
}