You've already forked img-proxy-url-generator
Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
a773b38794
|
|||
|
287d80ce86
|
|||
|
|
398ec7af81 | ||
|
d0e55c9a6b
|
|||
|
0271d575ab
|
|||
|
a834bc6384
|
|||
|
|
889ba3cb48 | ||
|
|
1e75f7823b | ||
|
e8eff432fc
|
|||
|
984909a648
|
|||
|
0d4a7fdb94
|
38
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
38
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Desktop (please complete the following information):**
|
||||
- OS: [e.g. iOS]
|
||||
- Browser [e.g. chrome, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Smartphone (please complete the following information):**
|
||||
- Device: [e.g. iPhone6]
|
||||
- OS: [e.g. iOS8.1]
|
||||
- Browser [e.g. stock browser, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
10
.github/ISSUE_TEMPLATE/custom.md
vendored
Normal file
10
.github/ISSUE_TEMPLATE/custom.md
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
---
|
||||
name: Custom issue template
|
||||
about: Describe this issue template's purpose here.
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
|
||||
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
6
.github/dependabot.yml
vendored
Normal file
6
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: gomod
|
||||
directory: /
|
||||
schedule:
|
||||
interval: daily
|
||||
27
.github/workflows/tests.yml
vendored
Normal file
27
.github/workflows/tests.yml
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
name: Go Tests
|
||||
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [ '1.22.x' ]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ${{ matrix.go-version }}
|
||||
- name: Install dependencies
|
||||
run: go get .
|
||||
- name: Test with Go
|
||||
run: go test ./... -json -cover > TestResults-${{ matrix.go-version }}.json
|
||||
- name: Upload Go test results
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: Go-results-${{ matrix.go-version }}
|
||||
path: TestResults-${{ matrix.go-version }}.json
|
||||
201
LICENSE
Normal file
201
LICENSE
Normal file
@@ -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.
|
||||
18
README.md
18
README.md
@@ -1,25 +1,29 @@
|
||||
# img-proxy url generator
|
||||
|
||||
|
||||
[host](https://docs.imgproxy.net/installation) an instance of img-proxy
|
||||
|
||||
img proxy [docs](https://docs.imgproxy.net/usage/processing)
|
||||
|
||||
## build
|
||||
|
||||
you can optionally hard code a path prefix on build
|
||||
you can optionally hard code a path prefix when building
|
||||
```shell
|
||||
go build --ldflags="-X 'github.com/siteworxpro/img-proxy-url-generator/generator.PathPrefix=s3://mybucket'"
|
||||
```
|
||||
|
||||
## config file
|
||||
|
||||
###### params
|
||||
### params
|
||||
|
||||
[img-proxy]
|
||||
- `key` sha256 hmac key
|
||||
- `salt` sha256 hmac salt
|
||||
- `host` img-proxy server hostname
|
||||
- `encryption-key` aes encryption key
|
||||
- `plain-url` send plain filename. bypasses all encoding
|
||||
- `plain-url` bypasses all encoding and uses plain filename
|
||||
|
||||
example config file
|
||||
```ini
|
||||
[img-proxy]
|
||||
key=2c...47
|
||||
@@ -29,7 +33,7 @@ encryption-key=1c...0b
|
||||
plain-url=1
|
||||
```
|
||||
|
||||
## usage
|
||||
## usage examples
|
||||
|
||||
generate a plain url with an insecure signature
|
||||
```ini
|
||||
@@ -73,7 +77,7 @@ salt=3f...4a
|
||||
https://i.fooo.com/NIColt6GBjtbquJXAtEMMsptARPw0CdeduEcu-S9Voc/raw:1/bG9jYWw6Ly9teS1zdXBlci1pbWFnZS5wbmc
|
||||
```
|
||||
|
||||
generate an encrypted url
|
||||
generate an encrypted url with a signature
|
||||
```ini
|
||||
[img-proxy]
|
||||
host=https://i.fooo.com
|
||||
@@ -88,7 +92,7 @@ encryption-key=1c...0b
|
||||
https://i.fooo.com/m3YtaMSgL86qCnfKCnS2i9_vLRmJSogdBx1o86cWbuc/raw:1/enc/F6FAWktv2SAFe5UQwMme0pB6JwKQJVtTI_6Xx-PUfKANdQk0pD1I13NPnv0CvkFT
|
||||
```
|
||||
|
||||
generate a url with params
|
||||
generate with params
|
||||
```bash
|
||||
./imgproxy --image "local:///my-super-image.png" -p h:200 -p rot:90
|
||||
|
||||
@@ -96,7 +100,7 @@ https://i.fooo.com/q-CfgLiuHTXDiZg7vBsUbZB3nkhzfsPgNrK0x20b878/h:200/rot:90/sm:1
|
||||
```
|
||||
|
||||
|
||||
generate a url a format
|
||||
generate a url with a specified format
|
||||
```bash
|
||||
./imgproxy --image "local:///my-super-image.png" --format bmp -p h:200
|
||||
|
||||
|
||||
35
aws/client.go
Normal file
35
aws/client.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package aws
|
||||
|
||||
import (
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
AwsKey string
|
||||
AwsSecret string
|
||||
AwsRole string
|
||||
Bucket string
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
s3 *s3.S3
|
||||
bucket string
|
||||
}
|
||||
|
||||
func NewClient(config *Config) *Service {
|
||||
awsSession := session.Must(session.NewSession(&aws.Config{
|
||||
Credentials: credentials.NewStaticCredentials(config.AwsKey, config.AwsSecret, ""),
|
||||
Region: aws.String("us-east-1"),
|
||||
}))
|
||||
|
||||
assumeRoleCredentials := stscreds.NewCredentials(awsSession, config.AwsRole)
|
||||
|
||||
return &Service{
|
||||
s3: s3.New(awsSession, &aws.Config{Credentials: assumeRoleCredentials}),
|
||||
bucket: config.Bucket,
|
||||
}
|
||||
}
|
||||
48
aws/s3.go
Normal file
48
aws/s3.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package aws
|
||||
|
||||
import (
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
)
|
||||
|
||||
type Image struct {
|
||||
Url string
|
||||
Download string
|
||||
Name string
|
||||
S3Path string
|
||||
}
|
||||
|
||||
type BucketList struct {
|
||||
Images []Image
|
||||
StartAfter string
|
||||
}
|
||||
|
||||
func (s *Service) ListBucketContents(continuationToken *string) (*BucketList, error) {
|
||||
v2, err := s.s3.ListObjectsV2(&s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(s.bucket),
|
||||
MaxKeys: aws.Int64(20),
|
||||
ContinuationToken: continuationToken,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
bucketList := BucketList{
|
||||
Images: make([]Image, 0),
|
||||
}
|
||||
|
||||
if v2.NextContinuationToken != nil {
|
||||
bucketList.StartAfter = *v2.NextContinuationToken
|
||||
}
|
||||
|
||||
for _, item := range v2.Contents {
|
||||
image := Image{
|
||||
Name: *item.Key,
|
||||
S3Path: "s3://" + s.bucket + "/" + *item.Key,
|
||||
}
|
||||
bucketList.Images = append(bucketList.Images, image)
|
||||
}
|
||||
|
||||
return &bucketList, nil
|
||||
}
|
||||
3
build.sh
3
build.sh
@@ -8,6 +8,7 @@ do
|
||||
|
||||
if [[ ${arrIN[0]} == 'linux' || ${arrIN[0]} == 'darwin' || ${arrIN[0]} == 'freebsd' || ${arrIN[0]} == 'windows' ]]; then
|
||||
echo "Building $distro..."
|
||||
GOOS=${arrIN[0]} GOARCH=${arrIN[1]} go build --ldflags="-X 'main.Version=$(git describe --tags --abbrev=0)'" -o dist/img_proxy_${arrIN[0]}_${arrIN[1]}
|
||||
GOOS=${arrIN[0]} GOARCH=${arrIN[1]} go build --ldflags="-X 'main.Version=$(git describe --tags --abbrev=0)'" -o "dist/img-proxy-url-generator_${arrIN[0]}_${arrIN[1]}"
|
||||
gpg --detach-sign "dist/img-proxy-url-generator_${arrIN[0]}_${arrIN[1]}"
|
||||
fi
|
||||
done
|
||||
7
generator/base64.go
Normal file
7
generator/base64.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package generator
|
||||
|
||||
import "encoding/base64"
|
||||
|
||||
func (g *Generator) generateBase64Url(file []byte) (string, error) {
|
||||
return base64.RawURLEncoding.EncodeToString(file), nil
|
||||
}
|
||||
21
generator/base64_test.go
Normal file
21
generator/base64_test.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package generator
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGenerator_GenerateBase64(t *testing.T) {
|
||||
g, err := NewGenerator(Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
url, err := g.generateBase64Url([]byte("test://file"))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if url != "dGVzdDovL2ZpbGU" {
|
||||
t.Errorf("url is wrong: %s", url)
|
||||
}
|
||||
}
|
||||
41
generator/crypt.go
Normal file
41
generator/crypt.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package generator
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"io"
|
||||
)
|
||||
|
||||
func pkcs7pad(data []byte, blockSize int) []byte {
|
||||
padLen := blockSize - len(data)%blockSize
|
||||
padding := bytes.Repeat([]byte{byte(padLen)}, padLen)
|
||||
return append(data, padding...)
|
||||
}
|
||||
|
||||
func (g *Generator) generateBaseAesEncUrl(file []byte) (string, error) {
|
||||
c, err := aes.NewCipher(g.config.encryptionKeyBin)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
data := pkcs7pad(file, aes.BlockSize)
|
||||
|
||||
ciphertext := make([]byte, aes.BlockSize+len(data))
|
||||
iv := ciphertext[:aes.BlockSize]
|
||||
|
||||
if _, err = io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
mode := cipher.NewCBCEncrypter(c, iv)
|
||||
mode.CryptBlocks(ciphertext[aes.BlockSize:], data)
|
||||
|
||||
encryptedURL, err := g.generateBase64Url(ciphertext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return "enc/" + encryptedURL, nil
|
||||
}
|
||||
45
generator/format_test.go
Normal file
45
generator/format_test.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package generator
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestGenerator_StringToFormat(t *testing.T) {
|
||||
g, err := NewGenerator(Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
formats := []string{"jpg", "jpeg", "png", "gif", "bmp", "webp", "ico", ""}
|
||||
|
||||
for _, format := range formats {
|
||||
format, err := g.StringToFormat(format)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if !isFormat(format) {
|
||||
t.Error("format not match")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerator_StringToFormatError(t *testing.T) {
|
||||
g, err := NewGenerator(Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err = g.StringToFormat("notaformat")
|
||||
if err == nil {
|
||||
t.Error("format did not return error")
|
||||
}
|
||||
}
|
||||
|
||||
func isFormat(t interface{}) bool {
|
||||
switch t.(type) {
|
||||
case Format:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
|
||||
}
|
||||
}
|
||||
5
generator/plain.go
Normal file
5
generator/plain.go
Normal file
@@ -0,0 +1,5 @@
|
||||
package generator
|
||||
|
||||
func (g *Generator) generatePlainUrl(file string) (string, error) {
|
||||
return "plain/" + file, nil
|
||||
}
|
||||
16
generator/plain_test.go
Normal file
16
generator/plain_test.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package generator
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestGenerator_GenerateUrl(t *testing.T) {
|
||||
g, err := NewGenerator(Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
url, _ := g.generatePlainUrl("local:///test.png")
|
||||
|
||||
if url != "plain/local:///test.png" {
|
||||
t.Errorf("url is %s", url)
|
||||
}
|
||||
}
|
||||
24
generator/signature.go
Normal file
24
generator/signature.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package generator
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"github.com/siteworxpro/img-proxy-url-generator/printer"
|
||||
)
|
||||
|
||||
func (g *Generator) generateSignature(path string) string {
|
||||
var signature string
|
||||
if len(g.config.keyBin) == 0 || len(g.config.saltBin) == 0 {
|
||||
signature = "insecure"
|
||||
|
||||
printer.NewPrinter().LogWarning("Insecure url generated. Provide salt and key to sign and secure url.")
|
||||
|
||||
} else {
|
||||
mac := hmac.New(sha256.New, g.config.keyBin)
|
||||
mac.Write(g.config.saltBin)
|
||||
mac.Write([]byte(path))
|
||||
signature = base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
return signature
|
||||
}
|
||||
@@ -1,17 +1,8 @@
|
||||
package generator
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"github.com/siteworxpro/img-proxy-url-generator/printer"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -48,51 +39,15 @@ func NewGenerator(config Config) (*Generator, error) {
|
||||
|
||||
if gen.config.EncryptionKey != nil && *gen.config.EncryptionKey != "" {
|
||||
if gen.config.encryptionKeyBin, err = hex.DecodeString(*gen.config.EncryptionKey); err != nil {
|
||||
return nil, fmt.Errorf("Key expected to be hex-encoded string")
|
||||
return nil, fmt.Errorf("key expected to be hex-encoded string")
|
||||
}
|
||||
}
|
||||
|
||||
return gen, nil
|
||||
}
|
||||
|
||||
func (g *Generator) generatePlainUrl(file []byte) {
|
||||
|
||||
}
|
||||
|
||||
func (g *Generator) generateBase64Url(file []byte) string {
|
||||
return base64.RawURLEncoding.EncodeToString(file)
|
||||
}
|
||||
|
||||
func pkcs7pad(data []byte, blockSize int) []byte {
|
||||
padLen := blockSize - len(data)%blockSize
|
||||
padding := bytes.Repeat([]byte{byte(padLen)}, padLen)
|
||||
return append(data, padding...)
|
||||
}
|
||||
|
||||
func (g *Generator) generateBaseAesEncUrl(file []byte) (string, error) {
|
||||
c, err := aes.NewCipher(g.config.encryptionKeyBin)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
data := pkcs7pad(file, aes.BlockSize)
|
||||
|
||||
ciphertext := make([]byte, aes.BlockSize+len(data))
|
||||
iv := ciphertext[:aes.BlockSize]
|
||||
|
||||
if _, err = io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
mode := cipher.NewCBCEncrypter(c, iv)
|
||||
mode.CryptBlocks(ciphertext[aes.BlockSize:], data)
|
||||
|
||||
encryptedURL := g.generateBase64Url(ciphertext)
|
||||
|
||||
return "enc/" + encryptedURL, nil
|
||||
}
|
||||
|
||||
func (g *Generator) GenerateUrl(file string, params []string, format Format) (string, error) {
|
||||
|
||||
if params == nil || len(params) == 0 || params[0] == "" {
|
||||
params = []string{"raw:1"}
|
||||
} else {
|
||||
@@ -107,16 +62,16 @@ func (g *Generator) GenerateUrl(file string, params []string, format Format) (st
|
||||
|
||||
var url string
|
||||
var err error
|
||||
|
||||
if g.config.PlainUrl {
|
||||
url = "plain/" + file
|
||||
url, _ = g.generatePlainUrl(file)
|
||||
} else if g.config.encryptionKeyBin != nil {
|
||||
url, err = g.generateBaseAesEncUrl([]byte(file))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
} else {
|
||||
url = g.generateBase64Url([]byte(file))
|
||||
url, _ = g.generateBase64Url([]byte(file))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
path := fmt.Sprintf("%s%s", paramString, url)
|
||||
@@ -125,18 +80,7 @@ func (g *Generator) GenerateUrl(file string, params []string, format Format) (st
|
||||
path = path + "." + string(format)
|
||||
}
|
||||
|
||||
var signature string
|
||||
if len(g.config.keyBin) == 0 || len(g.config.saltBin) == 0 {
|
||||
signature = "insecure"
|
||||
|
||||
printer.NewPrinter().LogWarning("Insecure url generated. Provide salt and key to sign and secure url.")
|
||||
|
||||
} else {
|
||||
mac := hmac.New(sha256.New, g.config.keyBin)
|
||||
mac.Write(g.config.saltBin)
|
||||
mac.Write([]byte(path))
|
||||
signature = base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
signature := g.generateSignature(path)
|
||||
|
||||
return fmt.Sprintf("%s/%s%s", g.config.Host, signature, path), nil
|
||||
}
|
||||
|
||||
24
go.mod
24
go.mod
@@ -1,23 +1,25 @@
|
||||
module github.com/siteworxpro/img-proxy-url-generator
|
||||
|
||||
go 1.21.1
|
||||
|
||||
require github.com/bigkevmcd/go-configparser v0.0.0-20230427073640-c6b631f70126
|
||||
go 1.22.5
|
||||
|
||||
require (
|
||||
github.com/aws/aws-sdk-go v1.54.19
|
||||
github.com/bigkevmcd/go-configparser v0.0.0-20240624060122-ccd05f93a9d2
|
||||
github.com/charmbracelet/lipgloss v0.12.1
|
||||
github.com/urfave/cli/v2 v2.27.2
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/aws/aws-sdk-go v1.49.16 // indirect
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||
github.com/charmbracelet/lipgloss v0.10.0 // indirect
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
|
||||
github.com/charmbracelet/x/ansi v0.1.4 // indirect
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect
|
||||
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.18 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.15 // indirect
|
||||
github.com/muesli/reflow v0.3.0 // indirect
|
||||
github.com/muesli/termenv v0.15.2 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
||||
github.com/urfave/cli/v2 v2.27.1 // indirect
|
||||
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
|
||||
golang.org/x/sys v0.12.0 // indirect
|
||||
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect
|
||||
golang.org/x/sys v0.22.0 // indirect
|
||||
)
|
||||
|
||||
40
go.sum
40
go.sum
@@ -1,16 +1,26 @@
|
||||
github.com/aws/aws-sdk-go v1.49.16 h1:KAQwhLg296hfffRdh+itA9p7Nx/3cXS/qOa3uF9ssig=
|
||||
github.com/aws/aws-sdk-go v1.49.16/go.mod h1:LF8svs817+Nz+DmiMQKTO3ubZ/6IaTpq3TjupRn3Eqk=
|
||||
github.com/aws/aws-sdk-go v1.54.18 h1:t8DGtN8A2wEiazoJxeDbfPsbxCKtjoRLuO7jBSgJzo4=
|
||||
github.com/aws/aws-sdk-go v1.54.18/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU=
|
||||
github.com/aws/aws-sdk-go v1.54.19 h1:tyWV+07jagrNiCcGRzRhdtVjQs7Vy41NwsuOcl0IbVI=
|
||||
github.com/aws/aws-sdk-go v1.54.19/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU=
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
|
||||
github.com/bigkevmcd/go-configparser v0.0.0-20230427073640-c6b631f70126 h1:uru++pUKoS/yYU3Ohq9VItZdK/cT7FFJH/UUjOlxc+s=
|
||||
github.com/bigkevmcd/go-configparser v0.0.0-20230427073640-c6b631f70126/go.mod h1:zqqfbfnDeSdRs1WihmMjSbhb2Ptw8Jbus831xoqiIec=
|
||||
github.com/bigkevmcd/go-configparser v0.0.0-20240624060122-ccd05f93a9d2 h1:2qnRmzKO1fVs2UOqyt6tRMpVB8FrOnx8IG8C2lK0cjU=
|
||||
github.com/bigkevmcd/go-configparser v0.0.0-20240624060122-ccd05f93a9d2/go.mod h1:vzEQfW+A1T+AMJmTIX+SXNLNECHOM7GEinHhw0IjykI=
|
||||
github.com/charmbracelet/lipgloss v0.10.0 h1:KWeXFSexGcfahHX+54URiZGkBFazf70JNMtwg/AFW3s=
|
||||
github.com/charmbracelet/lipgloss v0.10.0/go.mod h1:Wig9DSfvANsxqkRsqj6x87irdy123SR4dOXlKa91ciE=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/charmbracelet/lipgloss v0.12.1 h1:/gmzszl+pedQpjCOH+wFkZr/N90Snz40J/NR7A0zQcs=
|
||||
github.com/charmbracelet/lipgloss v0.12.1/go.mod h1:V2CiwIuhx9S1S1ZlADfOj9HmxeMAORuz5izHb0zGbB8=
|
||||
github.com/charmbracelet/x/ansi v0.1.4 h1:IEU3D6+dWwPSgZ6HBH+v6oUuZ/nVawMiWj5831KfiLM=
|
||||
github.com/charmbracelet/x/ansi v0.1.4/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
|
||||
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
|
||||
github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=
|
||||
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
|
||||
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
|
||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
@@ -18,8 +28,8 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=
|
||||
github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
|
||||
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
@@ -27,6 +37,7 @@ github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
|
||||
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
|
||||
github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=
|
||||
github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
|
||||
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/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
@@ -35,14 +46,19 @@ github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUc
|
||||
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/urfave/cli/v2 v2.27.1 h1:8xSQ6szndafKVRmfyeUMxkNUJQMjL1F2zmsZ+qHpfho=
|
||||
github.com/urfave/cli/v2 v2.27.1/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ=
|
||||
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=
|
||||
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8=
|
||||
github.com/urfave/cli/v2 v2.27.2 h1:6e0H+AkS+zDckwPCUrZkKX38mRaau4nL2uipkJpbkcI=
|
||||
github.com/urfave/cli/v2 v2.27.2/go.mod h1:g0+79LmHHATl7DAcHO99smiR/T7uGLw84w8Y42x+4eM=
|
||||
github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 h1:+qGGcbkzsfDQNPPe9UDgpxAWQrhbbBXOYJFQDq/dtJw=
|
||||
github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913/go.mod h1:4aEEwZQutDLsQv2Deui4iYQ6DWTxR14g6m8Wv88+Xqk=
|
||||
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4=
|
||||
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
|
||||
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
|
||||
113
main.go
113
main.go
@@ -3,9 +3,13 @@ package main
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/bigkevmcd/go-configparser"
|
||||
"github.com/siteworxpro/img-proxy-url-generator/aws"
|
||||
"github.com/siteworxpro/img-proxy-url-generator/generator"
|
||||
"github.com/siteworxpro/img-proxy-url-generator/printer"
|
||||
"github.com/urfave/cli/v2"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
@@ -15,23 +19,19 @@ var imgGenerator *generator.Generator
|
||||
|
||||
var Version = "v0.0.0"
|
||||
|
||||
var awsConfig aws.Config
|
||||
|
||||
func main() {
|
||||
|
||||
pr := printer.NewPrinter()
|
||||
|
||||
app := &cli.App{
|
||||
Name: "img-proxy-url-generator",
|
||||
Usage: "URL Generator for the img proxy service",
|
||||
DefaultCommand: "generate",
|
||||
Version: Version,
|
||||
Commands: []*cli.Command{
|
||||
{
|
||||
Name: "generate",
|
||||
Usage: "Generate an image from a URL",
|
||||
Action: func(c *cli.Context) error {
|
||||
return run(c, pr)
|
||||
},
|
||||
},
|
||||
var commands []*cli.Command
|
||||
|
||||
commands = append(commands, &cli.Command{
|
||||
Name: "generate",
|
||||
Usage: "Generate an image from a URL",
|
||||
Action: func(c *cli.Context) error {
|
||||
return run(c, pr)
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{
|
||||
@@ -39,12 +39,6 @@ func main() {
|
||||
Aliases: []string{"i"},
|
||||
Required: true,
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "config",
|
||||
Aliases: []string{"c"},
|
||||
Usage: "Config file to load from",
|
||||
DefaultText: "imgproxy.cfg",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "format",
|
||||
Aliases: []string{"f"},
|
||||
@@ -56,12 +50,39 @@ func main() {
|
||||
Usage: "Processing options to be passed to the generator ref: https://docs.imgproxy.net/usage/processing",
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
_, err := os.Stat("./templates")
|
||||
if !os.IsNotExist(err) {
|
||||
commands = append(commands, &cli.Command{
|
||||
Name: "server",
|
||||
Usage: "Start a webserver for s3 file browsing",
|
||||
Action: func(c *cli.Context) error {
|
||||
return startServer(c, pr)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
app := &cli.App{
|
||||
Name: "img-proxy-url-generator",
|
||||
Usage: "URL Generator for the img proxy service",
|
||||
DefaultCommand: "generate",
|
||||
Version: Version,
|
||||
Commands: commands,
|
||||
Action: func(c *cli.Context) error {
|
||||
return run(c, pr)
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{
|
||||
Name: "config",
|
||||
Aliases: []string{"c"},
|
||||
Usage: "Config file to load from",
|
||||
DefaultText: "imgproxy.cfg",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := app.Run(os.Args)
|
||||
err = app.Run(os.Args)
|
||||
if err != nil {
|
||||
pr.LogError(err.Error())
|
||||
|
||||
@@ -69,6 +90,51 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
func startServer(c *cli.Context, p *printer.Printer) error {
|
||||
err := initGenerator(c.String("config"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
awsClient := aws.NewClient(&awsConfig)
|
||||
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
contToken := r.URL.Query().Get("next")
|
||||
|
||||
var next *string
|
||||
if contToken == "" {
|
||||
next = nil
|
||||
} else {
|
||||
next = &contToken
|
||||
}
|
||||
|
||||
contents, err := awsClient.ListBucketContents(next)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
for i, content := range contents.Images {
|
||||
contents.Images[i].Url, _ = signURL("s3://"+awsConfig.Bucket+"/"+content.Name, []string{"pr:sq"}, "")
|
||||
contents.Images[i].Download, _ = signURL("s3://"+awsConfig.Bucket+"/"+content.Name, []string{""}, "")
|
||||
}
|
||||
|
||||
file, _ := os.ReadFile("./templates/index.gohtml")
|
||||
|
||||
tmpl := template.Must(template.New("index").Parse(string(file)))
|
||||
|
||||
err = tmpl.Execute(w, contents)
|
||||
|
||||
if err != nil {
|
||||
println(err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
p.LogSuccess("Starting http server on port 8080. http://localhost:8080")
|
||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func run(c *cli.Context, p *printer.Printer) error {
|
||||
err := initGenerator(c.String("config"))
|
||||
|
||||
@@ -135,6 +201,13 @@ func initGenerator(config string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if p.HasSection("aws") {
|
||||
awsConfig.AwsSecret, _ = p.Get("aws", "secret")
|
||||
awsConfig.AwsKey, _ = p.Get("aws", "key")
|
||||
awsConfig.AwsRole, _ = p.Get("aws", "role")
|
||||
awsConfig.Bucket, _ = p.Get("aws", "bucket")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
31
templates/index.gohtml
Normal file
31
templates/index.gohtml
Normal file
@@ -0,0 +1,31 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title></title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<style>
|
||||
a {
|
||||
text-decoration: none;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="flex flex-row flex-wrap justify-around text-center">
|
||||
{{ range .Images }}
|
||||
<div style="border: 1px solid #222222;" class="w-1/5 p-5 m-5 flex flex-wrap justify-center">
|
||||
<div>
|
||||
<a href="{{ .Download }}" target="_blank">
|
||||
<img style="background-color: #222222" src="{{ .Url }}" alt="{{ .Name }}"/>
|
||||
</a>
|
||||
</div>
|
||||
<div class="w-full">
|
||||
{{ .S3Path }}
|
||||
</div>
|
||||
</div>
|
||||
{{ end }}
|
||||
</div>
|
||||
<div class="p-10 text-right">
|
||||
<a href="/?next={{ .StartAfter }}">Next</a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user