2
2
package handlers
3
3
4
4
import (
5
+ "fmt"
5
6
"html/template"
6
7
"net/http"
7
8
"time"
8
9
9
10
"github.com/sirupsen/logrus"
10
11
11
12
"github.com/gin-gonic/gin"
12
- "github.com/mxschmitt/golang-url-shortener/internal/handlers/tmpls "
13
+ "github.com/gobuffalo/packr/v2 "
13
14
"github.com/mxschmitt/golang-url-shortener/internal/stores"
14
15
"github.com/mxschmitt/golang-url-shortener/internal/util"
15
16
"github.com/pkg/errors"
@@ -30,6 +31,8 @@ type loggerEntryWithFields interface {
30
31
WithFields (fields logrus.Fields ) * logrus.Entry
31
32
}
32
33
34
+ var templateBox = packr .New ("Templates" , "./tmpls" )
35
+
33
36
// Ginrus returns a gin.HandlerFunc (middleware) that logs requests using logrus.
34
37
//
35
38
// Requests with errors are logged using logrus.Error().
@@ -111,7 +114,7 @@ func New(store stores.Store) (*Handler, error) {
111
114
func (h * Handler ) addTemplatesFromFS (files []string ) error {
112
115
var t * template.Template
113
116
for _ , file := range files {
114
- fileContent , err := tmpls . FSString ( false , "/" + file )
117
+ fileContent , err := templateBox . FindString ( "/" + file )
115
118
if err != nil {
116
119
return errors .Wrap (err , "could not read template file" )
117
120
}
@@ -165,6 +168,22 @@ func (h *Handler) setHandlers() error {
165
168
h .engine .GET ("/d/:id/:hash" , h .handleDelete )
166
169
h .engine .GET ("/ok" , h .handleHealthcheck )
167
170
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
+
168
187
// Handling the shorted URLs, if no one exists, it checks
169
188
// in the filesystem and sets headers for caching
170
189
h .engine .NoRoute (
@@ -176,7 +195,7 @@ func (h *Handler) setHandlers() error {
176
195
},
177
196
// Pass down to the embedded FS, but let 404s escape via
178
197
// the interceptHandler.
179
- gin .WrapH (interceptHandler (http .FileServer (FS ( false ) ), customErrorHandler )),
198
+ gin .WrapH (interceptHandler (http .FileServer (assetBox ), customErrorHandler )),
180
199
// not in FS; redirect to root with customURL target filled out
181
200
func (c * gin.Context ) {
182
201
// if we get to this point we should not let the client cache
0 commit comments