github.com/grafviktor/keep-my-secret@v0.9.10-0.20230908165355-19f35cce90e5/internal/api/web/handler_static.go (about)

     1  package web
     2  
     3  import (
     4  	"net/http"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  
     9  	"github.com/go-chi/chi/v5"
    10  
    11  	"github.com/grafviktor/keep-my-secret/internal/config"
    12  )
    13  
    14  var serveDir = "./ui/static"
    15  
    16  // registerStaticHandler - registers a handler for serving client application.
    17  func registerStaticHandler(config config.AppConfig, router *chi.Mux) {
    18  	workDir, _ := os.Getwd()
    19  	fsPath := http.Dir(filepath.Join(workDir, serveDir))
    20  	url := config.ClientAppURL
    21  
    22  	if len(url) == 0 {
    23  		url = "/"
    24  	}
    25  
    26  	if strings.ContainsAny(url, "{}*") {
    27  		panic("FileServer does not permit any URL parameters.")
    28  	}
    29  
    30  	if url != "/" && url[len(url)-1] != '/' {
    31  		url += "/"
    32  	}
    33  	url += "*"
    34  
    35  	router.Get(url, func(w http.ResponseWriter, r *http.Request) {
    36  		ctx := chi.RouteContext(r.Context())
    37  		pathPrefix := strings.TrimSuffix(ctx.RoutePattern(), "/*")
    38  		fs := http.StripPrefix(pathPrefix, http.FileServer(fsPath))
    39  		fs.ServeHTTP(w, r)
    40  	})
    41  }