refactor: concurrently proxy img tags (#53)

This commit is contained in:
httpjamesm 2023-08-21 02:02:12 -04:00 committed by GitHub
parent 9e806186b7
commit 669187dd4d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -6,6 +6,7 @@ import (
"os" "os"
"regexp" "regexp"
"strings" "strings"
"sync"
"time" "time"
"github.com/golang-jwt/jwt/v4" "github.com/golang-jwt/jwt/v4"
@ -14,20 +15,28 @@ import (
var imgTagRegex = regexp.MustCompile(`<img[^>]*\s+src\s*=\s*"(.*?)"[^>]*>`) var imgTagRegex = regexp.MustCompile(`<img[^>]*\s+src\s*=\s*"(.*?)"[^>]*>`)
func ReplaceImgTags(inHtml string) string { func ReplaceImgTags(inHtml string) string {
// find all img tags
imgTags := imgTagRegex.FindAllString(inHtml, -1) imgTags := imgTagRegex.FindAllString(inHtml, -1)
var wg sync.WaitGroup
var mu sync.Mutex
for _, imgTag := range imgTags { for _, imgTag := range imgTags {
// parse the src="" attribute wg.Add(1)
srcRegex := regexp.MustCompile(`src\s*=\s*"(.*?)"`) go func(imgTag string) {
src := srcRegex.FindStringSubmatch(imgTag)[1] defer wg.Done()
srcRegex := regexp.MustCompile(`src\s*=\s*"(.*?)"`)
src := srcRegex.FindStringSubmatch(imgTag)[1]
authToken, _ := generateImageProxyAuth(src) authToken, _ := generateImageProxyAuth(src)
// replace the img tag with a proxied url mu.Lock()
inHtml = strings.Replace(inHtml, imgTag, fmt.Sprintf(`<img src="%s/proxy?auth=%s">`, os.Getenv("APP_URL"), authToken), 1) defer mu.Unlock()
inHtml = strings.Replace(inHtml, imgTag, fmt.Sprintf(`<img src="%s/proxy?auth=%s">`, os.Getenv("APP_URL"), authToken), 1)
}(imgTag)
} }
wg.Wait()
return inHtml return inHtml
} }