adding initial files

This commit is contained in:
Milos Gagovic 2023-09-20 15:51:13 +02:00
parent 0a06188900
commit 4a4cf2d849
18 changed files with 618 additions and 1 deletions

12
.editorconfig Normal file
View File

@ -0,0 +1,12 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = tab
insert_final_newline = true
trim_trailing_whitespace = true
[*.{yaml,yml,md,mdx}]
indent_style = space

15
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,15 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "weekly"

33
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: Release Tag
on:
push:
tags:
- v*.*.*
workflow_dispatch:
env:
GOFLAGS: -mod=readonly
GOPROXY: https://proxy.golang.org
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- run: git fetch --force --tags
- uses: actions/setup-go@v4
with:
check-latest: true
go-version-file: 'go.mod'
- uses: goreleaser/goreleaser-action@v4
with:
version: latest
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

34
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,34 @@
name: Test Branch
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
merge_group:
branches: [ main ]
workflow_dispatch:
env:
GOFLAGS: -mod=readonly
GOPROXY: https://proxy.golang.org
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
check-latest: true
go-version-file: 'go.mod'
- uses: golangci/golangci-lint-action@v3
- name: Run tests
run: go test -v ./...

12
.gitignore vendored Normal file
View File

@ -0,0 +1,12 @@
.*
*.log
!.github/
!.husky/
!.editorconfig
!.gitignore
!.golangci.yml
!.goreleaser.yml
!.husky.yaml
/coverage.out
/coverage.html
/tmp/

60
.golangci.yml Normal file
View File

@ -0,0 +1,60 @@
run:
timeout: 5m
linters-settings:
importas:
alias:
- pkg: '^github.com\/foomo\/redirects\/(.*\/)?([^\/]+)\/?$'
alias: '${2}x' # enforce `x` suffix
no-unaliased: true
linters:
enable:
# Enabled by default linters:
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
# Disabled by default linters:
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers [fast: true, auto-fix: false]
- bidichk # Checks for dangerous unicode character sequences [fast: true, auto-fix: false]
- depguard # Go linter that checks if package imports are in a list of acceptable packages [fast: true, auto-fix: false]
- dupl # Tool for code clone detection [fast: true, auto-fix: false]
- forcetypeassert # finds forced type assertions [fast: true, auto-fix: false]
- gochecknoinits # Checks that no init functions are present in Go code [fast: true, auto-fix: false]
- goconst # Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false]
- gocritic # Provides diagnostics that check for bugs, performance and style issues. [fast: false, auto-fix: false]
- goimports # In addition to fixing imports, goimports also formats your code in the same style as gofmt. [fast: true, auto-fix: true]
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. [fast: true, auto-fix: false]
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. [fast: true, auto-fix: false]
- goprintffuncname # Checks that printf-like functions are named with `f` at the end [fast: true, auto-fix: false]
- gosec # (gas): Inspects source code for security problems [fast: false, auto-fix: false]
- grouper # An analyzer to analyze expression groups. [fast: true, auto-fix: false]
- importas # Enforces consistent import aliases [fast: false, auto-fix: false]
- maintidx # maintidx measures the maintainability index of each function. [fast: true, auto-fix: false]
- makezero # Finds slice declarations with non-zero initial length [fast: false, auto-fix: false]
- misspell # Finds commonly misspelled English words in comments [fast: true, auto-fix: true]
- nakedret # Finds naked returns in functions greater than a specified function length [fast: true, auto-fix: false]
- nestif # Reports deeply nested if statements [fast: true, auto-fix: false]
- nilerr # Finds the code that returns nil even if it checks that the error is not nil. [fast: false, auto-fix: false]
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. [fast: false, auto-fix: false]
- noctx # noctx finds sending http request without context.Context [fast: false, auto-fix: false]
- nolintlint # Reports ill-formed or insufficient nolint directives [fast: true, auto-fix: false]
- nonamedreturns # Reports all named returns [fast: false, auto-fix: false]
- nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL. [fast: true, auto-fix: false]
- prealloc # Finds slice declarations that could potentially be pre-allocated [fast: true, auto-fix: false]
- predeclared # find code that shadows one of Go's predeclared identifiers [fast: true, auto-fix: false]
- promlinter # Check Prometheus metrics naming via promlint [fast: true, auto-fix: false]
- revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. [fast: false, auto-fix: false]
- tagliatelle # Checks the struct tags. [fast: true, auto-fix: false]
- testpackage # linter that makes you use a separate _test package [fast: true, auto-fix: false]
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers [fast: false, auto-fix: false]
- unconvert # Remove unnecessary type conversions [fast: false, auto-fix: false]
- unparam # Reports unused function parameters [fast: false, auto-fix: false]
- usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library. [fast: true, auto-fix: false]
- wastedassign # wastedassign finds wasted assignment statements. [fast: false, auto-fix: false]
- whitespace # Tool for detection of leading and trailing whitespace [fast: true, auto-fix: true]
disable:
- unused

