From 0a79ea224577eb593546522b3e073e965d74a595 Mon Sep 17 00:00:00 2001 From: Mohammed Al Ashaal Date: Thu, 28 Jun 2018 09:10:33 +0200 Subject: [PATCH] added some fixes --- main.go | 54 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 37 insertions(+), 17 deletions(-) diff --git a/main.go b/main.go index 6cbe0ef..3f68094 100644 --- a/main.go +++ b/main.go @@ -8,6 +8,7 @@ import ( "net/http" "net/url" "os" + "path" "regexp" "strings" @@ -44,6 +45,8 @@ func main() { m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify) m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify) + cssUrls := regexp.MustCompile(`(url|\@import)\((.*?)\)`) + forwarder := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { var err error @@ -74,27 +77,44 @@ func main() { return err } - bundleCSS := "" + // bundleCSS := "" doc.Find("link").Each(func(_ int, s *goquery.Selection) { dst := s.AttrOr("href", "") if dst == "" { return } - dst = fixURL(dst, w.Request.Host) - u, err := url.Parse(dst) - if err != nil || !strings.HasSuffix(u.Path, "css") { + if s.AttrOr("rel", "") != "stylesheet" { return } - if u.Host != w.Request.Host { + dst = fixURL(dst, w.Request.Host) + u, err := url.Parse(dst) + if err != nil { return } + // if u.Host != w.Request.Host { + // return + // } if d := fetch(dst); d != "" { - bundleCSS += d - s.Remove() + for _, val := range cssUrls.FindAllStringSubmatch(d, -1) { + newURL := strings.Trim(val[2], `"'`) + if !strings.HasPrefix(newURL, "http://") && !strings.HasPrefix(newURL, "http://") && !strings.HasPrefix(newURL, "/") && !strings.HasPrefix(newURL, "data:") { + newURL = "//" + u.Host + path.Join("/", path.Dir(u.Path), newURL) + "?" + u.RawQuery + } + if val[2] == newURL { + continue + } + if val[1] == "url" { + d = strings.Replace(d, "url("+val[2]+")", "url("+newURL+")", -1) + } else if val[1] == "@import" { + d = strings.Replace(d, "@import("+val[2]+")", "@import("+newURL+")", -1) + } + } + // bundleCSS += d + s.ReplaceWithHtml("") } }) - bundleJS := "" + // bundleJS := "" doc.Find("script").Each(func(_ int, s *goquery.Selection) { dst := s.AttrOr("src", "") if dst == "" { @@ -108,19 +128,19 @@ func main() { if u.Host != w.Request.Host { return } - if js := fetch(dst); js != "" { - bundleJS += js - s.Remove() + if d := fetch(dst); d != "" { + // bundleJS += js + s.ReplaceWithHtml("") } }) - if bundleCSS != "" { - doc.Find("head").AppendHtml("") - } + // if bundleCSS != "" { + // doc.Find("head").AppendHtml("") + // } - if bundleJS != "" { - doc.Find("body").AppendHtml("") - } + // if bundleJS != "" { + // doc.Find("body").AppendHtml("") + // } html, _ := doc.Html() w.Body = ioutil.NopCloser(strings.NewReader(html))