| 1 | package tinyclient |
| 2 | |
| 3 | import ( |
| 4 | "regexp" |
| 5 | "strings" |
| 6 | |
| 7 | "golang.org/x/net/html" |
| 8 | ) |
| 9 | |
| 10 | var rootURLAttribute = regexp.MustCompile(`\s(?:href|src|fx-action|action|data|fallback)="(/[^\"]*)"` ) |
| 11 | |
| 12 | // injectBase scopes root-relative template URLs without changing scripts or |
| 13 | // literal content. The signer bridge scopes its requests with localPath. |
| 14 | func injectBase(source, base string) string { |
| 15 | if base == "" { |
| 16 | return source |
| 17 | } |
| 18 | var out strings.Builder |
| 19 | out.Grow(len(source)) |
| 20 | tokens := html.NewTokenizer(strings.NewReader(source)) |
| 21 | for { |
| 22 | kind := tokens.Next() |
| 23 | raw := string(tokens.Raw()) |
| 24 | if kind == html.StartTagToken || kind == html.SelfClosingTagToken { |
| 25 | raw = rootURLAttribute.ReplaceAllStringFunc(raw, func(attribute string) string { |
| 26 | start := strings.IndexByte(attribute, '"' ) + 1 |
| 27 | path := attribute[start : len(attribute)-1] |
| 28 | if strings.HasPrefix(path, "//" ) || path == base || strings.HasPrefix(path, base+"/" ) { |
| 29 | return attribute |
| 30 | } |
| 31 | return attribute[:start] + base + path + `"` |
| 32 | }) |
| 33 | } |
| 34 | out.WriteString(raw) |
| 35 | if kind == html.ErrorToken { |
| 36 | return out.String() |
| 37 | } |
| 38 | } |
| 39 | } |