github.com/blend/go-sdk@v1.20220411.3/web/rewrite_rule.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package web 9 10 import "regexp" 11 12 // RewriteAction is an action for a rewrite rule. 13 type RewriteAction func(filePath string, matchedPieces ...string) string 14 15 // RewriteRule is a rule for re-writing incoming static urls. 16 type RewriteRule struct { 17 MatchExpression string 18 expr *regexp.Regexp 19 Action RewriteAction 20 } 21 22 // Apply runs the filter, returning a bool if it matched, and the resulting path. 23 func (rr RewriteRule) Apply(filePath string) (bool, string) { 24 if rr.expr.MatchString(filePath) { 25 pieces := extractSubMatches(rr.expr, filePath) 26 return true, rr.Action(filePath, pieces...) 27 } 28 29 return false, filePath 30 } 31 32 // ExtractSubMatches returns sub matches for an expr because go's regexp library is weird. 33 func extractSubMatches(re *regexp.Regexp, corpus string) []string { 34 allResults := re.FindAllStringSubmatch(corpus, -1) 35 results := []string{} 36 for _, resultSet := range allResults { 37 results = append(results, resultSet...) 38 } 39 return results 40 }