22package handlers
33
44import (
5+ "fmt"
56 "html/template"
67 "net/http"
78 "time"
89
910 "github.com/sirupsen/logrus"
1011
1112 "github.com/gin-gonic/gin"
12- "github.com/mxschmitt/golang-url-shortener/internal/handlers/tmpls "
13+ "github.com/gobuffalo/packr/v2 "
1314 "github.com/mxschmitt/golang-url-shortener/internal/stores"
1415 "github.com/mxschmitt/golang-url-shortener/internal/util"
1516 "github.com/pkg/errors"
@@ -30,6 +31,8 @@ type loggerEntryWithFields interface {
3031 WithFields (fields logrus.Fields ) * logrus.Entry
3132}
3233
34+ var templateBox = packr .New ("Templates" , "./tmpls" )
35+
3336// Ginrus returns a gin.HandlerFunc (middleware) that logs requests using logrus.
3437//
3538// Requests with errors are logged using logrus.Error().
@@ -111,7 +114,7 @@ func New(store stores.Store) (*Handler, error) {
111114func (h * Handler ) addTemplatesFromFS (files []string ) error {
112115 var t * template.Template
113116 for _ , file := range files {
114- fileContent , err := tmpls . FSString ( false , "/" + file )
117+ fileContent , err := templateBox . FindString ( "/" + file )
115118 if err != nil {
116119 return errors .Wrap (err , "could not read template file" )
117120 }
@@ -165,6 +168,22 @@ func (h *Handler) setHandlers() error {
165168 h .engine .GET ("/d/:id/:hash" , h .handleDelete )
166169 h .engine .GET ("/ok" , h .handleHealthcheck )
167170
171+ assetBox := packr .New ("Assets" , "../../web/build" )
172+
173+ h .engine .GET ("/" , func (c * gin.Context ) {
174+ f , err := assetBox .Open ("index.html" )
175+ if err != nil {
176+ http .Error (c .Writer , fmt .Sprintf ("could not open index.html: %v" , err ), http .StatusInternalServerError )
177+ return
178+ }
179+ fi , err := f .Stat ()
180+ if err != nil {
181+ http .Error (c .Writer , fmt .Sprintf ("could not stat index.html: %v" , err ), http .StatusInternalServerError )
182+ return
183+ }
184+ http .ServeContent (c .Writer , c .Request , fi .Name (), fi .ModTime (), f )
185+ })
186+
168187 // Handling the shorted URLs, if no one exists, it checks
169188 // in the filesystem and sets headers for caching
170189 h .engine .NoRoute (
@@ -176,7 +195,7 @@ func (h *Handler) setHandlers() error {
176195 },
177196 // Pass down to the embedded FS, but let 404s escape via
178197 // the interceptHandler.
179- gin .WrapH (interceptHandler (http .FileServer (FS ( false ) ), customErrorHandler )),
198+ gin .WrapH (interceptHandler (http .FileServer (assetBox ), customErrorHandler )),
180199 // not in FS; redirect to root with customURL target filled out
181200 func (c * gin.Context ) {
182201 // if we get to this point we should not let the client cache
0 commit comments