34
.goreleaser.yml Normal file
View File

@ -0,0 +1,34 @@
builds:
- skip: true
changelog:
filters:
exclude:
- "^wip"
- "^test"
- "^docs"
- "^chore"
- "^style"
- "go mod tidy"
- "merge conflict"
- "Merge pull request"
- "Merge remote-tracking branch"
- "Merge branch"
groups:
- title: Features
regexp: '^.*?feat(\([[:word:]]+\))??!?:.+$'
order: 0
- title: Dependency updates
regexp: '^.*?(feat|fix)\(deps\)!?:.+$'
order: 100
- title: "Bug fixes"
regexp: '^.*?fix(\([[:word:]]+\))??!?:.+$'
order: 150
- title: "Security"
regexp: '^.*?sec(\([[:word:]]+\))??!?:.+$'
order: 200
- title: "Performace"
regexp: '^.*?perf(\([[:word:]]+\))??!?:.+$'
order: 250
- title: Other
order: 999

128
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
info@bestbytes.de.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Foomo web framework
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

91
Makefile Normal file
View File

@ -0,0 +1,91 @@
.DEFAULT_GOAL:=help
-include .makerc
# --- Targets -----------------------------------------------------------------
# This allows us to accept extra arguments
%: .husky
@:
.PHONY: .husky
# Configure git hooks for husky
.husky:
@if ! command -v husky &> /dev/null; then \
echo "ERROR: missing executeable 'husky', please run:"; \
echo "\n$ go install github.com/go-courier/husky/cmd/husky@latest\n"; \
fi
@git config core.hooksPath .husky
## === Tasks ===
.PHONY: doc
## Run tests
doc:
@open "http://localhost:6060/pkg/github.com/foomo/contentfulvalidation/"
@godoc -http=localhost:6060 -play
.PHONY: test
## Run tests
test:
@set -euo pipefail && go test -json -v ./... | gotestfmt
.PHONY: test.cover
## Run tests with coverage
test.cover:
@go test -v -coverprofile=coverage.out ./...
@go tool cover -func=coverage.out
@go tool cover -html=coverage.out
.PHONY: lint
## Run linter
lint:
@golangci-lint run
.PHONY: lint.fix
## Run linter and fix violations
lint.fix:
@golangci-lint run --fix
.PHONY: tidy
## Run go mod tidy
tidy:
@go mod tidy
.PHONY: outdated
## Show outdated direct dependencies
outdated:
@go list -u -m -json all | go-mod-outdated -update -direct
## === Utils ===
## Show help text
help:
@awk '{ \
if ($$0 ~ /^.PHONY: [a-zA-Z\-\_0-9]+$$/) { \
helpCommand = substr($$0, index($$0, ":") + 2); \
if (helpMessage) { \
printf "\033[36m%-23s\033[0m %s\n", \
helpCommand, helpMessage; \
helpMessage = ""; \
} \
} else if ($$0 ~ /^[a-zA-Z\-\_0-9.]+:/) { \
helpCommand = substr($$0, 0, index($$0, ":")); \
if (helpMessage) { \
printf "\033[36m%-23s\033[0m %s\n", \
helpCommand, helpMessage"\n"; \
helpMessage = ""; \
} \
} else if ($$0 ~ /^##/) { \
if (helpMessage) { \
helpMessage = helpMessage"\n "substr($$0, 3); \
} else { \
helpMessage = substr($$0, 3); \
} \
} else { \
if (helpMessage) { \
print "\n "helpMessage"\n" \
} \
helpMessage = ""; \
} \
}' \
$(MAKEFILE_LIST)

View File

