go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/projects/nodes/pkg/controller/index.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  
    14  	"go.charczuk.com/sdk/apputil"
    15  	"go.charczuk.com/sdk/web"
    16  
    17  	"go.charczuk.com/projects/nodes/static"
    18  )
    19  
    20  type Index struct {
    21  	apputil.BaseController
    22  	NextProxyURL string
    23  }
    24  
    25  func (i Index) Register(app *web.App) {
    26  	i.clientAppPath(app, "/")
    27  }
    28  
    29  // clientAppPath is broken out as a helper in case we need to have
    30  // multiple _server_ routes that point to the nextjs SPA.
    31  func (i Index) clientAppPath(app *web.App, path string) {
    32  	if i.NextProxyURL != "" {
    33  		nextProxy := i.indexProxied()
    34  		app.Get(path, web.SessionRequired(nextProxy))
    35  		app.NotFoundHandler = app.ActionHandler(web.SessionRequired(nextProxy))
    36  	} else {
    37  		app.Get(path, web.SessionRequired(i.indexStatic))
    38  		app.NotFoundHandler = app.ActionHandler(web.SessionRequired(i.indexStatic))
    39  	}
    40  }
    41  
    42  func (i Index) indexProxied() web.Action {
    43  	nextProxyURL, _ := url.Parse(i.NextProxyURL)
    44  	return web.ProxyAction(nextProxyURL)
    45  }
    46  
    47  func (i Index) indexStatic(ctx web.Context) web.Result {
    48  	return web.Static(ctx, http.FS(static.Next), "_nextjs/_dist/index.html")
    49  }