From d3d7ce98d69e64921629b4e9d91585a5d7cf0db4 Mon Sep 17 00:00:00 2001 From: sam Date: Thu, 8 Feb 2024 00:41:17 +0100 Subject: [PATCH] init --- .gitignore | 3 + LICENSE | 201 +++++++++++++++++++++++++++++++++++++++ README.md | 24 +++++ cache/.gitkeep | 0 config.example.json | 13 +++ go.mod | 11 +++ go.sum | 48 ++++++++++ handler.go | 224 ++++++++++++++++++++++++++++++++++++++++++++ main.go | 74 +++++++++++++++ 9 files changed, 598 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 cache/.gitkeep create mode 100644 config.example.json create mode 100644 go.mod create mode 100644 go.sum create mode 100644 handler.go create mode 100644 main.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9d03041 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +config.json +cache/* +!cache/.gitkeep diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..40d6863 --- /dev/null +++ b/README.md @@ -0,0 +1,24 @@ +# image-proxy + +An image proxy server that resizes images before serving them. +Intended to only be used with images that already have a consistent size (such as already processed avatars). + +## Configuration + +Configuration is done in a `config.json` file, with the following keys: + +- `port`: the port the server will listen on +- `debug`: whether the server will log all request paths and durations +- `proxy_target`: the target for the reverse proxy, used when the requested size is the image's actual size. + Should be the full base URL of the target server, without a trailing slash. +- `patterns`: an array of patterns to accept + - `input`: (string) the input regex. This should start with a `/` and use unnamed capture groups. + - `output`: (string) the URL to rewrite the link to, using `$1` `$2` (etc) as placeholders for the capture groups. + - `cache_key`: (string) the file name used for cached files. Must be unique across all patterns. + - `content_type`: (string) the `Content-Type` header to return with requests. + - `sizes`: (array of numbers) the acceptable sizes for this pattern. + The first size in the list is the default, and will be passed through unmodified. + +## To-do list + +- Clean up old, unused cache entries diff --git a/cache/.gitkeep b/cache/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/config.example.json b/config.example.json new file mode 100644 index 0000000..8be5a49 --- /dev/null +++ b/config.example.json @@ -0,0 +1,13 @@ +{ + "port": 5170, + "debug": true, + "proxy_target": "https://cdn.pronouns.cc", + "patterns": [ + { + "input": "/users/([0-9a-v]{20})/([0-9a-f]+)\\.(webp|jpg)", + "output": "https://cdn.pronouns.cc/users/$1/$2.$3", + "cache_key": "user-$1-$2.$3", + "sizes": [512, 256] + } + ] +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a9114de --- /dev/null +++ b/go.mod @@ -0,0 +1,11 @@ +module codeberg.org/pronounscc/image-proxy + +go 1.20 + +require github.com/davidbyttow/govips/v2 v2.13.0 + +require ( + golang.org/x/image v0.5.0 // indirect + golang.org/x/net v0.7.0 // indirect + golang.org/x/text v0.7.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..dfaf13f --- /dev/null +++ b/go.sum @@ -0,0 +1,48 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davidbyttow/govips/v2 v2.13.0 h1:5MK9ZcXZC5GzUR9Ca8fJwOYqMgll/H096ec0PJP59QM= +github.com/davidbyttow/govips/v2 v2.13.0/go.mod h1:LPTrwWtNa5n4yl9UC52YBOEGdZcY5hDTP4Ms2QWasTw= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/image v0.5.0 h1:5JMiNunQeQw++mMOz48/ISeNu3Iweh/JaZU8ZLqHRrI= +golang.org/x/image v0.5.0/go.mod h1:FVC7BI/5Ym8R25iw5OLsgshdUBbT1h5jZTpA+mvAdZ4= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/handler.go b/handler.go new file mode 100644 index 0000000..9b9ae59 --- /dev/null +++ b/handler.go @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: Apache-2.0 +package main + +import ( + "context" + "errors" + "fmt" + "io" + "log" + "net/http" + "net/http/httputil" + "os" + "regexp" + "strconv" + "time" + + "github.com/davidbyttow/govips/v2/vips" +) + +type Handler struct { + // Port is the port to serve on. + Port int `json:"port"` + // Whether to log debug messages + Debug bool `json:"debug"` + // Patterns is an array of image URL patterns to serve. + Patterns []pattern `json:"patterns"` + // ProxyTarget is the host that requests for the default image size will be rewritten to. + ProxyTarget string `json:"proxy_target"` + proxy *httputil.ReverseProxy +} + +type pattern struct { + Input string `json:"input"` + Output string `json:"output"` + CacheKey string `json:"cache_key"` + ContentType string `json:"content_type"` + Sizes []int `json:"sizes"` + regexp *regexp.Regexp +} + +func (p *pattern) acceptsSize(size int) bool { + for i := range p.Sizes { + if p.Sizes[i] == size { + return true + } + } + return false +} + +// The proxy handler entrypoint. This handles rewriting the URL to the original image, and +func (hn *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + var pattern *pattern + for i := range hn.Patterns { + if hn.Patterns[i].regexp.MatchString(r.URL.Path) { + pattern = &hn.Patterns[i] + break + } + } + + if pattern == nil { + http.Error(w, "Invalid image URL", http.StatusBadRequest) + return + } + + var size int + if s := r.FormValue("size"); s != "" { + i, err := strconv.Atoi(s) + if err != nil { + http.Error(w, "Invalid image size", http.StatusBadRequest) + return + } + size = i + } else { + size = pattern.Sizes[0] + } + + if !pattern.acceptsSize(size) { + http.Error(w, "Invalid image size", http.StatusBadRequest) + return + } + + // If the requested size is the default, just proxy the request + if size == pattern.Sizes[0] { + if hn.Debug { + log.Printf("[DEBUG] Proxying image %q as it has default size of %v", r.URL.Path, size) + } + hn.proxy.ServeHTTP(w, r) + return + } + + url := pattern.regexp.ReplaceAllString(r.URL.Path, pattern.Output) + cacheKey := pattern.regexp.ReplaceAllString(r.URL.Path, pattern.CacheKey) + + if hn.Debug { + log.Printf("[DEBUG] Resizing image %q to size %v and serving it", r.URL.Path, size) + } + + hn.proxyImage(r.Context(), w, cacheKey, url, pattern.ContentType, size) +} + +func (hn *Handler) proxyImage(ctx context.Context, w http.ResponseWriter, cacheKey, url, contentType string, size int) { + // Check if we've cached the image + cacheName := fmt.Sprintf("cache/%v/%v", size, cacheKey) + cacheFile, err := os.Open(cacheName) + if err == nil { + defer func() { + err := cacheFile.Close() + if err != nil { + log.Printf("error closing file %q: %v", cacheName, err) + } + }() + + fi, err := cacheFile.Stat() + if err != nil { + log.Printf("error getting file info for file %q: %v", cacheName, err) + return + } + + // If so, just copy it to the output + w.Header().Add("Content-Type", contentType) + w.Header().Add("Content-Length", strconv.FormatInt(fi.Size(), 10)) + _, err = io.Copy(w, cacheFile) + if err != nil { + log.Printf("error serving cached file %q: %v", cacheName, err) + } + return + } else { + if !errors.Is(err, os.ErrNotExist) { + log.Printf("error opening cache file %q: %v", cacheName, err) + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + } + + // Otherwise, fall back to fetching the image + resizing it + start := time.Now() + + req, err := http.NewRequestWithContext(ctx, "GET", url, nil) + if err != nil { + log.Printf("creating request: %v", err) + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + log.Printf("executing request: %v", err) + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + switch resp.StatusCode { + case http.StatusOK: + case http.StatusNotFound: + http.Error(w, "Not found", http.StatusNotFound) + return + default: + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + defer resp.Body.Close() + + image, err := vips.NewImageFromReader(resp.Body) + if err != nil { + log.Printf("creating vips image: %v", err) + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + + err = image.ThumbnailWithSize(size, size, vips.InterestingCentre, vips.SizeBoth) + if err != nil { + log.Printf("resizing vips image: %v", err) + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + + out, _, err := export(image, contentType) + if err != nil { + log.Printf("exporting vips image: %v", err) + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + + if hn.Debug { + log.Printf("resized image %q in %v", cacheKey, time.Since(start).Round(time.Microsecond)) + } + + go func(b []byte) { + err = os.WriteFile(cacheName, b, 0o644) + if err != nil { + log.Printf("writing image to cache: %v", err) + return + } + }(out) + + w.Header().Add("Content-Type", contentType) + w.Header().Add("Content-Length", strconv.Itoa(len(out))) + _, err = w.Write(out) + if err != nil { + log.Printf("error writing resized file to response: %v", err) + } +} + +func export(image *vips.ImageRef, contentType string) ([]byte, *vips.ImageMetadata, error) { + switch contentType { + case "image/webp": + params := vips.NewWebpExportParams() + params.Quality = 90 + return image.ExportWebp(params) + case "image/jpeg": + params := vips.NewJpegExportParams() + params.Quality = 90 + return image.ExportJpeg(params) + case "image/png": + params := vips.NewPngExportParams() + params.Quality = 90 + return image.ExportPng(params) + case "image/gif": + params := vips.NewGifExportParams() + params.Quality = 90 + return image.ExportGIF(params) + } + + return nil, nil, errors.New("invalid image content type") +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..d2361b8 --- /dev/null +++ b/main.go @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: Apache-2.0 +package main + +import ( + "encoding/json" + "errors" + "log" + "net/http" + "net/http/httputil" + "net/url" + "os" + "regexp" + "strconv" + + "github.com/davidbyttow/govips/v2/vips" +) + +func main() { + // set vips log level to WARN, else it will spam logs on info level + vips.LoggingSettings(nil, vips.LogLevelWarning) + + vips.Startup(nil) + defer vips.Shutdown() + + // read config file and parse it + confB, err := os.ReadFile("config.json") + if err != nil { + log.Fatalf("reading config.json: %v", err) + } + + hn := &Handler{} + err = json.Unmarshal(confB, hn) + if err != nil { + log.Fatalf("unmarshaling config.json: %v", err) + } + + // Construct reverse proxy for bare/default size images + proxyURL, err := url.Parse(hn.ProxyTarget) + if err != nil { + log.Fatalf("parsing proxy_target as URL: %v", err) + } + hn.proxy = &httputil.ReverseProxy{ + Rewrite: func(pr *httputil.ProxyRequest) { + pr.SetURL(proxyURL) + pr.Out.URL.RawQuery = "" + }, + } + + // compile patterns + for i, pattern := range hn.Patterns { + if len(pattern.Sizes) <= 1 { + log.Fatalf("pattern %d (%q) has too few possible sizes", i+1, pattern.Input) + } + + hn.Patterns[i].regexp = regexp.MustCompile(pattern.Input) + } + + // create directories for all image sizes + for _, pattern := range hn.Patterns { + for _, size := range pattern.Sizes { + err := os.Mkdir("cache/"+strconv.Itoa(size), 0o755) + if err != nil && !errors.Is(err, os.ErrExist) { + log.Fatalf("creating cache directory %q: %v", "cache/"+strconv.Itoa(size), err) + } + } + } + + log.Printf("serving on port %v", hn.Port) + + err = http.ListenAndServe(":"+strconv.Itoa(hn.Port), hn) + if err != nil { + log.Fatalf("listening on port %v: %v", hn.Port, err) + } +}