├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── cache.go ├── config.go ├── go.mod ├── go.sum ├── main.go ├── stream ├── buffer.go ├── file.go ├── stream.go └── stream_test.go └── tiny.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | tiny-http-proxy 7 | main 8 | 9 | # Test binary, build with `go test -c` 10 | *.test 11 | 12 | # Output of the go coverage tool, specifically when used with LiteIDE 13 | *.out 14 | 15 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 16 | .glide/ 17 | 18 | # IDE stuff 19 | .idea 20 | 21 | # Cache folder 22 | cache -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | #!make 2 | 3 | upx := $(shell which upx) 4 | outName = "tiny-http-proxy" 5 | 6 | run: 7 | go run . 8 | 9 | build: 10 | go build -ldflags "-w -s" -o ${outName} . 11 | ifdef upx 12 | upx ${outName} 13 | endif 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tiny-http-proxy 2 | Maybe the tiniest HTTP proxy that also has a cache. 3 | 4 | The tiny-http-proxy acts as a reverse proxy for one server of your choice illustrated by this picture: 5 | 6 | ``` 7 | network proxy cache 8 | .—————————. .—————————. .—————————. 9 | <————|— — < — —|———<———|— — < — —|———<———|— < —.—. | 10 | you ————>|— — > — —|———>———|— —.— > —|———>———|— > —' | | 11 | | | | |(*) | | | | 12 | | ,—< —|———<———|< —' | | | | 13 | | | ,—>|———>———|— — > — —|———>———|— > ———' | 14 | `————+—+——´ `—————————´ `—————————´ 15 | | | 16 | '—' 17 | website 18 | 19 | (*) When the data is not in the cache, 20 | the website will be requested and is directly stored 21 | in the cache. 22 | ``` 23 | Where "network" may be anything (LAN/WAN/...). 24 | 25 | # Installation 26 | Just clone this repo and run it: 27 | 28 | ``` 29 | git clone https://github.com/hauke96/tiny-http-proxy.git 30 | cd tiny-http-proxy 31 | mkdir cache 32 | go run *.go 33 | ``` 34 | Alternative to the `go run` command you can also use `make run` as well as `make build` which uses additional build parameters for e.g. a smaller artifact size. 35 | 36 | Of course, you can also use the [ZIP-archive](https://github.com/hauke96/tiny-http-proxy/archive/master.zip) if you don't have git installed. 37 | 38 | Instead of `mkdir cache`, you have to make sure that the folder you'll configure later exists. 39 | 40 | # CLI arguments 41 | 42 | | Parameter | Description | 43 | |:---|:---| 44 | | `--help`, `-h` | Show this list of available parameters | 45 | | `-config my-config.json` | Uses the file `my-config.json` as configuration file. Default value is `./tiny.json`. 46 | 47 | # Configuration file 48 | All the configuration is done in the `tiny.json` file. This is a simple JSON-file with some properties that should be set by you: 49 | 50 | | Property | Type | Description | 51 | |:---|:---|:---| 52 | | `port` | `string` | The port this server is listening to. | 53 | | `target` | `string` | The target host every request should be routed to. | 54 | | `cache_folder` | `string` | The folder where the cache files are stored. This folder must exist and must be writable. | 55 | | `debug_logging` | `bool` | When set to true, more detailed log output is printed. | 56 | | `max_cache_item_size` | `int` | Maximum size in MB for the in-memory cache. Larger files are only cached on disk, smaller files are also cached directly within the memory. | 57 | 58 | # Usage 59 | If you normally go to `http://foo.com/bar?request=test` then now go to `http://localhost:8080/bar?request=test` (assumed there's a correct configuration). 60 | 61 | # Examples 62 | ## With the given config 63 | The current configuration caches requests to `https://imgs.xkcd.com`. So just start the proxy and go to e.g.: 64 | 65 | [http://localhost:8080/comics/campaign_fundraising_emails.png](http://localhost:8080/comics/campaign_fundraising_emails.png) 66 | 67 | ## Caching google searches 68 | Example: Create a proxy for google: 69 | 70 | ```json 71 | { 72 | "port": "8080", 73 | "target": "http://www.google.com/", 74 | "cache_folder": "./cache/" 75 | } 76 | ``` 77 | Then using the proxy with the URL `http://localhost:8080/search?source=hp&ei=QmBwWtTMHojOwAK2146oDQ&btnG=Suche&q=go+(language)` will open the result page of a google search for "go (language)". You may notice, that the site looks different then the original one. This happens because the proxy does not change links in the HTML (e.g. to `css` files). 78 | 79 | The cache folder now contains files that are requested when opening the site (the HTML page, the favicon or other images): 80 | ``` 81 | 5,4K 5b99ab35db77d3f6b8fada5270bc47b924ee8cca8b446d5d17cb6eed57bd372f 82 | 5,4K 802264eb0ff19278f578bfe80df00b9ed3b9ee67f670c2d6cea2d330cb7a49eb 83 | 152K 8988bca2a82bd9d3d52f03e0ecc7068db934d627f3a369f736e769360c968d93 84 | 0 aaa75631890ab943c5ac2033591cb4287d1a6085604a74dc854a6117e6a0e104 85 | 51K b9a229ca754de56be3c2743e5a51deac09e170c05388cc2c14b2e70608d9d4e4 86 | 12K e5c601f8012efac42f37f43427272d2e9ec9756b2d401fab2a495dd3b96266bc 87 | ``` 88 | A great thing: Accessing another google search site, some images are not downloaded twice. Long live the cache! 89 | -------------------------------------------------------------------------------- /cache.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "crypto/sha256" 7 | "encoding/hex" 8 | "fmt" 9 | "hash" 10 | "io" 11 | "io/ioutil" 12 | "os" 13 | "sync" 14 | 15 | "github.com/hauke96/sigolo" 16 | ) 17 | 18 | type Cache struct { 19 | folder string 20 | hash hash.Hash 21 | knownValues map[string][]byte 22 | busyValues map[string]*sync.Mutex 23 | mutex *sync.Mutex 24 | } 25 | 26 | func CreateCache(path string) (*Cache, error) { 27 | fileInfos, err := ioutil.ReadDir(path) 28 | if err != nil { 29 | sigolo.Error("Cannot open cache folder '%s': %s", path, err) 30 | sigolo.Info("Create cache folder '%s'", path) 31 | os.Mkdir(path, os.ModePerm) 32 | } 33 | 34 | values := make(map[string][]byte, 0) 35 | busy := make(map[string]*sync.Mutex, 0) 36 | 37 | // Go through every file an save its name in the map. The content of the file 38 | // is loaded when needed. This makes sure that we don't have to read 39 | // the directory content each time the user wants data that's not yet loaded. 40 | for _, info := range fileInfos { 41 | if !info.IsDir() { 42 | values[info.Name()] = nil 43 | } 44 | } 45 | 46 | hash := sha256.New() 47 | 48 | mutex := &sync.Mutex{} 49 | 50 | cache := &Cache{ 51 | folder: path, 52 | hash: hash, 53 | knownValues: values, 54 | busyValues: busy, 55 | mutex: mutex, 56 | } 57 | 58 | return cache, nil 59 | } 60 | 61 | // Returns true if the resource is found, and false otherwise. If the 62 | // resource is busy, this method will hang until the resource is free. If 63 | // the resource is not found, a lock indicating that the resource is busy will 64 | // be returned. Once the resource has been put into cache the busy lock *must* 65 | // be unlocked to allow others to access the newly cached resource 66 | func (c *Cache) has(key string) (*sync.Mutex, bool) { 67 | hashValue := calcHash(key) 68 | 69 | c.mutex.Lock() 70 | defer c.mutex.Unlock() 71 | 72 | // If the resource is busy, wait for it to be free. This is the case if 73 | // the resource is currently being cached as a result of another request. 74 | // Also, release the lock on the cache to allow other readers while waiting 75 | if lock, busy := c.busyValues[hashValue]; busy { 76 | c.mutex.Unlock() 77 | lock.Lock() 78 | lock.Unlock() 79 | c.mutex.Lock() 80 | } 81 | 82 | // If a resource is in the shared cache, it can't be reserved. One can simply 83 | // access it directly from the cache 84 | if _, found := c.knownValues[hashValue]; found { 85 | return nil, true 86 | } 87 | 88 | // The resource is not in the cache, mark the resource as busy until it has 89 | // been cached successfully. Unlocking lock is required! 90 | lock := new(sync.Mutex) 91 | lock.Lock() 92 | c.busyValues[hashValue] = lock 93 | return lock, false 94 | } 95 | 96 | func (c *Cache) get(key string) (*io.Reader, error) { 97 | var response io.Reader 98 | hashValue := calcHash(key) 99 | 100 | // Try to get content. Error if not found. 101 | c.mutex.Lock() 102 | content, ok := c.knownValues[hashValue] 103 | c.mutex.Unlock() 104 | if !ok && len(content) > 0 { 105 | sigolo.Debug("Cache doesn't know key '%s'", hashValue) 106 | return nil, fmt.Errorf("Key '%s' is not known to cache", hashValue) 107 | } 108 | 109 | sigolo.Debug("Cache has key '%s'", hashValue) 110 | 111 | // Key is known, but not loaded into RAM 112 | if content == nil { 113 | sigolo.Debug("Cache item '%s' known but is not stored in memory. Using file.", hashValue) 114 | 115 | file, err := os.Open(c.folder + hashValue) 116 | if err != nil { 117 | sigolo.Error("Error reading cached file '%s': %s", hashValue, err) 118 | return nil, err 119 | } 120 | 121 | response = file 122 | 123 | sigolo.Debug("Create reader from file %s", hashValue) 124 | } else { // Key is known and data is already loaded to RAM 125 | response = bytes.NewReader(content) 126 | sigolo.Debug("Create reader from %d byte large cache content", len(content)) 127 | } 128 | 129 | return &response, nil 130 | } 131 | 132 | // release is an internal method which atomically caches an item and unmarks 133 | // the item as busy, if it was busy before. The busy lock *must* be unlocked 134 | // elsewhere! 135 | func (c *Cache) release(hashValue string, content []byte) { 136 | c.mutex.Lock() 137 | delete(c.busyValues, hashValue) 138 | c.knownValues[hashValue] = content 139 | c.mutex.Unlock() 140 | } 141 | 142 | func (c *Cache) put(key string, content *io.Reader, contentLength int64) error { 143 | hashValue := calcHash(key) 144 | 145 | // Small enough to put it into the in-memory cache 146 | if contentLength <= config.MaxCacheItemSize*1024*1024 { 147 | buffer := &bytes.Buffer{} 148 | _, err := io.Copy(buffer, *content) 149 | if err != nil { 150 | return err 151 | } 152 | 153 | defer c.release(hashValue, buffer.Bytes()) 154 | sigolo.Debug("Added %s into in-memory cache", hashValue) 155 | 156 | err = ioutil.WriteFile(c.folder+hashValue, buffer.Bytes(), 0644) 157 | if err != nil { 158 | return err 159 | } 160 | sigolo.Debug("Wrote content of entry %s into file", hashValue) 161 | } else { // Too large for in-memory cache, just write to file 162 | defer c.release(hashValue, nil) 163 | sigolo.Debug("Added nil-entry for %s into in-memory cache", hashValue) 164 | 165 | file, err := os.Create(c.folder + hashValue) 166 | if err != nil { 167 | return err 168 | } 169 | 170 | writer := bufio.NewWriter(file) 171 | _, err = io.Copy(writer, *content) 172 | if err != nil { 173 | return err 174 | } 175 | sigolo.Debug("Wrote content of entry %s into file", hashValue) 176 | } 177 | 178 | sigolo.Debug("Cache wrote content into '%s'", hashValue) 179 | 180 | return nil 181 | } 182 | 183 | func calcHash(data string) string { 184 | sha := sha256.Sum256([]byte(data)) 185 | return hex.EncodeToString(sha[:]) 186 | } 187 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | ) 7 | 8 | type Config struct { 9 | Target string `json:"target"` 10 | CacheFolder string `json:"cache_folder"` 11 | Port string `json:"port"` 12 | DebugLogging bool `json:"debug_logging"` 13 | MaxCacheItemSize int64 `json:"max_cache_item_size"` // in MB 14 | } 15 | 16 | func LoadConfig(path string) (*Config, error) { 17 | file, err := ioutil.ReadFile(path) 18 | 19 | if err != nil { 20 | return nil, err 21 | } 22 | 23 | var config Config 24 | json.Unmarshal(file, &config) 25 | 26 | return &config, nil 27 | } 28 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/hauke96/tiny-http-proxy 2 | 3 | go 1.17 4 | 5 | require ( 6 | github.com/hauke96/sigolo v0.0.0-20200831155049-d5b5ab2a608f 7 | github.com/stretchr/testify v1.7.0 8 | ) 9 | 10 | require ( 11 | github.com/davecgh/go-spew v1.1.0 // indirect 12 | github.com/pmezard/go-difflib v1.0.0 // indirect 13 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect 14 | ) 15 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/hauke96/sigolo v0.0.0-20200831155049-d5b5ab2a608f h1:xG+4rtMXl2W7NemjthCbXW1wKUjgNurhlfK0qXqvPXo= 4 | github.com/hauke96/sigolo v0.0.0-20200831155049-d5b5ab2a608f/go.mod h1:F5f3UXFxSHe2BUizY8IvIYhjiPMy6FmJQvBMI83aeQs= 5 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 6 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 7 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 8 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= 9 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 10 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 11 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 12 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 13 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 14 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "io" 7 | "net/http" 8 | "time" 9 | 10 | "github.com/hauke96/sigolo" 11 | ) 12 | 13 | var config *Config 14 | var cache *Cache 15 | 16 | var client *http.Client 17 | 18 | func main() { 19 | configPath := flag.String("config", "./tiny.json", "configuration .json file path") 20 | flag.Parse() 21 | 22 | loadConfig(*configPath) 23 | if config.DebugLogging { 24 | sigolo.LogLevel = sigolo.LOG_DEBUG 25 | } 26 | sigolo.Debug("Config loaded") 27 | 28 | prepare() 29 | sigolo.Debug("Cache initialized") 30 | 31 | server := &http.Server{ 32 | Addr: ":" + config.Port, 33 | WriteTimeout: 30 * time.Second, 34 | ReadTimeout: 30 * time.Second, 35 | Handler: http.HandlerFunc(handleGet), 36 | } 37 | 38 | sigolo.Info("Start serving...") 39 | err := server.ListenAndServe() 40 | if err != nil { 41 | sigolo.Fatal(err.Error()) 42 | } 43 | } 44 | 45 | func loadConfig(configPath string) { 46 | var err error 47 | 48 | config, err = LoadConfig(configPath) 49 | if err != nil { 50 | sigolo.Fatal("Could not read config: '%s'", err.Error()) 51 | } 52 | } 53 | 54 | func prepare() { 55 | var err error 56 | 57 | cache, err = CreateCache(config.CacheFolder) 58 | 59 | if err != nil { 60 | sigolo.Fatal("Could not init cache: '%s'", err.Error()) 61 | } 62 | 63 | client = &http.Client{ 64 | Timeout: time.Second * 30, 65 | } 66 | } 67 | 68 | func handleGet(w http.ResponseWriter, r *http.Request) { 69 | fullUrl := r.URL.Path + "?" + r.URL.RawQuery 70 | 71 | sigolo.Info("Requested '%s'", fullUrl) 72 | 73 | // Cache miss -> Load data from requested URL and add to cache 74 | if busy, ok := cache.has(fullUrl); !ok { 75 | defer busy.Unlock() 76 | response, err := client.Get(config.Target + fullUrl) 77 | if err != nil { 78 | handleError(err, w) 79 | return 80 | } 81 | 82 | var reader io.Reader 83 | reader = response.Body 84 | 85 | err = cache.put(fullUrl, &reader, response.ContentLength) 86 | if err != nil { 87 | handleError(err, w) 88 | return 89 | } 90 | defer response.Body.Close() 91 | } 92 | 93 | // The cache has definitely the data we want, so get a reader for that 94 | content, err := cache.get(fullUrl) 95 | 96 | if err != nil { 97 | handleError(err, w) 98 | } else { 99 | bytesWritten, err := io.Copy(w, *content) 100 | if err != nil { 101 | sigolo.Error("Error writing response: %s", err.Error()) 102 | handleError(err, w) 103 | return 104 | } 105 | sigolo.Debug("Wrote %d bytes", bytesWritten) 106 | } 107 | } 108 | 109 | func handleError(err error, w http.ResponseWriter) { 110 | sigolo.Error(err.Error()) 111 | w.WriteHeader(500) 112 | fmt.Fprintf(w, err.Error()) 113 | } 114 | -------------------------------------------------------------------------------- /stream/buffer.go: -------------------------------------------------------------------------------- 1 | package stream 2 | 3 | import ( 4 | "io" 5 | "sync" 6 | ) 7 | 8 | // Buffer is an in-memory stream which supports one writer and multiple readers. 9 | // The stream is backed by a byte slice and concurrency is handled by an RWLock. 10 | type Buffer struct { 11 | buf []byte 12 | rw *sync.RWMutex 13 | } 14 | 15 | // bufferReader represents a single reader of a Buffer. It essentialy is an 16 | // index into the Buffer which indicates the current position from read data 17 | // from. Multiple instances of bufferReader can read concurrently from the 18 | // underlying Buffer 19 | type bufferReader struct { 20 | buffer *Buffer 21 | i int64 22 | } 23 | 24 | // NewBuffer returns an empty Buffer backed by a byte slice of initial length 0 25 | // and default capacity 26 | func NewBuffer() Source { 27 | return &Buffer{ 28 | buf: make([]byte, 0), 29 | rw: new(sync.RWMutex), 30 | } 31 | } 32 | 33 | // Open returns a new reader into Buffer. Open may be called multiple times to 34 | // retrieve multiple readers. All readers may read concurrently 35 | func (b *Buffer) Open() (io.Reader, error) { 36 | return &bufferReader{ 37 | buffer: b, 38 | i: 0, 39 | }, nil 40 | } 41 | 42 | func (b *bufferReader) Read(dst []byte) (n int, err error) { 43 | b.buffer.rw.RLock() 44 | defer b.buffer.rw.RUnlock() 45 | if b.i >= int64(len(b.buffer.buf)) { 46 | // No more data. Return EOF, Stream will wait for next write op 47 | return 0, io.EOF 48 | } 49 | n = copy(dst, b.buffer.buf[b.i:]) 50 | b.i += int64(n) 51 | return n, nil 52 | } 53 | 54 | func (b *Buffer) Write(src []byte) (n int, err error) { 55 | b.rw.Lock() 56 | defer b.rw.Unlock() 57 | b.buf = append(b.buf, src...) 58 | return len(src), nil 59 | } 60 | -------------------------------------------------------------------------------- /stream/file.go: -------------------------------------------------------------------------------- 1 | package stream 2 | 3 | import ( 4 | "io" 5 | "os" 6 | ) 7 | 8 | // File is a source for streams which is backed by a file on the file system. 9 | // Concurrency and safety is provided by the file system, hence no need for 10 | // mutex/locks. The write method is provided for free by *os.File. 11 | type File struct { 12 | *os.File 13 | } 14 | 15 | // NewFile creates a new file in path which is used as the source for a stream. 16 | // If the file cannot be created it panics. 17 | func NewFile(path string) Source { 18 | file, err := os.Create(path) 19 | if err != nil { 20 | panic(err) 21 | } 22 | return &File{file} 23 | } 24 | 25 | // Open returns a new reader for the file by opening the file in read only mode. 26 | func (f File) Open() (io.Reader, error) { 27 | return os.Open(f.Name()) 28 | } 29 | -------------------------------------------------------------------------------- /stream/stream.go: -------------------------------------------------------------------------------- 1 | // Package stream implements data streams which support one writer and multiple 2 | // concurrent readers. The Stream struct governs execution and suspension of 3 | // processed when data is available/unavailable. The Source struct handles 4 | // concurrent reads and writes to some data source. Streams are backed by such 5 | // a data Source implementation which is supplied as an in-memory and file 6 | // backed implementation 7 | package stream 8 | 9 | import ( 10 | "errors" 11 | "io" 12 | "sync" 13 | ) 14 | 15 | // New returns a new stream. A stream will have one writer and multiple readers 16 | // which can read from the stream concurrently. The stream is backed by a source 17 | // which is typically an in-memory slice of bytes or a file on disk. When no 18 | // data is available for readers, readers will be suspended from execution. When 19 | // the writer writes new data to the stream all readers are notified. Only when 20 | // the writer explicitly declares the end of the stream (no more data to write), 21 | // readers will begin to receive EOF on following reads. 22 | func New(source Source) *Stream { 23 | return &Stream{ 24 | Source: source, 25 | writer: source, 26 | cond: sync.NewCond(new(sync.Mutex)), 27 | closed: false, 28 | } 29 | } 30 | 31 | // Source is the underlying data store for a stream. Multiple implementations 32 | // of sources may exist. Typical implementations are in-memory and file backed 33 | // sources. Implementation must as a bare minimum provide one writer, multiple 34 | // readers and concurrency. 35 | type Source interface { 36 | io.Writer 37 | Open() (io.Reader, error) 38 | } 39 | 40 | // Stream handles access to some concurrency safe data store (source) and 41 | // handles suspension of execution when no data is available through a 42 | // sync.Condition. When the stream is closed, the closed bool will be true 43 | type Stream struct { 44 | Source 45 | writer io.Writer 46 | cond *sync.Cond 47 | closed bool 48 | } 49 | 50 | // streamReader is a single instance of a reader from a stream 51 | type streamReader struct { 52 | stream *Stream 53 | reader io.Reader 54 | } 55 | 56 | // NewReader returns a new reader for the stream. May be called multiple times 57 | // and each reader may read from the stream concurrently 58 | func (s *Stream) NewReader() (io.Reader, error) { 59 | r, err := s.Open() 60 | 61 | if err != nil { 62 | return nil, err 63 | } 64 | 65 | return &streamReader{ 66 | stream: s, 67 | reader: r, 68 | }, nil 69 | } 70 | 71 | // Read reads data from the stream. If no data is currently available and the 72 | // stream has not closed, the read method will block until more data is 73 | // available. Only when the writer has declared no more data (closed = true) 74 | // will the reader receive EOF. 75 | func (s *streamReader) Read(p []byte) (n int, err error) { 76 | s.stream.cond.L.Lock() 77 | defer s.stream.cond.L.Unlock() 78 | n, err = s.reader.Read(p) 79 | 80 | // No errors, base case, return data 81 | if err == nil { 82 | return 83 | } 84 | 85 | // End of file reached 86 | for err == io.EOF { 87 | // If we are done writing, handle this as a normal case 88 | if s.stream.closed { 89 | return 90 | } 91 | // If partial data, return that data, mask the EOF since the writer may 92 | // write additional data in the future 93 | if n > 0 { 94 | return n, nil 95 | } 96 | // Else, no data was read, wait until more data is available 97 | s.stream.cond.Wait() 98 | n, err = s.reader.Read(p) 99 | } 100 | return 101 | } 102 | 103 | func (s *Stream) Write(data []byte) (int, error) { 104 | defer s.cond.Broadcast() 105 | return s.writer.Write(data) 106 | } 107 | 108 | // CloseWrite is called when the writer declares the end of the stream. 109 | // This is a clear indication for readers, that no more data will be written to 110 | // the stream. Following this call, readers will begin receiving EOF on calls to 111 | // read. Readers may still join the stream after the stream is closed 112 | func (s *Stream) CloseWrite() error { 113 | s.cond.L.Lock() 114 | defer s.cond.L.Unlock() 115 | defer s.cond.Broadcast() 116 | if s.closed { 117 | return errors.New("Multireader closed multiple times") 118 | } 119 | s.closed = true 120 | return nil 121 | } 122 | -------------------------------------------------------------------------------- /stream/stream_test.go: -------------------------------------------------------------------------------- 1 | package stream 2 | 3 | import ( 4 | "bytes" 5 | "io" 6 | "io/ioutil" 7 | "math/rand" 8 | "sync" 9 | "testing" 10 | "time" 11 | 12 | "github.com/stretchr/testify/assert" 13 | "github.com/stretchr/testify/require" 14 | ) 15 | 16 | // TestStream test that all readers of a stream will receive the same data as 17 | // written by the one writer. Each reader is running concurrently in a 18 | // goroutine. When all readers have verified their result, the test ends. 19 | // Checking that readers are done are performed by a sync.WaitGroup. 20 | func TestStream(t *testing.T) { 21 | const numReaders = 16 22 | const dataSize = 1024 * 1024 // 1 MiB 23 | 24 | stream := New(NewBuffer()) 25 | 26 | wg := new(sync.WaitGroup) 27 | wg.Add(numReaders) 28 | 29 | r := rand.New(rand.NewSource(123)) 30 | buffer := new(bytes.Buffer) 31 | io.CopyN(buffer, r, dataSize) 32 | content := buffer.Bytes() 33 | 34 | for i := 0; i < numReaders; i++ { 35 | go func(i int) { 36 | r, err := stream.NewReader() 37 | defer wg.Done() 38 | time.Sleep(time.Duration(i) * 50 * time.Millisecond) 39 | require.Nil(t, err) 40 | data, err := ioutil.ReadAll(r) 41 | require.Nil(t, err) 42 | assert.Equal(t, data, content) 43 | }(i) 44 | } 45 | 46 | io.Copy(stream, bytes.NewBuffer(content)) 47 | err := stream.CloseWrite() 48 | assert.Nil(t, err) 49 | wg.Wait() 50 | } 51 | -------------------------------------------------------------------------------- /tiny.json: -------------------------------------------------------------------------------- 1 | { 2 | "port": "8080", 3 | "target": "https://imgs.xkcd.com/", 4 | "cache_folder": "./cache/", 5 | "debug_logging": true, 6 | "max_cache_item_size": 5 7 | } 8 | --------------------------------------------------------------------------------