go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/projects/chirp/pkg/controller/static.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package controller
     9  
    10  import (
    11  	"net/http"
    12  	"net/url"
    13  	"path/filepath"
    14  
    15  	"go.charczuk.com/sdk/apputil"
    16  	"go.charczuk.com/sdk/web"
    17  
    18  	"go.charczuk.com/projects/chirp/pkg/static"
    19  )
    20  
    21  type Static struct {
    22  	apputil.BaseController
    23  
    24  	NextProxyURL string
    25  }
    26  
    27  func (s Static) Register(app *web.App) {
    28  	app.Views.FuncMap["age"] = viewfuncAge
    29  	app.Views.AddFS(web.ViewFS{FS: static.Views, Patterns: []string{"_views/*.html"}})
    30  
    31  	staticSearchPaths := []http.FileSystem{http.FS(static.Static)}
    32  	staticFS := &web.StaticFileServer{
    33  		SearchPaths: staticSearchPaths,
    34  		RewriteRules: []web.RewriteRule{
    35  			web.RewriteRuleFunc(func(path string) (string, bool) {
    36  				return filepath.Join("_static", path), true
    37  			}),
    38  		},
    39  	}
    40  	app.HandleAction(http.MethodGet, "/static/*filepath", staticFS.Action)
    41  
    42  	if s.NextProxyURL != "" {
    43  		proxyURL, _ := url.Parse(s.NextProxyURL)
    44  		app.HandleAction(http.MethodGet, "/_next/static/*filepath", web.SessionRequired(web.ProxyAction(proxyURL)))
    45  	} else {
    46  		nextSearchPaths := []http.FileSystem{http.FS(static.Next)}
    47  		nextFS := &web.StaticFileServer{
    48  			UseEmptyResponseIfNotFound: true,
    49  			SearchPaths:                nextSearchPaths,
    50  			RewriteRules: []web.RewriteRule{
    51  				web.RewriteRuleFunc(func(path string) (string, bool) {
    52  					return filepath.Join("_nextjs/_dist/_next/static", path), true
    53  				}),
    54  			},
    55  		}
    56  		app.HandleAction(http.MethodGet, "/_next/static/*filepath", web.SessionRequired(nextFS.Action))
    57  	}
    58  }