├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE.md ├── README.md └── main.go /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at m7medalash3al@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please first discuss the change you wish to make via issue, 4 | email, or any other method with the owners of this repository before making a change. 5 | 6 | Please note we have a code of conduct, please follow it in all your interactions with the project. 7 | 8 | ## Pull Request Process 9 | 10 | 1. Ensure any install or build dependencies are removed before the end of the layer when doing a 11 | build. 12 | 2. Update the README.md with details of changes to the interface, this includes new environment 13 | variables, exposed ports, useful file locations and container parameters. 14 | 3. Increase the version numbers in any examples files and the README.md to the new version that this 15 | Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/). 16 | 4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you 17 | do not have permission to do that, you may request the second reviewer to merge it for you. 18 | 19 | ## Code of Conduct 20 | 21 | ### Our Pledge 22 | 23 | In the interest of fostering an open and welcoming environment, we as 24 | contributors and maintainers pledge to making participation in our project and 25 | our community a harassment-free experience for everyone, regardless of age, body 26 | size, disability, ethnicity, gender identity and expression, level of experience, 27 | nationality, personal appearance, race, religion, or sexual identity and 28 | orientation. 29 | 30 | ### Our Standards 31 | 32 | Examples of behavior that contributes to creating a positive environment 33 | include: 34 | 35 | * Using welcoming and inclusive language 36 | * Being respectful of differing viewpoints and experiences 37 | * Gracefully accepting constructive criticism 38 | * Focusing on what is best for the community 39 | * Showing empathy towards other community members 40 | 41 | Examples of unacceptable behavior by participants include: 42 | 43 | * The use of sexualized language or imagery and unwelcome sexual attention or 44 | advances 45 | * Trolling, insulting/derogatory comments, and personal or political attacks 46 | * Public or private harassment 47 | * Publishing others' private information, such as a physical or electronic 48 | address, without explicit permission 49 | * Other conduct which could reasonably be considered inappropriate in a 50 | professional setting 51 | 52 | ### Our Responsibilities 53 | 54 | Project maintainers are responsible for clarifying the standards of acceptable 55 | behavior and are expected to take appropriate and fair corrective action in 56 | response to any instances of unacceptable behavior. 57 | 58 | Project maintainers have the right and responsibility to remove, edit, or 59 | reject comments, commits, code, wiki edits, issues, and other contributions 60 | that are not aligned to this Code of Conduct, or to ban temporarily or 61 | permanently any contributor for other behaviors that they deem inappropriate, 62 | threatening, offensive, or harmful. 63 | 64 | ### Scope 65 | 66 | This Code of Conduct applies both within project spaces and in public spaces 67 | when an individual is representing the project or its community. Examples of 68 | representing a project or community include using an official project e-mail 69 | address, posting via an official social media account, or acting as an appointed 70 | representative at an online or offline event. Representation of a project may be 71 | further defined and clarified by project maintainers. 72 | 73 | ### Enforcement 74 | 75 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 76 | reported by contacting the project team at [INSERT EMAIL ADDRESS]. All 77 | complaints will be reviewed and investigated and will result in a response that 78 | is deemed necessary and appropriate to the circumstances. The project team is 79 | obligated to maintain confidentiality with regard to the reporter of an incident. 80 | Further details of specific enforcement policies may be posted separately. 81 | 82 | Project maintainers who do not follow or enforce the Code of Conduct in good 83 | faith may face temporary or permanent repercussions as determined by other 84 | members of the project's leadership. 85 | 86 | ### Attribution 87 | 88 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 89 | available at [http://contributor-covenant.org/version/1/4][version] 90 | 91 | [homepage]: http://contributor-covenant.org 92 | [version]: http://contributor-covenant.org/version/1/4/ 93 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:alpine 2 | 3 | RUN apk update && apk add git 4 | 5 | RUN go get github.com/alash3al/lightify 6 | 7 | ENTRYPOINT ["lightify"] 8 | 9 | WORKDIR /root/ -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright 2018 Lightify 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Lightify 2 | ========= 3 | > Let's minify, compress & combine static files on the fly. 4 | 5 | ![](http://preview.ibb.co/nkCgpy/36283128_1069026009937885_5431723196539731968_o_1.jpg) 6 | 7 | Features 8 | ========== 9 | - Simple & Stupid. 10 | - Minify `css, js, html, xml, json`. 11 | - Gzip each minified file. 12 | - Combine and inline self-hosted `css, js` on the fly! 13 | - Automatically fixes internal relative css imports! 14 | - Supports any http upstream. 15 | - Portable, no dependancies. 16 | 17 | Download 18 | ======== 19 | - Docker `$ docker pull alash3al/lightify` 20 | - Binaries go to [releases page](https://github.com/alash3al/lightify/releases) 21 | - From Source `go get github.com/alash3al/lightify` 22 | 23 | Usage 24 | ====== 25 | - Docker `$ docker run --network=host alash3al/lightify --upstream="http://localhost:8080"` 26 | - Binaries `./lightify -http :80 -upstream http://localhost:8080` 27 | - From Source `lightify -http :80 -upstream http://localhost:8080` 28 | 29 | Help 30 | ==== 31 | - Docker `$ docker run alash3al/lightify --help` 32 | - Binaries `./lightify --help` 33 | - From Source `lightify --help` 34 | 35 | Credits 36 | ======== 37 | Mohamed Al Ashaal, a Gopher ;) 38 | 39 | License 40 | ======== 41 | MIT License 42 | 43 | Contribution 44 | ============= 45 | The door is always open ;) -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "compress/gzip" 6 | "flag" 7 | "io" 8 | "io/ioutil" 9 | "log" 10 | "net/http" 11 | "net/url" 12 | "os" 13 | "path" 14 | "regexp" 15 | "strings" 16 | 17 | "github.com/PuerkitoBio/goquery" 18 | "github.com/gorilla/handlers" 19 | "github.com/tdewolff/minify" 20 | "github.com/tdewolff/minify/css" 21 | "github.com/tdewolff/minify/html" 22 | "github.com/tdewolff/minify/js" 23 | "github.com/tdewolff/minify/json" 24 | "github.com/tdewolff/minify/svg" 25 | "github.com/tdewolff/minify/xml" 26 | "github.com/vulcand/oxy/forward" 27 | ) 28 | 29 | var ( 30 | flagUpstream = flag.String("upstream", "http://localhost:8080", "the upstream server to fallback") 31 | flagHTTPAddr = flag.String("http", ":80", "the http port to listen on") 32 | flagMinify = flag.String("minify", "js,css,json,xml,html,svg", "the types to be minified, empty means none") 33 | flagCombine = flag.Bool("combine", true, "combine the assets files on the fly") 34 | flagGZIP = flag.Bool("gzip", true, "compress the output") 35 | flagLog = flag.Bool("log", true, "enable logging") 36 | ) 37 | 38 | func main() { 39 | flag.Parse() 40 | 41 | minifiable := strings.Split(*flagMinify, ",") 42 | m := minify.New() 43 | 44 | if inArray(minifiable, "css") { 45 | m.AddFunc("text/css", css.Minify) 46 | } 47 | 48 | if inArray(minifiable, "html") { 49 | m.Add("text/html", &html.Minifier{ 50 | KeepConditionalComments: true, 51 | KeepEndTags: true, 52 | KeepDocumentTags: true, 53 | KeepDefaultAttrVals: true, 54 | }) 55 | } 56 | 57 | if inArray(minifiable, "js") { 58 | m.AddFuncRegexp(regexp.MustCompile("^(application|text)/(x-)?(java|ecma)script$"), js.Minify) 59 | } 60 | 61 | if inArray(minifiable, "svg") { 62 | m.AddFunc("image/svg+xml", svg.Minify) 63 | } 64 | 65 | if inArray(minifiable, "xml") { 66 | m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify) 67 | } 68 | 69 | if inArray(minifiable, "json") { 70 | m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify) 71 | } 72 | 73 | cssURLs := regexp.MustCompile(`(url|\@import)\((.*?)\)`) 74 | forwarder := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { 75 | var err error 76 | 77 | req.URL, err = url.Parse(*flagUpstream) 78 | if err != nil { 79 | http.Error(w, "Internal Server Error", 500) 80 | return 81 | } 82 | 83 | fwd, err := forward.New(forward.PassHostHeader(true), forward.ResponseModifier(func(w *http.Response) (err error) { 84 | w.Header.Del("Server") 85 | w.Header.Del("X-Powered-By") 86 | // w.Header.Del("Content-Length") 87 | 88 | if strings.ToLower(w.Header.Get("Content-Encoding")) == "gzip" { 89 | w.Body, err = gzip.NewReader(w.Body) 90 | if err != nil { 91 | return nil 92 | } 93 | w.Header.Del("Content-Encoding") 94 | } 95 | 96 | chunk := make([]byte, 512) 97 | w.Body.Read(chunk) 98 | 99 | w.Body = ioutil.NopCloser(io.MultiReader(bytes.NewBuffer(chunk), w.Body)) 100 | 101 | if !strings.Contains(strings.ToLower(http.DetectContentType(chunk)), "text/html") { 102 | return nil 103 | } 104 | 105 | doc, err := goquery.NewDocumentFromReader(w.Body) 106 | if err != nil { 107 | return nil 108 | } 109 | 110 | if *flagCombine { 111 | // bundle css 112 | doc.Find("link").Each(func(_ int, s *goquery.Selection) { 113 | dst := s.AttrOr("href", "") 114 | if dst == "" { 115 | return 116 | } 117 | if s.AttrOr("rel", "") != "stylesheet" { 118 | return 119 | } 120 | dst = fixURL(dst, w.Request.Host) 121 | u, err := url.Parse(dst) 122 | if err != nil { 123 | return 124 | } 125 | if d := fetch(dst); d != "" { 126 | for _, val := range cssURLs.FindAllStringSubmatch(d, -1) { 127 | newURL := strings.Trim(val[2], `"'`) 128 | if !strings.HasPrefix(newURL, "//") && !strings.HasPrefix(newURL, "http://") && !strings.HasPrefix(newURL, "http://") && !strings.HasPrefix(newURL, "/") && !strings.HasPrefix(newURL, "data:") { 129 | newURL = "//" + u.Host + path.Join("/", path.Dir(u.Path), newURL) + "?" + u.RawQuery 130 | } 131 | if val[2] == newURL { 132 | continue 133 | } 134 | if val[1] == "url" { 135 | d = strings.Replace(d, "url("+val[2]+")", "url("+newURL+")", -1) 136 | } else if val[1] == "@import" { 137 | d = strings.Replace(d, "@import("+val[2]+")", "@import("+newURL+")", -1) 138 | } 139 | } 140 | s.ReplaceWithHtml("") 141 | } 142 | }) 143 | 144 | // bundleJS 145 | doc.Find("script").Each(func(_ int, s *goquery.Selection) { 146 | dst := s.AttrOr("src", "") 147 | if dst == "" { 148 | return 149 | } 150 | // s.SetAttr("async", "true") 151 | dst = fixURL(dst, w.Request.Host) 152 | if d := fetch(dst); d != "" { 153 | s.RemoveAttr("src") 154 | s.SetText(d) 155 | } 156 | }) 157 | } 158 | 159 | html, _ := doc.Html() 160 | w.Body = ioutil.NopCloser(strings.NewReader(html)) 161 | 162 | return nil 163 | })) 164 | 165 | if err != nil { 166 | http.Error(w, "Internal Server Error", 500) 167 | return 168 | } 169 | 170 | fwd.ServeHTTP(w, req) 171 | }) 172 | 173 | var container http.Handler = forwarder 174 | 175 | if *flagMinify != "" { 176 | container = m.Middleware(container) 177 | } 178 | 179 | if *flagGZIP { 180 | container = handlers.CompressHandlerLevel(container, 9) 181 | } 182 | 183 | if *flagLog { 184 | container = handlers.CombinedLoggingHandler(os.Stdout, container) 185 | } 186 | 187 | log.Println("> starting server on `" + (*flagHTTPAddr) + "`") 188 | log.Fatal(http.ListenAndServe(*flagHTTPAddr, container)) 189 | } 190 | 191 | func fetch(dst string) string { 192 | resp, err := http.Get(dst) 193 | if err != nil { 194 | return "" 195 | } 196 | defer resp.Body.Close() 197 | d, err := ioutil.ReadAll(resp.Body) 198 | if err != nil { 199 | return "" 200 | } 201 | return string(d) 202 | } 203 | 204 | func fixURL(dst, host string) string { 205 | if !strings.HasPrefix(dst, "//") && !strings.HasPrefix(dst, "http://") && !strings.HasPrefix(dst, "https://") { 206 | dst = "//" + host + "/" + strings.TrimLeft(dst, "/") 207 | } 208 | return dst 209 | } 210 | 211 | func inArray(a []string, s string) bool { 212 | for _, v := range a { 213 | if s == v { 214 | return true 215 | } 216 | } 217 | return false 218 | } 219 | --------------------------------------------------------------------------------