github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/dm/ui/server.go (about)

     1  // Copyright 2021 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  // this file implement all of the APIs of the DataMigration service.
    15  
    16  package ui
    17  
    18  import (
    19  	"io/fs"
    20  	"net/http"
    21  	"strings"
    22  
    23  	"github.com/gin-gonic/gin"
    24  	"github.com/pingcap/tiflow/dm/openapi"
    25  	"github.com/pingcap/tiflow/dm/pkg/log"
    26  	"go.uber.org/zap"
    27  )
    28  
    29  const (
    30  	buildPath  = "dist"
    31  	assetsPath = "assets"
    32  	basePath   = "/dashboard/"
    33  )
    34  
    35  var webFS = NewWebUIAssetsFS()
    36  
    37  // WebUIAssetsHandler returns a http handler for serving static files and strip the dist prefix.
    38  func NewWebUIAssetsFS() http.FileSystem {
    39  	stripped, err := fs.Sub(WebUIAssets, buildPath)
    40  	if err != nil {
    41  		panic(err) // this should never happen
    42  	}
    43  	return http.FS(stripped)
    44  }
    45  
    46  // we need this to handle this case: user want to access /dashboard/source.html/ but webui is a single page app,
    47  // and it only can handle requests in index page, so we need to return to index.html and let js handler request.
    48  func returnIndex() gin.HandlerFunc {
    49  	return func(c *gin.Context) {
    50  		// If it is not a request to assets return the default index.html
    51  		if c.Request.URL.Path != basePath && !strings.Contains(c.Request.URL.Path, assetsPath) {
    52  			c.FileFromFS("/", webFS)
    53  		} else {
    54  			c.Next()
    55  		}
    56  	}
    57  }
    58  
    59  // InitWebUIRouter initializes the webUI router.
    60  func InitWebUIRouter() *gin.Engine {
    61  	router := gin.New()
    62  	router.Use(gin.Recovery())
    63  	router.Use(openapi.ZapLogger(log.L().WithFields(zap.String("component", "webui")).Logger))
    64  	router.Use(returnIndex())
    65  	router.StaticFS(basePath, webFS)
    66  	return router
    67  }