@ -1 +1,11 @@
This is readme
# redirects
[![GoDoc](https://godoc.org/github.com/foomo/go?status.svg)](https://godoc.org/github.com/foomo/go)
[![Go Report Card](https://goreportcard.com/badge/github.com/foomo/redirects)](https://goreportcard.com/report/github.com/foomo/contentfulvalidation)
[![Tests](https://github.com/foomo/contentfulvalidation/actions/workflows/test.yml/badge.svg)](https://github.com/foomo/redirects/actions/workflows/test.yml)
Framework to kickstart automatic redirects.
## License
Distributed under MIT License, please see license file within the code for more details.

3
generate.go Normal file
View File

@ -0,0 +1,3 @@
package redirects
//go:generate gotsrpc gotsrpc.yml

15
go.mod Normal file
View File

@ -0,0 +1,15 @@
module github.com/foomo/redirects
go 1.20
require (
github.com/foomo/gotsrpc/v2 v2.7.2 // indirect
github.com/iancoleman/strcase v0.2.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/mod v0.9.0 // indirect
golang.org/x/sys v0.6.0 // indirect
golang.org/x/tools v0.7.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)

19
go.sum Normal file
View File

@ -0,0 +1,19 @@
github.com/foomo/gotsrpc/v2 v2.7.2 h1:a94V/a8LSssq+aRN3Fv1lJPjWoyMilOvRq+yEaDTHVM=
github.com/foomo/gotsrpc/v2 v2.7.2/go.mod h1:n5SiKVNCZ7Tob6wcROWT5Sx1i/W42+ErpTbNqT3etM8=
github.com/iancoleman/strcase v0.2.0 h1:05I4QRnGpI0m37iZQRuskXh+w77mr6Z41lwQzuHLwW0=
github.com/iancoleman/strcase v0.2.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/mod v0.9.0 h1:KENHtAZL2y3NLMYZeHY9DW8HW8V+kQyJsY/V9JlKvCs=
golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/tools v0.7.0 h1:W4OVu8VVOaIO0yzWMNdepAulS7YfoS3Zabrm8DOXXU4=
golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=

11
gotsrpc.yml Normal file
View File

@ -0,0 +1,11 @@
module:
name: github.com/foomo/redirects
path: ./
targets:
redirect:
services:
/services/redirects/redirect: Redirect
package: github.com/foomo/redirects/redirect
tsrpc:
- Redirect

68
redirect/gotsrpc_gen.go Normal file
View File

@ -0,0 +1,68 @@
// Code generated by gotsrpc https://github.com/foomo/gotsrpc/v2 - DO NOT EDIT.
package redirect
import (
io "io"
http "net/http"
time "time"
gotsrpc "github.com/foomo/gotsrpc/v2"
)
const (
RedirectGoTSRPCProxyCreate = "Create"
)
type RedirectGoTSRPCProxy struct {
EndPoint string
service Redirect
}
func NewDefaultRedirectGoTSRPCProxy(service Redirect) *RedirectGoTSRPCProxy {
return NewRedirectGoTSRPCProxy(service, "/services/redirects/redirect")
}
func NewRedirectGoTSRPCProxy(service Redirect, endpoint string) *RedirectGoTSRPCProxy {
return &RedirectGoTSRPCProxy{
EndPoint: endpoint,
service: service,
}
}
// ServeHTTP exposes your service
func (p *RedirectGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
return
} else if r.Method != http.MethodPost {
gotsrpc.ErrorMethodNotAllowed(w)
return
}
defer io.Copy(io.Discard, r.Body) // Drain Request Body
funcName := gotsrpc.GetCalledFunc(r, p.EndPoint)
callStats, _ := gotsrpc.GetStatsForRequest(r)
callStats.Func = funcName
callStats.Package = "github.com/foomo/redirects/redirect"
callStats.Service = "Redirect"
switch funcName {
case RedirectGoTSRPCProxyCreate:
var (
args []interface{}
rets []interface{}
)
executionStart := time.Now()
p.service.Create()
callStats.Execution = time.Since(executionStart)
rets = []interface{}{}
if err := gotsrpc.Reply(rets, callStats, r, w); err != nil {
gotsrpc.ErrorCouldNotReply(w)
return
}
gotsrpc.Monitor(w, r, args, rets, callStats)
return
default:
gotsrpc.ClearStats(r)
gotsrpc.ErrorFuncNotFound(w)
}
}

View File

@ -0,0 +1,46 @@
// Code generated by gotsrpc https://github.com/foomo/gotsrpc/v2 - DO NOT EDIT.
package redirect
import (
go_context "context"
go_net_http "net/http"
gotsrpc "github.com/foomo/gotsrpc/v2"
pkg_errors "github.com/pkg/errors"
)
type RedirectGoTSRPCClient interface {
Create(ctx go_context.Context) (clientErr error)
}
type HTTPRedirectGoTSRPCClient struct {
URL string
EndPoint string
Client gotsrpc.Client
}
func NewDefaultRedirectGoTSRPCClient(url string) *HTTPRedirectGoTSRPCClient {
return NewRedirectGoTSRPCClient(url, "/services/redirects/redirect")
}
func NewRedirectGoTSRPCClient(url string, endpoint string) *HTTPRedirectGoTSRPCClient {
return NewRedirectGoTSRPCClientWithClient(url, endpoint, nil)
}
func NewRedirectGoTSRPCClientWithClient(url string, endpoint string, client *go_net_http.Client) *HTTPRedirectGoTSRPCClient {
return &HTTPRedirectGoTSRPCClient{
URL: url,
EndPoint: endpoint,
Client: gotsrpc.NewClientWithHttpClient(client),
}
}
func (tsc *HTTPRedirectGoTSRPCClient) Create(ctx go_context.Context) (clientErr error) {
args := []interface{}{}
reply := []interface{}{}
clientErr = tsc.Client.Call(ctx, tsc.URL, tsc.EndPoint, "Create", args, reply)
if clientErr != nil {
clientErr = pkg_errors.WithMessage(clientErr, "failed to call redirect.RedirectGoTSRPCProxy Create")
}
return
}

5
redirect/redirect.go Normal file
View File

@ -0,0 +1,5 @@
package redirect
type Redirect interface {
Create()
}