压缩html
(doc *goquery.Document)
| 116 | |
| 117 | //压缩html |
| 118 | func compress(doc *goquery.Document) (*goquery.Document, map[string]string) { |
| 119 | //blockquote、pre、code,并替换 span 为空 |
| 120 | |
| 121 | var maps = make(map[string]string) |
| 122 | |
| 123 | if ele := doc.Find("textarea"); len(ele.Nodes) > 0 { |
| 124 | ele.Each(func(i int, selection *goquery.Selection) { |
| 125 | key := fmt.Sprintf("{$textarea%v}", i) |
| 126 | cont := "<textarea>" + getInnerHtml(selection) + "</textarea>" |
| 127 | selection.BeforeHtml(key) |
| 128 | selection.Remove() |
| 129 | maps[key] = cont |
| 130 | }) |
| 131 | } |
| 132 | |
| 133 | if ele := doc.Find("code"); len(ele.Nodes) > 0 { |
| 134 | ele.Each(func(i int, selection *goquery.Selection) { |
| 135 | key := fmt.Sprintf("{$code%v}", i) |
| 136 | cont := "<code>" + getInnerHtml(selection) + "</code>" |
| 137 | selection.BeforeHtml(key) |
| 138 | selection.Remove() |
| 139 | maps[key] = cont |
| 140 | }) |
| 141 | } |
| 142 | |
| 143 | if ele := doc.Find("pre"); len(ele.Nodes) > 0 { |
| 144 | ele.Each(func(i int, selection *goquery.Selection) { |
| 145 | key := fmt.Sprintf("{$pre%v}", i) |
| 146 | cont := "<pre>" + getInnerHtml(selection) + "</pre>" |
| 147 | selection.BeforeHtml(key) |
| 148 | selection.Remove() |
| 149 | maps[key] = cont |
| 150 | }) |
| 151 | } |
| 152 | |
| 153 | if ele := doc.Find("blockquote"); len(ele.Nodes) > 0 { |
| 154 | ele.Each(func(i int, selection *goquery.Selection) { |
| 155 | key := fmt.Sprintf("{$blockquote%v}", i) |
| 156 | cont := "<blockquote>" + getInnerHtml(selection) + "</blockquote>" |
| 157 | selection.BeforeHtml(key) |
| 158 | selection.Remove() |
| 159 | maps[key] = cont |
| 160 | }) |
| 161 | } |
| 162 | |
| 163 | replaces := map[string]string{ |
| 164 | "\n": " ", "\r": " ", "\t": " ", "<dl": "<ul", |
| 165 | "</dl": "</ul", "<dt": "<li", "</dt": "</li", |
| 166 | "<dd": "<li", "</dd": "</li", |
| 167 | } |
| 168 | |
| 169 | htmlstr, _ := doc.Html() |
| 170 | for old, new := range replaces { |
| 171 | htmlstr = strings.Replace(htmlstr, old, new, -1) |
| 172 | } |
| 173 | |
| 174 | //正则匹配,把“>”和“<”直接的空格全部去掉 |
| 175 | //去除标签之间的空格,如果是存在代码预览的页面,不要替换空格,否则预览的代码会错乱 |
no test coverage detected