github.com/web-platform-tests/wpt.fyi@v0.0.0-20240530210107-70cf978996f1/webapp/components_handler.go (about) 1 // Copyright 2018 The WPT Dashboard Project. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 //go:generate packr2 6 7 package webapp 8 9 import ( 10 "fmt" 11 "mime" 12 "net/http" 13 "path/filepath" 14 "regexp" 15 16 "github.com/gobuffalo/packr/v2" 17 "github.com/gorilla/mux" 18 ) 19 20 const packageRegexReplacement = "$1 $2/node_modules/$3" 21 22 var ( 23 packageRegex = regexp.MustCompile(`(import .* from|import) (['"])(@[^/]*/)`) 24 box *packr.Box 25 ) 26 27 func init() { 28 box = packr.New("node modules", "./node_modules/") 29 } 30 31 // componentsHandler loads a /node_modules/ path, and replaces any 32 // npm package loads in the js file with paths on the host. 33 func componentsHandler(w http.ResponseWriter, r *http.Request) { 34 filePath := mux.Vars(r)["path"] 35 body, err := box.FindString(filePath) 36 if err != nil || body == "" { 37 http.Error(w, fmt.Sprintf("Component %s not found", filePath), http.StatusNotFound) 38 return 39 } 40 body = packageRegex.ReplaceAllString(body, packageRegexReplacement) 41 // Cache up to a day (same as the default expiration in app.yaml). 42 w.Header().Set("Cache-Control", "public, max-age=86400") 43 w.Header().Set("Content-Type", mime.TypeByExtension(filepath.Ext(filePath))) 44 w.Write([]byte(body)) 45 }