diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1965bd6 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +*.go text eol=lf +go.mod text eol=lf +go.sum text eol=lf diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 615dfde..883dadb 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,3 +1,4 @@ +# yaml-language-server: $schema=https://json.schemastore.org/dependabot-2.0.json version: 2 updates: - package-ecosystem: "github-actions" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5a8983b..2f86eef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,3 +1,4 @@ +# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json name: CI on: @@ -50,6 +51,9 @@ jobs: echo '' make env + - name: Check shell files + run: make ci-sh + - name: ci-gen-n-format run: make ci-gen-n-format diff --git a/.golangci.yml b/.golangci.yml index 7f7d556..2285ebb 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,3 +1,5 @@ +# yaml-language-server: $schema=https://golangci-lint.run/jsonschema/golangci.jsonschema.json + # https://golangci-lint.run/usage/configuration/ # https://golangci-lint.run/usage/linters/ @@ -21,6 +23,7 @@ output: linters: enable-all: true disable: + - exportloopref # deprecated - exhaustruct # TODO: reconsider - depguard # TODO: reconsider - funlen # TODO: reconsider @@ -30,6 +33,10 @@ linters: - varnamelen - nonamedreturns - testpackage + - godox + - godot + - gochecknoglobals + - mnd issues: # https://golangci-lint.run/usage/false-positives/#default-exclusions @@ -50,7 +57,6 @@ linters-settings: unused: field-writes-are-uses: false post-statements-are-reads: false - exported-is-used: true exported-fields-are-used: true parameters-are-used: true local-variables-are-used: false diff --git a/.vscode/cspell.json b/.vscode/cspell.json index 5f08a63..3a94b75 100644 --- a/.vscode/cspell.json +++ b/.vscode/cspell.json @@ -17,6 +17,7 @@ "goimports", "gojq", "golangci", + "gomod", "GOPATH", "GOVERSION", "honnef", @@ -26,17 +27,21 @@ "mvdan", "NOTINTERMEDIATE", "NOTPARALLEL", + "POSIX", "proto", "protobuf", "PROTOBUFGO", "PROTOC", "SECONDEXPANSION", + "shellcheck", + "shfmt", "staticcheck", - "trimpath" + "trimpath", + "vektra" ], "ignorePaths": [ "vendor", ".git", "/go.mod" - ] + ], } diff --git a/.vscode/launch.json b/.vscode/launch.json index 4e36832..9422c32 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -22,12 +22,12 @@ ], }, { - "name": "Run Main", + "name": "Debug Main", "preLaunchTask": "build debug", "type": "go", "request": "launch", - "mode": "exec", - "program": "${workspaceFolder}/output/goboilerplate", + "mode": "debug", + "program": "${workspaceFolder}/cmd/goboilerplate", "debugAdapter": "dlv-dap", "buildFlags": "", "env": { @@ -36,7 +36,7 @@ "APP_HTTP_OUTBOUND_TRAFFIC_LOG_LEVEL": "2", "APP_HTTP_READ_HEADER_TIMEOUT": "3s", "APP_SHUTDOWN_TIMEOUT": "6s", - "APP_LOG_LEVEL": "-1" + "APP_LOG_LEVEL": "DEBUG" } } ] diff --git a/.vscode/settings.json b/.vscode/settings.json index 7c1f668..3bd9490 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,4 +1,10 @@ { + "json.schemas": [{ + "fileMatch": [ + "/.vscode/cspell.json" + ], + "url": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/packages/cspell-types/cspell.schema.json" + }], "search.exclude": { "**/vendor": true }, diff --git a/Makefile b/Makefile index 27b122e..2c43aec 100644 --- a/Makefile +++ b/Makefile @@ -1,172 +1,62 @@ -SHELL := /bin/bash +SHELL := /usr/bin/env bash +## https://www.gnu.org/software/make/manual/html_node/Parallel-Disable.html .NOTPARALLEL: -.SECONDEXPANSION: -## NOTINTERMEDIATE requires make >=4.4 -.NOTINTERMEDIATE: - -GO_EXEC ?= go -export GO_EXEC -DOCKER_EXEC ?= docker -export DOCKER_EXEC - -MODULE := $(shell cat go.mod | grep -e "^module" | sed "s/^module //") -VERSION ?= 0.0.0 -X_FLAGS = \ - -X '$(MODULE)/build.Version=$(VERSION)' \ - -X '$(MODULE)/build.Branch=$(shell git rev-parse --abbrev-ref HEAD 2>/dev/null || true)' \ - -X '$(MODULE)/build.Commit=$(shell git rev-parse HEAD 2>/dev/null || true)' \ - -X '$(MODULE)/build.CommitShort=$(shell git rev-parse --short HEAD 2>/dev/null || true)' \ - -X '$(MODULE)/build.Tag=$(shell git describe --tags 2>/dev/null || true)' -IMAGE_NAME ?= goboilerplate -IMAGE_TAG ?= latest - -GO_PACKAGES = $(GO_EXEC) list -tags='$(TAGS)' -mod=vendor ./... -GO_FOLDERS = $(GO_EXEC) list -tags='$(TAGS)' -mod=vendor -f '{{ .Dir }}' ./... -GO_FILES = find . -type f -name '*.go' -not -path './vendor/*' - -export GO111MODULE := on -#export GOFLAGS := -mod=vendor -GOPATH := $(shell go env GOPATH) -GO_VER := $(shell go env GOVERSION) -BUILD_OUTPUT ?= $(CURDIR)/output +include $(CURDIR)/scripts/go.mk +include $(CURDIR)/scripts/docker.mk include $(CURDIR)/scripts/tools.mk .DEFAULT_GOAL=default .PHONY: default default: checks build -.PHONY: mod -mod: - $(GO_EXEC) mod tidy -go=1.23 - $(GO_EXEC) mod verify - -.PHONY: vendor -vendor: - $(GO_EXEC) mod vendor - -# https://go.dev/ref/mod#go-get -# -u flag tells go get to upgrade modules -# -t flag tells go get to consider modules needed to build tests of packages named on the command line. -# When -t and -u are used together, go get will update test dependencies as well. -.PHONY: go-deps-upgrade -go-deps-upgrade: - $(GO_EXEC) get -u -t ./... - $(GO_EXEC) mod tidy -go=1.23 - $(GO_EXEC) mod vendor - -# https://pkg.go.dev/cmd/go#hdr-Compile_packages_and_dependencies -# https://pkg.go.dev/cmd/compile -# https://pkg.go.dev/cmd/link - -#BUILD_FLAGS := -mod=vendor -a -ldflags "-s -w $(X_FLAGS) -extldflags='-static'" -tags '$(TAGS)' -BUILD_FLAGS := -mod=vendor -a -ldflags '-s -w $(X_FLAGS)' -tags '$(TAGS)' -BUILD_FLAGS_DEBUG := -mod=vendor -ldflags '$(X_FLAGS)' -tags '$(TAGS)' - -.PHONY: build -build: $(shell ls -d cmd/* | sed -e 's/\//./') - -cmd.%: CMDNAME=$* -cmd.%: - $(GO_EXEC) env - @echo '' - CGO_ENABLED=0 $(GO_EXEC) build $(BUILD_FLAGS) -o $(BUILD_OUTPUT)/$(CMDNAME) ./cmd/$(CMDNAME) - -dbg.%: BUILD_FLAGS=$(BUILD_FLAGS_DEBUG) -dbg.%: cmd.% - @echo "debug binary done" - -.PHONY: clean -clean: - rm -rf $(BUILD_OUTPUT) - # man git-clean .PHONY: git-reset git-reset: git reset --hard git clean -fd -## https://docs.docker.com/reference/cli/docker/buildx/build/ -## --output='type=docker' -## --output='type=image,push=true' -## --platform=linux/arm64 -## --platform=linux/amd64,linux/arm64,linux/arm/v7 -## --platform=local -## --progress='plain' -## make DOCKER_BUILD_PLATFORM=linux/arm64 image -DOCKER_BUILD_PLATFORM ?= local -DOCKER_BUILD_OUTPUT ?= type=docker -.PHONY: image -image: - $(DOCKER_EXEC) buildx build \ - --output='type=docker' \ - --file='$(CURDIR)/build/docker/Dockerfile' \ - --tag='$(IMAGE_NAME):$(IMAGE_TAG)' \ - --platform='$(DOCKER_BUILD_PLATFORM)' \ - --output='$(DOCKER_BUILD_OUTPUT)' \ - . - -DOCKER_COMPOSE_EXEC ?= $(DOCKER_EXEC) compose -f $(CURDIR)/deployments/local/docker-compose.yml - -.PHONY: compose-up -compose-up: - $(DOCKER_COMPOSE_EXEC) up --force-recreate --build - -.PHONY: compose-up-detach -compose-up-detach: - $(DOCKER_COMPOSE_EXEC) up --force-recreate --build --detach - -.PHONY: compose-down -compose-down: - $(DOCKER_COMPOSE_EXEC) down --volumes --rmi local --remove-orphans - -# If the first target is "compose-exec" -# remove the first argument 'compose-exec' and store the rest in DOCKER_COMPOSE_ARGS -# and ignore the subsequent arguments as make targets. -# (using spaces for indentation) -ifeq (compose-exec,$(firstword $(MAKECMDGOALS))) - DOCKER_COMPOSE_ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS)) - $(eval $(DOCKER_COMPOSE_ARGS):;@:) -endif - -.PHONY: compose-exec -compose-exec: - $(DOCKER_COMPOSE_EXEC) exec $(DOCKER_COMPOSE_ARGS) - .PHONY: env env: - @echo "Module: $(MODULE)" + @echo -e "\e[0;90m>>>\e[0m \e[0;94m Module \e[0m \e[0;90m<<<\e[0m" + @echo "$(MODULE)" + @echo "" + + @echo -e "\e[0;90m>>>\e[0m \e[0;94m Go env \e[0m \e[0;90m<<<\e[0m" $(GO_EXEC) env @echo "" - @echo ">>> Packages:" + + @echo -e "\e[0;90m>>>\e[0m \e[0;94m Packages \e[0m \e[0;90m<<<\e[0m" $(GO_PACKAGES) @echo "" - @echo ">>> Folders:" + + @echo -e "\e[0;90m>>>\e[0m \e[0;94m Folders \e[0m \e[0;90m<<<\e[0m" $(GO_FOLDERS) @echo "" - @echo ">>> Files:" + + @echo -e "\e[0;90m>>>\e[0m \e[0;94m Files \e[0m \e[0;90m<<<\e[0m" $(GO_FILES) @echo "" - @echo ">>> Tools:" + + @echo -e "\e[0;90m>>>\e[0m \e[0;94m Tools \e[0m \e[0;90m<<<\e[0m" @echo '$(TOOLS_BIN)' @echo "" - @echo ">>> Path:" + + @echo -e "\e[0;90m>>>\e[0m \e[0;94m Path \e[0m \e[0;90m<<<\e[0m" @echo "$${PATH}" | tr ':' '\n' + @echo "" -.PHONY: test -test: - CGO_ENABLED=1 $(GO_EXEC) test -timeout 60s -race -tags="$(TAGS)" -coverprofile cover.out -covermode atomic ./... - @$(GO_EXEC) tool cover -func cover.out - @rm cover.out + @echo -e "\e[0;90m>>>\e[0m \e[0;94m Shell \e[0m \e[0;90m<<<\e[0m" + @echo "SHELL=$${SHELL}" + @echo "BASH=$${BASH}" + @echo "BASH_VERSION=$${BASH_VERSION}" + @echo "BASH_VERSINFO=$${BASH_VERSINFO}" + @echo "" .PHONY: checks checks: vet staticcheck gofumpt goimports golangci-lint-github-actions -.PHONY: run -run: - $(GO_EXEC) run -mod=vendor ./cmd/goboilerplate - .PHONY: ci-gen-n-format ci-gen-n-format: goimports gofumpt ./scripts/git-check-dirty @@ -174,3 +64,7 @@ ci-gen-n-format: goimports gofumpt .PHONY: ci-mod ci-mod: mod ./scripts/git-check-dirty + +.PHONY: ci-sh +ci-sh: shfmt shellcheck + @./scripts/git-check-dirty diff --git a/README.md b/README.md index c30102c..b291a87 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,20 @@ # Go service boilerplate The boilerplate consists of: -* Go code with [chi](https://github.com/go-chi/chi) http router, [zerolog](https://github.com/rs/zerolog) logging, [knadh/koanf](github.com/knadh/koanf) config library and [testify](github.com/stretchr/testify). Basic code infra with http setup and request and response logger (configurable), logging setup, config setup and graceful shutdown. +* Go code with + * [chi](https://github.com/go-chi/chi) http router. + * [slog](https://pkg.go.dev/log/slog) logging, + * [knadh/koanf](github.com/knadh/koanf) config library. + * [testify](github.com/stretchr/testify). + * Basic code infra with http setup and request and response logger (configurable), logging setup, config setup and graceful shutdown. + * Optional verbose logging of http traffic, with payload, * Makefile targets for local installation of external tools (`staticcheck`, `golangci-lint`, `goimports`, `gofumpt`, `gojq`, `air`). * Makefile targets for linting (installing all necessary tools locally), building, testing, and local run (docker compose or native). * [GitHub Actions](https://github.com/features/actions) for linter checks and tests on each pr. * [Dependabot](https://docs.github.com/en/code-security/dependabot/dependabot-security-updates/configuring-dependabot-security-updates) setup for updating dependencies. * [Visual Studio Code](https://code.visualstudio.com/) settings, tasks and launch configuration for building, debugging and testing the code. * Docker compose and development Dockerfile with hot-rebuild (using [air](https://github.com/air-verse/air)) and dlv debug server. -* Production Dockerfile +* Production Dockerfile. ## How to use 1. Click `Use this template` from this repo github page, and choose your destination repo/name (e.g. `github.com/glendale/service`) @@ -17,6 +23,7 @@ The boilerplate consists of: ## Go package and file structure +The project structure attempts to be on a par with [golang-standards/project-layout](https://github.com/golang-standards/project-layout). > Every local package that collides with a golang std package is named with `x` postfix. For example `.../internal/httpx` or `.../internal/logx`. By doing this cheat you can avoid putting aliases when you need both of those and you can take advantage of package autocomplete/autoimport features more easily than having colliding names. @@ -25,126 +32,13 @@ The boilerplate consists of: | `cmd/*/main.go` | main function that is intended to glue together the most core level components like: configuration, http server and router, logs initialization, db connections (if any), the `App` and finally the `Main` struct (`/internal/exec.go`) that handles the long running / signal handling / graceful shutdown of the service. | | `internal/exec.go` | the `Main` struct that wraps the long running / signal handling / graceful shutdown of the service | | `internal/config` | this package contain the initialization of `koanf` config. | -| `internal/httpx` | this package contains: the setup of the `chi` router, some helpers functions for parsing/writing http request and http response and some middlewares like for logging each request/response. | -| `internal/logx` | this package contains the setup/init function for `zerolog` logger. | +| `internal/httpx` | this package contains: the setup of the `chi` router, some helpers functions for parsing/writing http request and http response. | +| `internal/logx` | this package contains the setup/init function for `slog` logger. | | Folder/File | Description | |--------------------|-----------------------------------------| -| `deployments` | this folder is intended to hold everything regarding deployment (e.g. helm/kubernetes etc). Inside `compose` directory a `docker-compose.yml` file is included that is intended for local development. | +| `deployments` | this folder is intended to hold everything regarding deployment (e.g. helm/kubernetes etc). Inside `local` directory a `docker-compose.yml` file is included that is intended for local development. | | `build/docker` | this folder contains production-like docker file as well as a local development one. | - - - -## Make file targets - - -### Build, Debug and Local Deploy Targets - -#### `build` -Builds all binaries under `./cmd` (one for each directory) and outputs the binaries into `./output` folder using this patter `./cmd/ -> ./output/`. -___ - -#### `cmd.` -Builds a specific cmd directory `` and outputs the binary into `./output` folder using this pattern `./cmd/ -> ./output/`. -___ - -#### `clean` -Deletes `./output` folder. -___ - -#### `compose-up` -Deploys (rebuilds and recreates) the docker compose file `deployments/compose/docker-compose.yml` in attached mode. This docker compose file is intended for local development.
-It uses the docker file `build/docker/debug.Dockerfile` and runs `air` target (see below), including hot-reload (rebuild on changes) and debug server. -___ - -#### `compose-down` -Stops (if started) the containers specified by the docker compose file `deployments/compose/docker-compose.yml` removes containers, cleans up the volumes and delete local docker images. -___ - -#### `air` -Installs (if needed) [air](https://github.com/air-verse/air) under `TOOLS_BIN` folder (default is `./.tools/bin`) and runs `air -c .air.toml`.
-Air watches for code file changes and rebuilds the binary according to the configuration `.air.toml`.
-Current air configuration executes `cmd.goboilerplate` target (on each file change) and then runs the `./build/dlv` that starts the debug server (`dlv exec`) with the produced binary. -___ - -#### `image` -Builds the docker image using the docker file `./build/docker/Dockerfile`.
-This docker file is intended to be used as a production image.
-Image name and tag are specified by `IMAGE_NAME` and `IMAGE_TAG`. Default values can be overwritten during execution (eg `make IMAGE_NAME=myimage IMAGE_TAG=1.0.0 image`). -___ - - -### Util Targets - -#### `mod` -Runs go mod [tidy](https://go.dev/ref/mod#go-mod-tidy) and [verify](https://go.dev/ref/mod#go-mod-verify). -___ - -#### `vendor` -Runs [go mod vendor](https://go.dev/ref/mod#go-mod-vendor) that downloads all dependencies into `./vendor` folder. -___ - -#### `env` -Prints information regarding the local environment. More specifically: go env, all go packages and folders, and the specified tools bin directory. -___ - -#### `git-reset` -Full hard reset to HEAD. Cleans up all untracked files and restore all staged and un-staged changes. -___ - - -### Tests and Linters Targets - -#### `test` -Runs go [test](https://pkg.go.dev/cmd/go/internal/test) with race conditions and prints cover report. -___ - -#### `tools` -Installs (if needed) all tools (goimports, staticcheck, gofumpt, etc) under `TOOLS_BIN` folder (default is `./.tools/bin`). -___ - -#### `checks` -Runs all default checks (`vet`, `staticcheck`, `gofumpt`, `goimports`, `golangci-lint`). -___ - -#### `vet` -Runs go [vet](https://pkg.go.dev/cmd/vet). -___ - -#### `gofumpt` -Installs (if needed) [gofumpt](https://github.com/mvdan/gofumpt) under `TOOLS_BIN` folder (default is `./.tools/bin`) and runs `gofumpt` for each folder.
-If `gofumpt` finds files that need fix/format it displays those files as list and the target fails (_exit 1_). -___ - -#### `gofumpt.display` -In case of `gofumpt` fails this target can be used to display the necessary changes. It runs `gofumpt -d` to display the needed changes that can be applied with `make gofumpt.fix`. -___ - -#### `gofumpt.fix` -Runs `gofumpt -w` to fix/format files (that need fix). -___ - -#### `goimports` -Installs (if needed) [goimports](https://pkg.go.dev/golang.org/x/tools/cmd/goimports) under `TOOLS_BIN` folder (default is `./.tools/bin`) and runs `goimports` for each folder.
-If `goimports` finds files that need fix/format it displays those files as list and the target fails (_exit 1_). -___ - -#### `goimports.display` -In case of `goimports` fails this target can be used to display the necessary changes. It runs `goimports -d` to display the needed changes that can be applied with `make goimports.fix`. -___ - -#### `goimports.fix` -Runs `goimports -w` to fix files (that need fix). -___ - -#### `staticcheck` -Installs (if needed) [staticcheck](https://staticcheck.io/) under `TOOLS_BIN` folder (default is `./.tools/bin`) and runs `staticcheck` using all [checks](https://staticcheck.io/docs/checks) excluding [ST1000](https://staticcheck.io/docs/checks/#ST1000).
-If issues are found the target fails (due to `staticcheck` exit status). -___ - -#### `golangci-lint` -Installs (if needed) [golangci-lint](https://golangci-lint.run/) under `TOOLS_BIN` folder (default is `./.tools/bin`) and runs `golangci-lint`.
-If issues are found the target fails (due to `golangci-lint` exit status). -___ - +## Makefile targets +Makefile targets can be found in [docs/makefile_targets.md](docs/makefile_targets.md) file. diff --git a/api/sample.http b/api/sample.http new file mode 100644 index 0000000..ac345d6 --- /dev/null +++ b/api/sample.http @@ -0,0 +1,34 @@ +GET http://localhost:8888/about +Accept: application/json +Accept-Encoding: gzip, deflate, br + +GET http://localhost:8888/echo +Accept: application/json +Accept-Encoding: gzip, deflate, br +Content-Type: application/json +X-Auth-Key: _Named must your fear be before banish it you can_ +{ + "glossary": { + "title": "example glossary", + "GlossDiv": { + "title": "S", + "GlossList": { + "GlossEntry": { + "ID": "SGML", + "SortAs": "SGML", + "GlossTerm": "Standard Generalized Markup Language", + "Acronym": "SGML", + "Abbrev": "ISO 8879:1986", + "GlossDef": { + "para": "A meta-markup language, used to create markup languages such as DocBook.", + "GlossSeeAlso": [ + "GML", + "XML" + ] + }, + "GlossSee": "markup" + } + } + } + } +} diff --git a/build/build.go b/build/build.go index 6ec715c..1e3bcfe 100644 --- a/build/build.go +++ b/build/build.go @@ -4,7 +4,7 @@ package build // //nolint:gochecknoglobals var ( - Version = "" + Version = "0.0.1" Branch = "" Commit = "" CommitShort = "" diff --git a/build/docker/Dockerfile b/build/docker/Dockerfile index d7b45f0..db33288 100644 --- a/build/docker/Dockerfile +++ b/build/docker/Dockerfile @@ -1,10 +1,10 @@ -# syntax=docker/dockerfile:1.10 +# syntax=docker/dockerfile:1.12 ### https://hub.docker.com/r/docker/dockerfile # https://docs.docker.com/build/guide/mounts/ # https://hub.docker.com/_/golang -FROM --platform=$BUILDPLATFORM golang:1.23.0-alpine3.20 AS builder +FROM --platform=$BUILDPLATFORM golang:1.23.4-alpine3.21 AS builder RUN apk update && apk add --no-cache make git bash ca-certificates WORKDIR /app ARG TARGETOS TARGETARCH @@ -15,7 +15,7 @@ RUN --mount=type=bind,target=. \ #FROM scratch #COPY --from=builder /etc/ssl/certs/ /etc/ssl/certs -FROM alpine:3.20 +FROM alpine:3.21 RUN apk add --no-cache ca-certificates WORKDIR /app COPY --from=builder /tmp/out/* /app/ diff --git a/build/docker/debug.Dockerfile b/build/docker/debug.Dockerfile index 17cc17f..442bc7c 100644 --- a/build/docker/debug.Dockerfile +++ b/build/docker/debug.Dockerfile @@ -1,8 +1,8 @@ -# syntax=docker/dockerfile:1.10 +# syntax=docker/dockerfile:1.12 ### https://hub.docker.com/r/docker/dockerfile # https://hub.docker.com/_/golang -FROM golang:1.23.0-alpine3.20 +FROM golang:1.23.4-alpine3.21 WORKDIR /wd diff --git a/cmd/goboilerplate/main.go b/cmd/goboilerplate/main.go index 47cc8bb..7971b47 100644 --- a/cmd/goboilerplate/main.go +++ b/cmd/goboilerplate/main.go @@ -3,12 +3,13 @@ package main import ( "context" "fmt" + "log/slog" + "os" "github.com/moukoublen/goboilerplate/internal" "github.com/moukoublen/goboilerplate/internal/config" "github.com/moukoublen/goboilerplate/internal/httpx" "github.com/moukoublen/goboilerplate/internal/logx" - "github.com/rs/zerolog/log" ) func defaultConfigs() map[string]any { @@ -31,22 +32,26 @@ func defaultConfigs() map[string]any { } func main() { - cnf, err := config.Load("APP_", defaultConfigs()) + // pre-init slog with default config + logger := logx.InitSLog(logx.Config{LogType: logx.LogTypeText, Level: slog.LevelInfo}) + logger.Info("starting up...") + + cnf, err := config.Load(context.Background(), "APP_", defaultConfigs()) if err != nil { - log.Fatal().Err(err).Send() + logger.Error("error during config init", logx.Error(err)) + os.Exit(1) } - logx.SetupLog(logx.ParseConfig(cnf)) - log.Info().Msgf("Starting up") + logger = logx.InitSLog(logx.ParseConfig(cnf)) daemon, ctx := internal.NewDaemon( context.Background(), + logger, internal.SetShutdownTimeout(cnf.Duration("shutdown_timeout")), ) - _ = ctx httpConf := httpx.ParseConfig(cnf) - router := httpx.NewDefaultRouter(httpConf) + router := httpx.NewDefaultRouter(ctx, httpConf) // init services / application server := httpx.StartListenAndServe( @@ -55,14 +60,14 @@ func main() { httpConf.ReadHeaderTimeout, daemon.FatalErrorsChannel(), ) - log.Info().Msgf("service started at %s:%d", httpConf.IP, httpConf.Port) + logger.InfoContext(ctx, "service started", slog.String("bind", fmt.Sprintf("%s:%d", httpConf.IP, httpConf.Port))) // set onShutdown for other components/services. daemon.OnShutDown( func(ctx context.Context) { - log.Info().Msg("shuting down http server") + logger.InfoContext(ctx, "shuting down http server") if err := server.Shutdown(ctx); err != nil { - log.Warn().Err(err).Msg("error during http server shutdown") + logger.Warn("error during http server shutdown", logx.Error(err)) } }, ) diff --git a/deployments/local/docker-compose.yml b/deployments/local/compose.local.yml similarity index 100% rename from deployments/local/docker-compose.yml rename to deployments/local/compose.local.yml diff --git a/docs/makefile_targets.md b/docs/makefile_targets.md new file mode 100644 index 0000000..f755749 --- /dev/null +++ b/docs/makefile_targets.md @@ -0,0 +1,28 @@ +# Makefile targets + +| Target | Description | +| -------------------- | ----------- | +| `mod` | Runs go mod [tidy](https://go.dev/ref/mod#go-mod-tidy) and [verify](https://go.dev/ref/mod#go-mod-verify). | +| `vendor` | Runs [go mod vendor](https://go.dev/ref/mod#go-mod-vendor) that downloads all dependencies into `./vendor` folder. | +| `go-deps-upgrade` | Runs updates all `go.mod` dependencies. | +| `env` | Prints information regarding the local environment. More specifically: go env, all go packages and folders, and the specified tools bin directory. | +| `git-reset` | Full hard reset to HEAD. Cleans up all untracked files and restore all staged and un-staged changes. | +| `build` | Builds all binaries under `./cmd` (one for each directory) and outputs the binaries into `./output` folder using this pattern: `./cmd/ -> ./output/`. | +| `cmd.` | Builds a specific cmd directory `` and outputs the binary into `./output` folder using this pattern: `./cmd/ -> ./output/`. +| `dbg.` | Builds a specific cmd directory `` (keeping debug symbols) and outputs the binary into `./output` folder using this pattern: `./cmd/ -> ./output/`. +| `clean` | Deletes `./output` folder. +| `compose-up` | Deploys (rebuilds and recreates) the docker compose file `deployments/compose.local.yml` in attached mode. This docker compose file is intended for local development.
It uses the docker file `build/docker/debug.Dockerfile` and runs `air` target (see below), including hot-reload (rebuild on changes) and debug server. +| `compose-down` | Stops (if started) the containers specified by the docker compose file `deployments/compose.local.yml` removes containers, cleans up the volumes and delete local docker images. +| `air` | Installs (if needed) [air](https://github.com/air-verse/air) under `TOOLS_BIN` folder (default is `./.tools/bin`) and runs `air -c .air.toml`.
Air watches for code file changes and rebuilds the binary according to the configuration `.air.toml`.
Current air configuration executes `cmd.goboilerplate` target (on each file change) and then runs the `./build/dlv` that starts the debug server (`dlv exec`) with the produced binary. +| `build-image` | Builds the docker image using the docker file `./build/docker/Dockerfile`.
This docker file is intended to be used as a production image.
Image name and tag are specified by `IMAGE_NAME` and `IMAGE_TAG`. Default values can be overwritten during execution (eg `make IMAGE_NAME=myimage IMAGE_TAG=1.0.0 image`). +| `test` | Runs go [test](https://pkg.go.dev/cmd/go/internal/test) with race conditions and prints cover report. +| `tools` | Installs (if needed) all tools (goimports, staticcheck, gofumpt, etc) under `TOOLS_BIN` folder (default is `./.tools/bin`). +| `checks` | Runs all default checks (`vet`, `staticcheck`, `gofumpt`, `goimports`, `golangci-lint`). +| `vet` | Runs go [vet](https://pkg.go.dev/cmd/vet). +| `gofumpt` | Installs (if needed) [gofumpt](https://github.com/mvdan/gofumpt) under `TOOLS_BIN` folder (default is `./.tools/bin`) and runs `gofumpt` for each folder.
If `gofumpt` finds files that need fix/format it displays those files as list and the target fails (_exit 1_). +| `gofumpt.fix` | Runs `gofumpt -w` to fix/format files (that need fix). +| `goimports` | Installs (if needed) [goimports](https://pkg.go.dev/golang.org/x/tools/cmd/goimports) under `TOOLS_BIN` folder (default is `./.tools/bin`) and runs `goimports` for each folder.
If `goimports` finds files that need fix/format it displays those files as list and the target fails (_exit 1_). +| `goimports.fix` | Runs `goimports -w` to fix files (that need fix). +| `staticcheck` | Installs (if needed) [staticcheck](https://staticcheck.io/) under `TOOLS_BIN` folder (default is `./.tools/bin`) and runs `staticcheck` using all [checks](https://staticcheck.io/docs/checks) excluding [ST1000](https://staticcheck.io/docs/checks/#ST1000).
If issues are found the target fails (due to `staticcheck` exit status). +| `golangci-lint` | Installs (if needed) [golangci-lint](https://golangci-lint.run/) under `TOOLS_BIN` folder (default is `./.tools/bin`) and runs `golangci-lint`.
If issues are found the target fails (due to `golangci-lint` exit status). + diff --git a/go.mod b/go.mod index 2d0274f..4ac5d62 100644 --- a/go.mod +++ b/go.mod @@ -7,26 +7,22 @@ require ( github.com/knadh/koanf/parsers/dotenv v1.0.0 github.com/knadh/koanf/parsers/yaml v0.1.0 github.com/knadh/koanf/providers/confmap v0.1.0 - github.com/knadh/koanf/providers/env v0.1.0 - github.com/knadh/koanf/providers/file v1.1.0 + github.com/knadh/koanf/providers/env v1.0.0 + github.com/knadh/koanf/providers/file v1.1.2 github.com/knadh/koanf/v2 v2.1.1 - github.com/rs/zerolog v1.33.0 github.com/stretchr/testify v1.9.0 ) require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/fsnotify/fsnotify v1.7.0 // indirect - github.com/go-viper/mapstructure/v2 v2.1.0 // indirect + github.com/go-viper/mapstructure/v2 v2.2.1 // indirect github.com/joho/godotenv v1.5.1 // indirect github.com/knadh/koanf/maps v0.1.1 // indirect - github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect - github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/stretchr/objx v0.5.2 // indirect - golang.org/x/sys v0.25.0 // indirect + golang.org/x/sys v0.26.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 8747762..b2a43ff 100644 --- a/go.sum +++ b/go.sum @@ -1,13 +1,11 @@ -github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw= github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= -github.com/go-viper/mapstructure/v2 v2.1.0 h1:gHnMa2Y/pIxElCH2GlZZ1lZSsn6XMtufpGyP1XxdC/w= -github.com/go-viper/mapstructure/v2 v2.1.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= -github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss= +github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/knadh/koanf/maps v0.1.1 h1:G5TjmUh2D7G2YWf5SQQqSiHRJEjaicvU0KpypqB3NIs= @@ -18,42 +16,28 @@ github.com/knadh/koanf/parsers/yaml v0.1.0 h1:ZZ8/iGfRLvKSaMEECEBPM1HQslrZADk8fP github.com/knadh/koanf/parsers/yaml v0.1.0/go.mod h1:cvbUDC7AL23pImuQP0oRw/hPuccrNBS2bps8asS0CwY= github.com/knadh/koanf/providers/confmap v0.1.0 h1:gOkxhHkemwG4LezxxN8DMOFopOPghxRVp7JbIvdvqzU= github.com/knadh/koanf/providers/confmap v0.1.0/go.mod h1:2uLhxQzJnyHKfxG927awZC7+fyHFdQkd697K4MdLnIU= -github.com/knadh/koanf/providers/env v0.1.0 h1:LqKteXqfOWyx5Ab9VfGHmjY9BvRXi+clwyZozgVRiKg= -github.com/knadh/koanf/providers/env v0.1.0/go.mod h1:RE8K9GbACJkeEnkl8L/Qcj8p4ZyPXZIQ191HJi44ZaQ= -github.com/knadh/koanf/providers/file v1.1.0 h1:MTjA+gRrVl1zqgetEAIaXHqYje0XSosxSiMD4/7kz0o= -github.com/knadh/koanf/providers/file v1.1.0/go.mod h1:/faSBcv2mxPVjFrXck95qeoyoZ5myJ6uxN8OOVNJJCI= +github.com/knadh/koanf/providers/env v1.0.0 h1:ufePaI9BnWH+ajuxGGiJ8pdTG0uLEUWC7/HDDPGLah0= +github.com/knadh/koanf/providers/env v1.0.0/go.mod h1:mzFyRZueYhb37oPmC1HAv/oGEEuyvJDA98r3XAa8Gak= +github.com/knadh/koanf/providers/file v1.1.2 h1:aCC36YGOgV5lTtAFz2qkgtWdeQsgfxUkxDOe+2nQY3w= +github.com/knadh/koanf/providers/file v1.1.2/go.mod h1:/faSBcv2mxPVjFrXck95qeoyoZ5myJ6uxN8OOVNJJCI= github.com/knadh/koanf/v2 v2.1.1 h1:/R8eXqasSTsmDCsAyYj+81Wteg8AqrV9CP6gvsTsOmM= github.com/knadh/koanf/v2 v2.1.1/go.mod h1:4mnTRbZCK+ALuBXHZMjDfG9y714L7TykVnZkXbMU3Es= github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19/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/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 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/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8= -github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= -golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= +golang.org/x/sys v0.26.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-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/config/config.go b/internal/config/config.go index 2d39578..b1af8c7 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,6 +1,7 @@ package config import ( + "context" "errors" "io/fs" @@ -10,20 +11,23 @@ import ( "github.com/knadh/koanf/providers/env" "github.com/knadh/koanf/providers/file" "github.com/knadh/koanf/v2" - "github.com/rs/zerolog/log" + "github.com/moukoublen/goboilerplate/internal/logx" ) -func Load(envVarPrefix string, defaultConfigs map[string]any) (*koanf.Koanf, error) { +func Load(ctx context.Context, envVarPrefix string, defaultConfigs map[string]any) (*koanf.Koanf, error) { + logger := logx.GetFromContext(ctx) + const delim = "." k := koanf.New(delim) + // Load default values. if err := k.Load(confmap.Provider(defaultConfigs, delim), nil); err != nil { - log.Warn().Err(err).Msg("error during config loading from defaults") + logger.Debug("error during config loading from defaults", logx.Error(err)) } - // Load JSON config. + // Load YAML config. if err := k.Load(file.Provider("config.yaml"), yaml.Parser()); err != nil { - log.Warn().Err(err).Msg("error during config loading from yaml file") + logger.Debug("error during config loading from yaml file", logx.Error(err)) if !errors.Is(err, fs.ErrNotExist) { return k, err } @@ -35,12 +39,12 @@ func Load(envVarPrefix string, defaultConfigs map[string]any) (*koanf.Koanf, err "log": map[string]any{}, } if err := k.Load(env.Provider(envVarPrefix, delim, buildEnvVarsNamesMapper(envVarsLevels, envVarPrefix)), nil); err != nil { - log.Warn().Err(err).Msg("error during config loading from env vars") + logger.Warn("error during config loading from env vars", logx.Error(err)) } - // Dot env file + // Load .env file if err := k.Load(file.Provider(".env"), dotenv.ParserEnv(envVarPrefix, delim, buildEnvVarsNamesMapper(envVarsLevels, envVarPrefix))); err != nil { - log.Warn().Err(err).Msg("error during config loading from dot env file") + logger.Warn("error during config loading from dot env file", logx.Error(err)) if !errors.Is(err, fs.ErrNotExist) { return k, err } diff --git a/internal/daemon.go b/internal/daemon.go index 838e3bb..c195e32 100644 --- a/internal/daemon.go +++ b/internal/daemon.go @@ -2,14 +2,13 @@ package internal import ( "context" + "fmt" + "log/slog" "os" "os/signal" "sync" "syscall" "time" - - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" ) // Daemon struct wraps tha basic functionality that is needed in order for an application to run daemon/service like and shutdown gracefully when stop conditions are met. @@ -24,6 +23,7 @@ type Daemon struct { signalCh chan os.Signal fatalErrorsCh chan error done chan struct{} + logger *slog.Logger onShutDown []func(context.Context) config daemonConfig onShutDownMutex sync.Mutex @@ -37,9 +37,7 @@ func (o *Daemon) OnShutDown(f ...func(context.Context)) { } func (o *Daemon) shutDown(ctx context.Context) { - logger := zerolog.Ctx(ctx) - - logger.Info().Msg("starting graceful shutdown") + o.logger.Info("starting graceful shutdown") deadline := time.Now().Add(o.config.shutdownTimeout) dlCtx, dlCancel := context.WithDeadline(ctx, deadline) o.onShutDownMutex.Lock() @@ -63,13 +61,12 @@ func (o *Daemon) FatalErrorsChannel() chan<- error { // After a stop conditions is met the `Daemon` will attempt shutdown "gracefully" by running every function that is registered in `onShutDown` slice, sequentially. func (o *Daemon) start(rootCTX context.Context) context.Context { ctx, cnl := context.WithCancel(rootCTX) - logger := zerolog.Ctx(ctx) // consume fatal errors go func() { for err := range o.fatalErrorsCh { // Stop condition (B) fatal error received. - logFatalErr(logger, err) + logFatalErr(o.logger, err) cnl() } }() @@ -80,10 +77,11 @@ func (o *Daemon) start(rootCTX context.Context) context.Context { for sig := range o.signalCh { // Stop condition (A) signal received. sigReceived++ - logSig(logger, sig) + logSig(o.logger, sig) cnl() if sigReceived == o.config.maxSignalCount { - logger.Fatal().Msg("max number of signal received. Terminating immediately") + o.logger.Error("max number of signal received. Terminating immediately") + os.Exit(1) //nolint:revive //its the emergency shut-down situation } } }() @@ -92,14 +90,19 @@ func (o *Daemon) start(rootCTX context.Context) context.Context { select { // Stop condition (C) root context is done. case <-rootCTX.Done(): - logger.Error().Err(rootCTX.Err()).Msg("root context got canceled") + o.logger.Error("root context got canceled", slog.String("error", rootCTX.Err().Error())) cnl() o.shutDown(context.Background()) //nolint:contextcheck return case <-ctx.Done(): - logger.Error().Err(rootCTX.Err()).Msg("context got canceled") + if err := rootCTX.Err(); err != nil { + o.logger.Error("context got canceled", slog.String("error", rootCTX.Err().Error())) + } else { + o.logger.Error("context got canceled") + } + o.shutDown(rootCTX) } }() @@ -109,7 +112,7 @@ func (o *Daemon) start(rootCTX context.Context) context.Context { func (o *Daemon) Wait() { <-o.done - log.Info().Msg("shutdown completed") + o.logger.Info("shutdown completed") } type DaemonConfigOption func(*daemonConfig) @@ -156,7 +159,7 @@ type daemonConfig struct { shutdownTimeout time.Duration } -func NewDaemon(ctx context.Context, opts ...DaemonConfigOption) (*Daemon, context.Context) { +func NewDaemon(ctx context.Context, logger *slog.Logger, opts ...DaemonConfigOption) (*Daemon, context.Context) { cnf := daemonConfig{ signalsNotify: []os.Signal{os.Interrupt, syscall.SIGQUIT, syscall.SIGABRT, syscall.SIGTERM}, maxSignalCount: defaultMaxSignalCount, @@ -176,19 +179,23 @@ func NewDaemon(ctx context.Context, opts ...DaemonConfigOption) (*Daemon, contex fatalErrorsCh: make(chan error, cnf.fatalErrorsChannelBufferSize), done: make(chan struct{}), config: cnf, + logger: logger, } return o, o.start(ctx) } -func logSig(logger *zerolog.Logger, sig os.Signal) { - event := logger.Warn().Str("signal", sig.String()) +func logSig(logger *slog.Logger, sig os.Signal) { + var signalStr string if sigInt, ok := sig.(syscall.Signal); ok { - event.Int("signalNumber", int(sigInt)) + signalStr = fmt.Sprintf("%s %d", sig.String(), int(sigInt)) + } else { + signalStr = sig.String() } - event.Msg("signal received") + + logger.Warn("signal received", slog.String("signal", signalStr)) } -func logFatalErr(logger *zerolog.Logger, err error) { - logger.Error().Err(err).Msg("fatal error received") +func logFatalErr(logger *slog.Logger, err error) { + logger.Error("fatal error received", slog.String("error", err.Error())) } diff --git a/internal/httpx/handlers.go b/internal/httpx/handlers.go new file mode 100644 index 0000000..9df1e98 --- /dev/null +++ b/internal/httpx/handlers.go @@ -0,0 +1,85 @@ +package httpx + +import ( + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/moukoublen/goboilerplate/build" + "github.com/moukoublen/goboilerplate/internal/logx" +) + +func AboutHandler(w http.ResponseWriter, r *http.Request) { + RespondJSON(r.Context(), w, http.StatusOK, build.GetInfo()) +} + +func EchoHandler(w http.ResponseWriter, r *http.Request) { + var cErr error + defer DrainAndCloseRequest(r, &cErr) + + logger := logx.GetFromContext(r.Context()) + + if h := r.Header.Get("X-Auth-Key"); h != `_Named must your fear be before banish it you can_` { + w.WriteHeader(http.StatusUnauthorized) + return + } + + b := map[string]any{} + { + b["method"] = r.Method + b["proto"] = r.Proto + b["protoMajor"] = r.ProtoMajor + b["protoMinor"] = r.ProtoMinor + + if r.URL != nil { + u := map[string]any{} + u["scheme"] = r.URL.Scheme + u["opaque"] = r.URL.Opaque + u["user"] = r.URL.User + u["host"] = r.URL.Host + u["path"] = r.URL.Path + u["rawPath"] = r.URL.RawPath + u["omitHost"] = r.URL.OmitHost + u["forceQuery"] = r.URL.ForceQuery + u["rawQuery"] = r.URL.RawQuery + u["fragment"] = r.URL.Fragment + u["rawFragment"] = r.URL.RawFragment + } + + headers := map[string]string{} + for k := range r.Header { + headers[k] = r.Header.Get(k) + } + b["headers"] = headers + + if ct := r.Header.Get("Content-Type"); strings.Contains(ct, "application/json") { + body := map[string]any{} + _ = json.NewDecoder(r.Body).Decode(&body) + b["body"] = body + } else { + body, _ := io.ReadAll(r.Body) + b["body"] = body + } + + b["contentLength"] = r.ContentLength + b["transferEncoding"] = r.TransferEncoding + b["host"] = r.Host + + trailer := map[string]string{} + for k := range r.Trailer { + trailer[k] = r.Header.Get(k) + } + b["trailer"] = trailer + + b["remoteAddr"] = r.RemoteAddr + b["requestURI"] = r.RequestURI + } + + w.Header().Add("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + err := json.NewEncoder(w).Encode(b) + if err != nil { + logger.Error("error during json encoding", logx.Error(err)) + } +} diff --git a/internal/httpx/inbound.go b/internal/httpx/inbound.go index 7d10a1b..f992899 100644 --- a/internal/httpx/inbound.go +++ b/internal/httpx/inbound.go @@ -1,69 +1,54 @@ package httpx import ( - "bytes" "context" "encoding/json" + "errors" + "io" "net/http" - "time" - "github.com/go-chi/chi/v5/middleware" - "github.com/rs/zerolog" + "github.com/moukoublen/goboilerplate/internal/logx" ) -// RespondJSON renders a json response using a json encoder directly over the ResponseWriter. -// That's why in most cases will end up sending chunked (`transfer-encoding: chunked`) response. -func RespondJSON(ctx context.Context, w http.ResponseWriter, statusCode int, body any) { - w.Header().Add(`Content-Type`, `application/json; charset=utf-8`) - w.WriteHeader(statusCode) - - if body != nil { - if err := json.NewEncoder(w).Encode(body); err != nil { - logger := zerolog.Ctx(ctx) - logger.Error().Err(err).Msg("error during response encoding") - } +// DrainAndCloseRequest can be used (most probably with defer) from the server side to ensure that the http request body is fully consumed and closed. +func DrainAndCloseRequest(r *http.Request, errOut *error) { + if r == nil || r.Body == nil || r.Body == http.NoBody { + return } -} -func NewHTTPInboundLoggerMiddleware(cnf Config) func(http.Handler) http.Handler { - switch cnf.InBoundHTTPLogLevel { - case TrafficLogLevelNone: - return func(h http.Handler) http.Handler { return h } - case TrafficLogLevelBasic: - return middleware.RequestLogger(&ChiZerolog{LogInLevel: cnf.LogInLevel}) - case TrafficLogLevelVerbose: - return RequestResponseLogger(cnf) - } + _, discardErr := io.Copy(io.Discard, r.Body) + closeErr := r.Body.Close() - return func(h http.Handler) http.Handler { return h } + if discardErr != nil || closeErr != nil { + *errOut = errors.Join(*errOut, discardErr, closeErr) + } } -func RequestResponseLogger(cnf Config) func(next http.Handler) http.Handler { - return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - logger := zerolog.Ctx(r.Context()).With().Logger() - - requestDict, requestDictError := dictFromRequest(r) +func ReadJSONRequest(r *http.Request, decodeTo any) (e error) { + if r == nil || r.Body == nil || r.Body == http.NoBody { + return nil + } - responseBodyBuffer := bytes.Buffer{} - wrapResponseWriter := middleware.NewWrapResponseWriter(w, r.ProtoMajor) - wrapResponseWriter.Tee(&responseBodyBuffer) + defer DrainAndCloseRequest(r, &e) - startTime := time.Now() + if err := json.NewDecoder(r.Body).Decode(decodeTo); err != nil { + return err + } - next.ServeHTTP(wrapResponseWriter, r) + return +} - responseDict := dictFromWrapResponseWriter(wrapResponseWriter, startTime, responseBodyBuffer) +// RespondJSON renders a json response using a json encoder directly over the ResponseWriter. +// That's why in most cases will end up sending chunked (`transfer-encoding: chunked`) response. +func RespondJSON(ctx context.Context, w http.ResponseWriter, statusCode int, body any) { + w.Header().Add(`Content-Type`, `application/json; charset=utf-8`) + w.Header().Add(`Cache-Control`, `no-store`) // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control + w.WriteHeader(statusCode) - event := logger.WithLevel(cnf.LogInLevel) - event.Str("url", r.URL.String()) - if requestDictError != nil { - event.AnErr("requestDrainError", requestDictError) - } else { - event.Dict("request", requestDict) - } - event.Dict("response", responseDict) - event.Msg("http transaction completed") - }) + if body != nil { + if err := json.NewEncoder(w).Encode(body); err != nil { + logger := logx.GetFromContext(ctx) + logger.Error("error during response encoding", logx.Error(err)) + } } } diff --git a/internal/httpx/log.go b/internal/httpx/log.go deleted file mode 100644 index 7bd3ef5..0000000 --- a/internal/httpx/log.go +++ /dev/null @@ -1,204 +0,0 @@ -package httpx - -import ( - "bytes" - "fmt" - "io" - "net/http" - "strings" - "time" - - "github.com/go-chi/chi/v5/middleware" - "github.com/rs/zerolog" -) - -type httpHeaderMarshalZerologObject struct { - header http.Header -} - -func (l *httpHeaderMarshalZerologObject) MarshalZerologObject(e *zerolog.Event) { - for k := range l.header { - e.Str(k, l.header.Get(k)) - } -} - -type httpRequestMarshalZerologObject struct { - Request *http.Request -} - -func (rr *httpRequestMarshalZerologObject) MarshalZerologObject(e *zerolog.Event) { - e. - Object("header", &httpHeaderMarshalZerologObject{header: rr.Request.Header}). - Int64("contentLength", rr.Request.ContentLength). - Strs("transferEncoding", rr.Request.TransferEncoding). - Str("host", rr.Request.Host). - Str("remoteAddr", rr.Request.RemoteAddr). - Str("uri", rr.Request.RequestURI). - Str("proto", rr.Request.Proto). - Str("method", rr.Request.Method). - Str("url", requestURL(rr.Request)) -} - -type httpResponseMarshalZerologObject struct { - Response *http.Response -} - -func (rr *httpResponseMarshalZerologObject) MarshalZerologObject(e *zerolog.Event) { - e. - Object("header", &httpHeaderMarshalZerologObject{header: rr.Response.Header}). - Str("status", rr.Response.Status). - Int("statusCode", rr.Response.StatusCode). - Str("proto", rr.Response.Proto). - Int64("contentLength", rr.Response.ContentLength). - Strs("transferEncoding", rr.Response.TransferEncoding) -} - -type httpWrapResponseWriterMarshalZerologObject struct { - ResponseWriter middleware.WrapResponseWriter -} - -func (rr *httpWrapResponseWriterMarshalZerologObject) MarshalZerologObject(e *zerolog.Event) { - e. - Object("header", &httpHeaderMarshalZerologObject{header: rr.ResponseWriter.Header()}). - Int("statusCode", rr.ResponseWriter.Status()). - Int("bytesWritten", rr.ResponseWriter.BytesWritten()) -} - -type ChiZerolog struct { - LogInLevel zerolog.Level -} - -// NewLogEntry implements chi LogFormatter NewLogEntry function. -// -//nolint:ireturn -func (c *ChiZerolog) NewLogEntry(r *http.Request) middleware.LogEntry { - logger := zerolog.Ctx(r.Context()) - - if logger.GetLevel() > c.LogInLevel { - return chiNopLogEntry{} - } - - entry := &chiZerologEntry{ - logEvent: logger.WithLevel(c.LogInLevel), //nolint:zerologlint // indented behavior. - logger: logger, - } - - entry.logEvent.Str("request_id", middleware.GetReqID(r.Context())) - entry.logEvent.EmbedObject(&httpRequestMarshalZerologObject{Request: r}) - - return entry -} - -type chiZerologEntry struct { - logEvent *zerolog.Event - logger *zerolog.Logger -} - -func (e *chiZerologEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra any) { - e.logEvent. - Int("status_code", status). - Str("status", http.StatusText(status)). - Int("bytes", bytes). - Dur("elapsed", elapsed). - Interface("extra", extra). - Object("responseHeaders", &httpHeaderMarshalZerologObject{header: header}). - Msg("http call") -} - -func (e *chiZerologEntry) Panic(v any, stack []byte) { - s := strings.Split(string(stack), "\n") - for i := range s { - s[i] = strings.ReplaceAll(s[i], "\t", " ") - } - - e.logger.Error(). - Interface("panic", v). - Strs("stack", s). - Msg("http call paniced") -} - -type chiNopLogEntry struct{} - -func (e chiNopLogEntry) Write(_, _ int, _ http.Header, _ time.Duration, _ any) {} -func (e chiNopLogEntry) Panic(_ any, _ []byte) {} - -func requestURL(r *http.Request) string { - scheme := "http" - if r.TLS != nil { - scheme = "https" - } - - return fmt.Sprintf("%s://%s%s %s", scheme, r.Host, r.RequestURI, r.Proto) -} - -func dictFromWrapResponseWriter(w middleware.WrapResponseWriter, startTime time.Time, responseBodyBuffer bytes.Buffer) *zerolog.Event { - dict := zerolog.Dict() - dict.EmbedObject(&httpWrapResponseWriterMarshalZerologObject{ResponseWriter: w}) - dict.Dur("duration", time.Since(startTime)) - - if logBody(w.Header()) { - dict.RawJSON("payload", sanitizeJSONBytesToLog(responseBodyBuffer.Bytes())) - } - - return dict -} - -func dictFromRequest(r *http.Request) (*zerolog.Event, error) { - body, payloadBytes, err := drainBody(r.Body) - if err != nil { - return nil, err - } - - r.Body = body - - dict := zerolog.Dict() - dict.EmbedObject(&httpRequestMarshalZerologObject{Request: r}) - - if logBody(r.Header) { - dict.RawJSON("payload", sanitizeJSONBytesToLog(payloadBytes)) - } - - return dict, nil -} - -func logBody(h http.Header) bool { - contentType := h.Get("Content-Type") - contentEncoding := h.Get("Content-Encoding") - return strings.Contains(contentType, `application/json`) && len(contentEncoding) == 0 -} - -func sanitizeJSONBytesToLog(b []byte) []byte { - return bytes.ReplaceAll( - bytes.ReplaceAll( - b, - []byte("\t"), - []byte{}, - ), - []byte("\n"), - []byte{}, - ) -} - -// drainBody reads all of b to memory and then returns two equivalent -// ReadClosers yielding the same bytes. -// -// It returns an error if the initial slurp of all bytes fails. It does not attempt -// to make the returned ReadClosers have identical error-matching behavior. -// Source: https://go.dev/src/net/http/httputil/dump.go -func drainBody(b io.ReadCloser) (io.ReadCloser, []byte, error) { - if b == nil || b == http.NoBody { - // No copying needed. Preserve the magic sentinel meaning of NoBody. - return http.NoBody, nil, nil - } - - var buf bytes.Buffer - if _, err := buf.ReadFrom(b); err != nil { - return nil, nil, err - } - - if err := b.Close(); err != nil { - return nil, nil, err - } - - return io.NopCloser(&buf), buf.Bytes(), nil -} diff --git a/internal/httpx/mock_inner_client_test.go b/internal/httpx/mock_inner_client_test.go index c18d79a..b2f7e78 100644 --- a/internal/httpx/mock_inner_client_test.go +++ b/internal/httpx/mock_inner_client_test.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.45.1. DO NOT EDIT. +// Code generated by mockery v2.46.2. DO NOT EDIT. package httpx diff --git a/internal/httpx/outbound.go b/internal/httpx/outbound.go index a2dcf51..d9b5286 100644 --- a/internal/httpx/outbound.go +++ b/internal/httpx/outbound.go @@ -3,53 +3,40 @@ package httpx import ( "compress/flate" "compress/gzip" - "context" "encoding/json" + "errors" "fmt" "io" "net" "net/http" "time" - - "github.com/rs/zerolog" ) // DrainAndCloseResponse can be used (most probably with defer) from the client side to ensure that the http response body is consumed til the end and closed. -func DrainAndCloseResponse(res *http.Response) { - if res == nil || res.Body == nil { +func DrainAndCloseResponse(res *http.Response, errOut *error) { + if res == nil || res.Body == nil || res.Body == http.NoBody { return } - _, _ = io.Copy(io.Discard, res.Body) - _ = res.Body.Close() -} + _, discardErr := io.Copy(io.Discard, res.Body) + closeErr := res.Body.Close() -type InnerClient interface { - Do(req *http.Request) (*http.Response, error) + if discardErr != nil || closeErr != nil { + *errOut = errors.Join(*errOut, discardErr, closeErr) + } } -// Client wraps an http.Client and offers `DoAndDecode` as an extra function. -type Client struct { - InnerClient +type HTTPClient interface { + Do(req *http.Request) (*http.Response, error) } -// DoAndDecode performs the request (req) and tries to json decodes the response to output, it handles gzip and flate compression and also logs in debug level the http transaction (request/response). -func (c *Client) DoAndDecode(ctx context.Context, req *http.Request, output any) error { - start := time.Now() - +// DoAndDecode performs the request (req) and tries to json decodes the response to output, it handles gzip and flate compression. +func DoAndDecode(c HTTPClient, req *http.Request, output any) (er error) { res, err := c.Do(req) if err != nil { return err } - defer DrainAndCloseResponse(res) - - defer func() { - zerolog.Ctx(ctx).Debug(). - Dur("duration", time.Since(start)). - Object("request", &httpRequestMarshalZerologObject{Request: req}). - Object("response", &httpResponseMarshalZerologObject{Response: res}). - Msg("outbound traffic") - }() + defer DrainAndCloseResponse(res, &er) if res.StatusCode >= http.StatusBadRequest { return NewStatusCodeError(res.StatusCode) diff --git a/internal/httpx/router.go b/internal/httpx/router.go index 36b6d82..afd034c 100644 --- a/internal/httpx/router.go +++ b/internal/httpx/router.go @@ -1,7 +1,9 @@ package httpx import ( + "context" "errors" + "log/slog" "net/http" "strings" "time" @@ -9,41 +11,19 @@ import ( "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/knadh/koanf/v2" - "github.com/moukoublen/goboilerplate/build" - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" -) - -type TrafficLogLevel int16 - -const ( - TrafficLogLevelNone TrafficLogLevel = 0 - TrafficLogLevelBasic TrafficLogLevel = 1 - TrafficLogLevelVerbose TrafficLogLevel = 2 -) - -// Default configuration values. -const ( - defaultInboundTrafficLogLevel = 2 - defaultOutboundTrafficLogLevel = 2 + "github.com/moukoublen/goboilerplate/internal/logx" ) func DefaultConfigValues() map[string]any { return map[string]any{ - "http.ip": "0.0.0.0", - "http.port": "43000", - "http.inbound_traffic_log_level": defaultInboundTrafficLogLevel, - "http.outbound_traffic_log_level": defaultOutboundTrafficLogLevel, - "http.log_in_level": 0, + "http.ip": "0.0.0.0", + "http.port": "8888", } } type Config struct { IP string - Port int32 - InBoundHTTPLogLevel TrafficLogLevel - OutBoundHTTPLogLevel TrafficLogLevel - LogInLevel zerolog.Level + Port int64 GlobalInboundTimeout time.Duration ReadHeaderTimeout time.Duration } @@ -51,27 +31,20 @@ type Config struct { func ParseConfig(cnf *koanf.Koanf) Config { return Config{ IP: cnf.String("http.ip"), - Port: int32(cnf.Int64("http.port")), - InBoundHTTPLogLevel: TrafficLogLevel(cnf.Int64("http.inbound_traffic_log_level")), - OutBoundHTTPLogLevel: TrafficLogLevel(cnf.Int64("http.outbound_traffic_log_level")), - LogInLevel: zerolog.Level(cnf.Int64("http.log_in_level")), + Port: cnf.Int64("http.port"), GlobalInboundTimeout: cnf.Duration("http.global_inbound_timeout"), ReadHeaderTimeout: cnf.Duration("http.read_header_timeout"), } } // NewDefaultRouter returns a *chi.Mux with a default set of middlewares and an "/about" route. -func NewDefaultRouter(c Config) *chi.Mux { +func NewDefaultRouter(ctx context.Context, c Config) *chi.Mux { router := chi.NewRouter() router.Use(middleware.Heartbeat("/ping")) router.Use(middleware.RequestID) router.Use(middleware.RealIP) - if c.InBoundHTTPLogLevel > TrafficLogLevelNone { - router.Use(NewHTTPInboundLoggerMiddleware(c)) - } - router.Use(middleware.Recoverer) if c.GlobalInboundTimeout > 0 { @@ -79,17 +52,19 @@ func NewDefaultRouter(c Config) *chi.Mux { } router.Get("/about", AboutHandler) + router.Get("/echo", EchoHandler) // for test purposes // router.Get("/panic", func(_ http.ResponseWriter, _ *http.Request) { panic("test panic") }) - LogRoutes(router) + LogRoutes(ctx, router) return router } -func LogRoutes(r *chi.Mux) { - if log.Logger.GetLevel() > zerolog.DebugLevel { +func LogRoutes(ctx context.Context, r *chi.Mux) { + logger := logx.GetFromContext(ctx) + if !logger.Enabled(ctx, slog.LevelDebug) { return } @@ -103,16 +78,12 @@ func LogRoutes(r *chi.Mux) { } if err := chi.Walk(r, walkFunc); err != nil { - log.Error().Err(err).Msg("error during chi walk") + logger.Error("error during chi walk", logx.Error(err)) } else { - log.Debug().Strs("routes", routes).Msg("http routes") + logger.Debug("http routes", slog.Any("routes", routes)) } } -func AboutHandler(w http.ResponseWriter, r *http.Request) { - RespondJSON(r.Context(), w, http.StatusOK, build.GetInfo()) -} - // StartListenAndServe creates and runs server.ListenAndServe in a separate go routine. // Any error produced by ListenAndServe will be sent to fatalErrCh. // It returns the server struct. diff --git a/internal/logx/log.go b/internal/logx/log.go index 4c1d9f8..1df0e6d 100644 --- a/internal/logx/log.go +++ b/internal/logx/log.go @@ -1,61 +1,110 @@ package logx import ( - "io" + "context" + "log/slog" "os" - "time" "github.com/knadh/koanf/v2" - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" - "github.com/rs/zerolog/pkgerrors" ) -func DefaultConfigValues() map[string]any { - return map[string]any{ - "log.console_writer": false, - "log.level": 0, - } -} +type LogType string + +const ( + LogTypeJSON LogType = "json" + LogTypeText LogType = "text" +) type Config struct { - ConsoleWriter bool - LogLevel zerolog.Level + LogType LogType + Level slog.Level } func ParseConfig(cnf *koanf.Koanf) Config { + level := slog.Level(0) + levelStr := cnf.Bytes("log.level") + err := level.UnmarshalText(levelStr) + _ = err + return Config{ - ConsoleWriter: cnf.Bool("log.console_writer"), - LogLevel: zerolog.Level(cnf.Int("log.level")), + Level: level, + LogType: LogType(cnf.String("log.type")), } } -func newDefaultLogger(l zerolog.Level, w io.Writer) zerolog.Logger { - zerolog.SetGlobalLevel(l) - zerolog.TimeFieldFormat = time.RFC3339 +func DefaultConfigValues() map[string]any { + return map[string]any{ + "log.type": "text", + "log.level": "INFO", + } +} + +//nolint:gochecknoglobals +var logLevel = &slog.LevelVar{} + +func SetLogLevel(l slog.Level) { + slog.SetLogLoggerLevel(l) + logLevel.Set(l) +} + +func InitSLog(c Config, attrs ...slog.Attr) *slog.Logger { + SetLogLevel(c.Level) - //nolint: reassign - zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack - // zerolog.ErrorMarshalFunc + opts := &slog.HandlerOptions{ + AddSource: true, + Level: logLevel, + } - logger := zerolog.New(w).With(). - Stack(). - Timestamp(). - Caller(). - Logger() + var slogHandler slog.Handler + switch c.LogType { //nolint:exhaustive + case LogTypeJSON: + slogHandler = slog.NewJSONHandler(os.Stdout, opts) + default: // fallback to text + slogHandler = slog.NewTextHandler(os.Stdout, opts) + } + + logger := slog.New(slogHandler.WithAttrs(attrs)) + + slog.SetDefault(logger) + + logger.Debug("logger initialized", slog.String("level", c.Level.String())) return logger } -func SetupLog(c Config) { - var w io.Writer - if c.ConsoleWriter { - w = zerolog.ConsoleWriter{Out: os.Stdout} - } else { - w = os.Stdout +type ctxSLogKey struct{} + +func GetFromContext(ctx context.Context) *slog.Logger { + if logger, ok := ctx.Value(ctxSLogKey{}).(*slog.Logger); ok { + return logger + } + + return slog.Default() +} + +func SetInContext(ctx context.Context, logger *slog.Logger) context.Context { + return context.WithValue(ctx, ctxSLogKey{}, logger) +} + +type NOOPLogHandler struct{} + +func (NOOPLogHandler) Enabled(context.Context, slog.Level) bool { return false } +func (NOOPLogHandler) Handle(context.Context, slog.Record) error { return nil } +func (l NOOPLogHandler) WithAttrs(_ []slog.Attr) slog.Handler { return l } +func (l NOOPLogHandler) WithGroup(_ string) slog.Handler { return l } + +func Error(err error) slog.Attr { + if err == nil { + return slog.Attr{} + } + + return slog.String("error", err.Error()) +} + +func AnError(key string, err error) slog.Attr { + if err == nil { + return slog.Attr{} } - zerolog.SetGlobalLevel(c.LogLevel) - log.Logger = newDefaultLogger(c.LogLevel, w) - zerolog.DefaultContextLogger = &log.Logger + return slog.String(key, err.Error()) } diff --git a/internal/mock_daemon_config_option_test.go b/internal/mock_daemon_config_option_test.go index e46cb46..a0b602c 100644 --- a/internal/mock_daemon_config_option_test.go +++ b/internal/mock_daemon_config_option_test.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.45.1. DO NOT EDIT. +// Code generated by mockery v2.46.2. DO NOT EDIT. package internal diff --git a/pkg/testingx/testing.go b/pkg/testingx/testing.go new file mode 100644 index 0000000..6eb11c4 --- /dev/null +++ b/pkg/testingx/testing.go @@ -0,0 +1,332 @@ +package testingx + +import ( + "errors" + "fmt" + "io" + "math" + "reflect" + "strconv" + "strings" + "testing" + "time" +) + +func AssertError(t *testing.T, assertErrFn func(*testing.T, error), err error) { + t.Helper() + switch { + case err != nil && assertErrFn != nil: + assertErrFn(t, err) + case err != nil && assertErrFn == nil: + t.Errorf("unexpected error returned.\nError: %T(%s)", err, err.Error()) + case err == nil && assertErrFn != nil: + t.Errorf("expected error but none received") + } +} + +func ExpectedErrorChecks(expected ...func(*testing.T, error)) func(*testing.T, error) { + return func(t *testing.T, err error) { + t.Helper() + for _, fn := range expected { + fn(t, err) + } + } +} + +func ExpectedErrorIs(allExpectedErrors ...error) func(*testing.T, error) { + return func(t *testing.T, err error) { + t.Helper() + for _, expected := range allExpectedErrors { + if is := errors.Is(err, expected); !is { + t.Errorf("error unexpected.\nExpected error: %T(%s) \nGot : %T(%s)", expected, expected.Error(), err, err.Error()) + } + } + } +} + +func ExpectedErrorIsOfType(expected error) func(*testing.T, error) { + return func(t *testing.T, err error) { + t.Helper() + if !errorIsOfType(err, expected) { + t.Errorf("Error type check failed.\nExpected error type: %T\nGot : %T(%s)", expected, err, err) + } + } +} + +func errorIsOfType(err, expected error) bool { + expectedType := reflect.TypeOf(expected) + return atLeastOneError(err, func(e error) bool { + tp := reflect.TypeOf(e) + return tp == expectedType + }) +} + +func atLeastOneError(err error, check func(error) bool) bool { + if err == nil { + return false + } + + if check(err) { + return true + } + + switch x := err.(type) { //nolint:errorlint + case interface{ Unwrap() error }: + return atLeastOneError(x.Unwrap(), check) + case interface{ Unwrap() []error }: + for _, err := range x.Unwrap() { + if atLeastOneError(err, check) { + return true + } + } + + return false + } + + return false +} + +func ExpectedErrorStringContains(s string) func(*testing.T, error) { + return func(t *testing.T, err error) { + t.Helper() + if !strings.Contains(err.Error(), s) { + t.Errorf("error string check failed. \nExpected to contain: %s\nGot : %s\n", s, err.Error()) + } + } +} + +func AssertEqualFn(t *testing.T) func(subject, expected any) { + t.Helper() + return func(subject, expected any) { + t.Helper() + AssertEqual(t, subject, expected) + } +} + +func AssertEqual(t *testing.T, subject, expected any) { + t.Helper() + if expectedErr, is := expected.(error); is { + gotErr, _ := subject.(error) + if errors.Is(expectedErr, gotErr) { + t.Errorf("Expected error mismatch:\nExpected: %s\nGot : %s", Format(expectedErr), Format(gotErr)) + } + + return + } + + subjectType := reflect.TypeOf(subject) + expectedType := reflect.TypeOf(expected) + + if subjectType != expectedType { + t.Errorf("Expected types mismatch:\nExpected: %s\nGot : %s", expectedType.String(), subjectType.String()) + } + + compFn := compareFn(expected) + if !compFn(subject, expected) { + t.Errorf("Expected value mismatch:\nExpected: %s\nGot : %s", Format(expected), Format(subject)) + } +} + +func compareFn(expected any) func(any, any) bool { + switch expected.(type) { + case float32: + return CompareFloat32 + case float64: + return CompareFloat64 + case time.Time: + return CompareTime + case []float32: + return CompareSlicesFn[float32](CompareFloat32) + case []float64: + return CompareSlicesFn[float64](CompareFloat64) + case []time.Time: + return CompareSlicesFn[time.Time](CompareTime) + default: + return reflect.DeepEqual + } +} + +func Format(a any) string { + var val string + switch t := a.(type) { + case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: + val = fmt.Sprintf("%d", a) + case string: + val = t + case bool: + val = strconv.FormatBool(t) + case float32, float64: + val = fmt.Sprintf("%g", a) + case time.Time: + val = t.Format(time.RFC3339Nano) + case []int, []int8, []int16, []int32, []int64, []uint, []uint8, []uint16, []uint32, []uint64: + val = formatSlice(t, Format) + case []float32, []float64: + val = formatSlice(t, Format) + case []bool: + val = formatSlice(t, Format) + case []string: + val = formatSlice(t, Format) + case []any: + val = formatSlice(t, Format) + default: + val = fmt.Sprintf("%#v", a) + } + + return fmt.Sprintf("%T(%s)", a, val) +} + +func formatSlice(sl any, elementFormatFn func(any) string) string { + s := strings.Builder{} + s.WriteRune('[') + + value := reflect.ValueOf(sl) + for i := range value.Len() { + item := value.Index(i) + ifc := item.Interface() + if i != 0 { + s.WriteRune(',') + } + s.WriteString(elementFormatFn(ifc)) + } + + s.WriteRune(']') + + return s.String() +} + +func CompareFloat64(a, b any) bool { + var ( + fx float64 + fy float64 + isFloat bool + ) + fx, isFloat = a.(float64) + if !isFloat { + return false + } + fy, isFloat = b.(float64) + if !isFloat { + return false + } + + if math.IsInf(fx, 1) && math.IsInf(fy, 1) { + return true + } + + if math.IsInf(fx, -1) && math.IsInf(fy, -1) { + return true + } + + const thr = float64(1e-10) + + return math.Abs(fx-fy) <= thr +} + +func CompareFloat32(a, b any) bool { + var ( + fx float32 + fy float32 + isFloat bool + ) + fx, isFloat = a.(float32) + if !isFloat { + return false + } + fy, isFloat = b.(float32) + if !isFloat { + return false + } + + return CompareFloat64(float64(fx), float64(fy)) +} + +func CompareTime(x, y any) bool { + var t1, t2 time.Time + var isTime bool + t1, isTime = x.(time.Time) + if !isTime { + return false + } + t2, isTime = y.(time.Time) + if !isTime { + return false + } + + s1 := t1.Format(time.RFC3339Nano) + s2 := t2.Format(time.RFC3339Nano) + + return s1 == s2 // t1.Equal(t2) +} + +func CompareSlicesFn[T any](compareFn func(any, any) bool) func(x, y any) bool { + return func(x, y any) bool { + var ( + sx, sy []T + isSlice bool + ) + sx, isSlice = x.([]T) + if !isSlice { + return false + } + sy, isSlice = y.([]T) + if !isSlice { + return false + } + + if len(sx) != len(sy) { + return false + } + + for i := range sx { + if !compareFn(sx[i], sy[i]) { + return false + } + } + + return true + } +} + +func ReadAndClose(t *testing.T, body io.ReadCloser) []byte { + t.Helper() + + defer func() { + if body == nil { + return + } + err := body.Close() + if err != nil { + t.Errorf("error while closing body: %s", err.Error()) + } + }() + + b, err := io.ReadAll(body) + if err != nil { + t.Fatalf("error while reading body: %s", err.Error()) + } + + return b +} + +func AssertPartialEqualMap(t *testing.T, subject, expected map[string]any) { + t.Helper() + + for expectedKey, expectedValue := range expected { + gotValue, exists := subject[expectedKey] + + if !exists { + t.Errorf("missing field %s", expectedKey) + continue + } + + if asMap, is := expectedValue.(map[string]any); is { + if subjectAsMap, subIs := gotValue.(map[string]any); subIs { + AssertPartialEqualMap(t, subjectAsMap, asMap) + continue + } + } + + AssertEqual(t, gotValue, expectedValue) + } +} diff --git a/scripts/docker.mk b/scripts/docker.mk new file mode 100644 index 0000000..6cca4b0 --- /dev/null +++ b/scripts/docker.mk @@ -0,0 +1,52 @@ +DOCKER_EXEC ?= docker +export DOCKER_EXEC + +IMAGE_NAME ?= goboilerplate +IMAGE_TAG ?= latest + +## https://docs.docker.com/reference/cli/docker/buildx/build/ +## --output='type=docker' +## --output='type=image,push=true' +## --platform=linux/arm64 +## --platform=linux/amd64,linux/arm64,linux/arm/v7 +## --platform=local +## --progress='plain' +## make DOCKER_BUILD_PLATFORM=linux/arm64 image +DOCKER_BUILD_PLATFORM ?= local +DOCKER_BUILD_OUTPUT ?= type=docker +.PHONY: build-image +build-image: + $(DOCKER_EXEC) buildx build \ + --output='type=docker' \ + --file='$(CURDIR)/build/docker/Dockerfile' \ + --tag='$(IMAGE_NAME):$(IMAGE_TAG)' \ + --platform='$(DOCKER_BUILD_PLATFORM)' \ + --output='$(DOCKER_BUILD_OUTPUT)' \ + . + +DOCKER_COMPOSE_EXEC ?= $(DOCKER_EXEC) compose -f $(CURDIR)/deployments/compose.local.yml + +.PHONY: compose-up +compose-up: + $(DOCKER_COMPOSE_EXEC) up --force-recreate --build + +.PHONY: compose-up-detach +compose-up-detach: + $(DOCKER_COMPOSE_EXEC) up --force-recreate --build --detach + +.PHONY: compose-down +compose-down: + $(DOCKER_COMPOSE_EXEC) down --volumes --rmi local --remove-orphans + +# If the first target is "compose-exec" +# remove the first argument 'compose-exec' and store the rest in DOCKER_COMPOSE_ARGS +# and ignore the subsequent arguments as make targets. +# (using spaces for indentation) +ifeq (compose-exec,$(firstword $(MAKECMDGOALS))) + DOCKER_COMPOSE_ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS)) + $(eval $(DOCKER_COMPOSE_ARGS):;@:) +endif + +.PHONY: compose-exec +compose-exec: + $(DOCKER_COMPOSE_EXEC) exec $(DOCKER_COMPOSE_ARGS) diff --git a/scripts/foreach-script b/scripts/foreach-script new file mode 100755 index 0000000..0214eda --- /dev/null +++ b/scripts/foreach-script @@ -0,0 +1,37 @@ +#!/usr/bin/env bash + +# https://man7.org/linux/man-pages/man1/find.1.html +# https://linux.die.net/man/1/find +# https://ss64.com/mac/find.html + +# set -e +# set -u +# set -o pipefail + +VERBOSE=${VERBOSE:="0"} + +__is_file_bash_or_sh() { + [[ ${1} == *.bash || ${1} == *.sh ]] || + file "${1}" | grep -qE 'POSIX shell script|Bourne-Again shell script|bash script|sh script' +} + +mapfile -d '' -t files < <( + find ./ \ + -type f \ + -and \( -not -path './.git/*' \) \ + -and \( -not -path './.tools/*' \) \ + -and \( -not -path './vendor/*' \) \ + -and \( -name '*.bash' -or -name '*.sh' -or -perm /111 \) \ + -print0 +) + +status=0 + +for file in "${files[@]}"; do + if __is_file_bash_or_sh "${file}"; then + [[ ${VERBOSE} == "1" ]] && echo "${*} ${file}" + "${@}" "${file}" || status=1 + fi +done + +exit ${status} diff --git a/scripts/git-check-dirty b/scripts/git-check-dirty index 3009750..3970c46 100755 --- a/scripts/git-check-dirty +++ b/scripts/git-check-dirty @@ -4,8 +4,9 @@ set -e # https://git-scm.com/docs/git-status -if [ -n "$(git status --porcelain)" ]; then - echo "new or modified files" +if ! git diff --exit-code >/dev/null; then + echo "" + echo "**New or modified files**" echo "" git status --short --branch --untracked-files=all --ahead-behind diff --git a/scripts/go.mk b/scripts/go.mk new file mode 100644 index 0000000..b4c347c --- /dev/null +++ b/scripts/go.mk @@ -0,0 +1,79 @@ +GO_EXEC ?= go +export GO_EXEC + +REPO_GIT_BRANCH = $(shell git rev-parse --abbrev-ref HEAD 2>/dev/null || true) +REPO_GIT_COMMIT = $(shell git rev-parse HEAD 2>/dev/null || true) +REPO_GIT_COMMIT_SHORT = $(shell git rev-parse --short HEAD 2>/dev/null || true) +REPO_GIT_TAG = $(shell git describe --tags 2>/dev/null || true) + +MODULE := $(shell cat go.mod | grep -e "^module" | sed "s/^module //") +X_FLAGS = \ + -X '$(MODULE)/build.Branch=$(REPO_GIT_BRANCH)' \ + -X '$(MODULE)/build.Commit=$(REPO_GIT_COMMIT)' \ + -X '$(MODULE)/build.CommitShort=$(REPO_GIT_COMMIT_SHORT)' \ + -X '$(MODULE)/build.Tag=$(REPO_GIT_TAG)' + +GO_PACKAGES = $(GO_EXEC) list -tags='$(TAGS)' -mod=vendor ./... +GO_FOLDERS = $(GO_EXEC) list -tags='$(TAGS)' -mod=vendor -f '{{ .Dir }}' ./... +GO_FILES = find . -type f -name '*.go' -not -path './vendor/*' + +export GO111MODULE := on +#export GOFLAGS := -mod=vendor +GOPATH := $(shell go env GOPATH) +GO_VER := $(shell go env GOVERSION) +BUILD_OUTPUT ?= $(CURDIR)/output + + +.PHONY: mod +mod: + $(GO_EXEC) mod tidy -go=1.23 + $(GO_EXEC) mod verify + +.PHONY: vendor +vendor: + $(GO_EXEC) mod vendor + +# https://go.dev/ref/mod#go-get +# -u flag tells go get to upgrade modules +# -t flag tells go get to consider modules needed to build tests of packages named on the command line. +# When -t and -u are used together, go get will update test dependencies as well. +.PHONY: go-deps-upgrade +go-deps-upgrade: + $(GO_EXEC) get -u -t ./... + $(GO_EXEC) mod tidy -go=1.23 + $(GO_EXEC) mod vendor + +# https://pkg.go.dev/cmd/go#hdr-Compile_packages_and_dependencies +# https://pkg.go.dev/cmd/compile +# https://pkg.go.dev/cmd/link + +#BUILD_FLAGS := -mod=vendor -a -ldflags "-s -w $(X_FLAGS) -extldflags='-static'" -tags '$(TAGS)' +BUILD_FLAGS := -mod=vendor -a -ldflags '-s -w $(X_FLAGS)' -tags '$(TAGS)' +BUILD_FLAGS_DEBUG := -mod=vendor -ldflags '$(X_FLAGS)' -tags '$(TAGS)' + +cmd.%: CMDNAME=$* +cmd.%: + $(GO_EXEC) env + @echo '' + CGO_ENABLED=0 $(GO_EXEC) build $(BUILD_FLAGS) -o $(BUILD_OUTPUT)/$(CMDNAME) ./cmd/$(CMDNAME) + +dbg.%: BUILD_FLAGS=$(BUILD_FLAGS_DEBUG) +dbg.%: cmd.% + @echo "debug binary done" + +.PHONY: build +build: $(shell ls -d cmd/* | sed -e 's/\//./') + +.PHONY: clean +clean: + rm -rf $(BUILD_OUTPUT) + +.PHONY: test +test: + CGO_ENABLED=1 $(GO_EXEC) test -timeout 60s -race -tags="$(TAGS)" -coverprofile cover.out -covermode atomic ./... + @$(GO_EXEC) tool cover -func cover.out + @rm cover.out + +.PHONY: run +run: + $(GO_EXEC) run -mod=vendor ./cmd/goboilerplate diff --git a/scripts/install-protoc b/scripts/install-protoc index ebf41ca..fdcc480 100755 --- a/scripts/install-protoc +++ b/scripts/install-protoc @@ -22,18 +22,17 @@ arch() { uname -m | tr '[:upper:]' '[:lower:]' } - VERSION="" DESTINATION_DIR="" UNKNOWN_ARGS=() while (($#)); do case "${1}" in - -v|--version) + -v | --version) VERSION="${2}" shift 2 ;; - -d|--destination) + -d | --destination) DESTINATION_DIR="${2}" shift 2 ;; @@ -44,13 +43,13 @@ while (($#)); do esac done -if [[ "${VERSION}" == "" ]]; then +if [[ ${VERSION} == "" ]]; then VERSION="$(get_protoc_latest_version)" fi VERSION="$(echo "${VERSION}" | sed 's/^v//g')" -if [[ "${DESTINATION_DIR}" == "" ]]; then +if [[ ${DESTINATION_DIR} == "" ]]; then echo "missing destination argument" exit 1 fi @@ -62,7 +61,7 @@ rm -rf "${DESTINATION_DIR}"/include/google/protobuf # https://github.com/protocolbuffers/protobuf/releases/download/v22.3/protoc-22.3-linux-x86_64.zip DL_URL="https://github.com/protocolbuffers/protobuf/releases/download/v${VERSION}/protoc-${VERSION}-$(os)-$(arch).zip" -curl ${CURL_SHOW_ERROR} \ +curl "${CURL_SHOW_ERROR}" \ --silent \ --fail \ --location \ diff --git a/scripts/install-shellcheck b/scripts/install-shellcheck new file mode 100755 index 0000000..9affe4e --- /dev/null +++ b/scripts/install-shellcheck @@ -0,0 +1,99 @@ +#!/usr/bin/env bash + +set -e +#set -u +set -o pipefail + +get_protoc_latest_version() { + JS_BODY=$(curl --silent --fail --location "https://api.github.com/repos/koalaman/shellcheck/releases/latest") + echo "${JS_BODY}" | jq '.tag_name' --raw-output +} + +package_os() { + case "$(uname)" in + "Darwin") + echo "darwin" + ;; + "Linux") + echo "linux" + ;; + *) + echo "" + ;; + esac +} + +package_arch() { + local arch + arch="$(uname -m | tr '[:upper:]' '[:lower:]')" + case "${arch}" in + "x86_64") + echo "x86_64" + ;; + "aarch64") + echo "aarch64" + ;; + "arm64") + echo "aarch64" + ;; + *) + echo "" + ;; + esac +} + +VERSION="" +DESTINATION_DIR="" + +UNKNOWN_ARGS=() +while (($#)); do + case "${1}" in + -v | --version) + VERSION="${2}" + shift 2 + ;; + -d | --destination) + DESTINATION_DIR="${2}" + shift 2 + ;; + *) + UNKNOWN_ARGS+=("${1}") + shift + ;; + esac +done + +if [[ ${VERSION} == "" ]]; then + VERSION="$(get_protoc_latest_version)" +fi + +if [[ ${DESTINATION_DIR} == "" ]]; then + echo "missing destination argument" + exit 1 +fi + +# uninstall previous version +rm -rf "${DESTINATION_DIR}"/bin/shellcheck + +DL_URL="https://github.com/koalaman/shellcheck/releases/download/${VERSION}/shellcheck-${VERSION}.$(package_os).$(package_arch).tar.xz" + +curl \ + --silent \ + --fail \ + --location \ + "${DL_URL}" \ + -o "${DESTINATION_DIR}/shellcheck.tar.xz" + +tar \ + --extract \ + --xz \ + --file="${DESTINATION_DIR}/shellcheck.tar.xz" \ + --strip-components=1 \ + --directory="${DESTINATION_DIR}/bin" + +rm -f "${DESTINATION_DIR}/shellcheck.tar.xz" +rm -f "${DESTINATION_DIR}/bin/LICENSE.txt" +rm -f "${DESTINATION_DIR}/bin/README.txt" + +# to update all dates in order for make file to get it as new (check stat "${DESTINATION_DIR}/bin/shellcheck") +touch "${DESTINATION_DIR}/bin/shellcheck" diff --git a/scripts/rename b/scripts/rename index 00f353d..1cdaf06 100755 --- a/scripts/rename +++ b/scripts/rename @@ -18,12 +18,12 @@ OLD_NAME='goboilerplate' NEW_PACKAGE="${1}" NEW_NAME="${2}" -[[ -z ${NEW_PACKAGE} ]] || \ -[[ -z ${NEW_NAME} ]] || \ -[[ ! ${NEW_PACKAGE} =~ ^[0-9a-zA-Z\/\.]+$ ]] || \ -[[ ! ${NEW_NAME} =~ ^[0-9a-zA-Z\/\.]+$ ]] && \ - echo -e "\e[0;31mWrong input\e[0m" && \ - __help && \ +[[ -z ${NEW_PACKAGE} ]] || + [[ -z ${NEW_NAME} ]] || + [[ ! ${NEW_PACKAGE} =~ ^[0-9a-zA-Z\/\.]+$ ]] || + [[ ! ${NEW_NAME} =~ ^[0-9a-zA-Z\/\.]+$ ]] && + echo -e "\e[0;31mWrong input\e[0m" && + __help && exit 1 find ./ \ @@ -40,4 +40,4 @@ find ./ \ -not -path "./scripts/rename" \ -exec sed -i "s|${OLD_NAME}|${NEW_NAME}|g" {} \; -mv ./cmd/${OLD_NAME} ./cmd/${NEW_NAME} +mv "./cmd/${OLD_NAME}" "./cmd/${NEW_NAME}" diff --git a/scripts/tools.mk b/scripts/tools.mk index 72e3ab1..35c30af 100644 --- a/scripts/tools.mk +++ b/scripts/tools.mk @@ -1,3 +1,11 @@ +## https://www.gnu.org/software/make/manual/html_node/Secondary-Expansion.html +## in order for +#.SECONDEXPANSION: + +## https://www.gnu.org/software/make/manual/html_node/Special-Targets.html#index-not-intermediate-targets_002c-explicit +## NOTINTERMEDIATE requires make >=4.4 +.NOTINTERMEDIATE: + # https://www.gnu.org/software/make/manual/make.html#Automatic-Variables # https://www.gnu.org/software/make/manual/make.html#Prerequisite-Types @@ -45,7 +53,7 @@ vet: ## # https://github.com/dominikh/go-tools/releases https://staticcheck.io/c STATICCHECK_CMD:=honnef.co/go/tools/cmd/staticcheck -STATICCHECK_VER:=2024.1 +STATICCHECK_VER:=2024.1.1 $(TOOLS_BIN)/staticcheck: $(TOOLS_DB)/staticcheck.$(STATICCHECK_VER).$(GO_VER).ver $(call go_install,staticcheck,$(STATICCHECK_CMD),$(STATICCHECK_VER)) @@ -58,7 +66,7 @@ staticcheck: $(TOOLS_BIN)/staticcheck ## # https://github.com/golangci/golangci-lint/releases GOLANGCI-LINT_CMD:=github.com/golangci/golangci-lint/cmd/golangci-lint -GOLANGCI-LINT_VER:=v1.60.1 +GOLANGCI-LINT_VER:=v1.62.2 $(TOOLS_BIN)/golangci-lint: $(TOOLS_DB)/golangci-lint.$(GOLANGCI-LINT_VER).$(GO_VER).ver @curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(TOOLS_BIN) $(GOLANGCI-LINT_VER) @@ -69,14 +77,14 @@ golangci-lint: $(TOOLS_BIN)/golangci-lint .PHONY: golangci-lint-github-actions golangci-lint-github-actions: $(TOOLS_BIN)/golangci-lint - golangci-lint run --out-format github-actions + golangci-lint run --out-format colored-line-number @echo '' ## ## # https://pkg.go.dev/golang.org/x/tools?tab=versions GOIMPORTS_CMD := golang.org/x/tools/cmd/goimports -GOIMPORTS_VER := v0.24.0 +GOIMPORTS_VER := v0.28.0 $(TOOLS_BIN)/goimports: $(TOOLS_DB)/goimports.$(GOIMPORTS_VER).$(GO_VER).ver $(call go_install,goimports,$(GOIMPORTS_CMD),$(GOIMPORTS_VER)) @@ -92,7 +100,7 @@ goimports.display: $(TOOLS_BIN)/goimports ## # https://github.com/mvdan/gofumpt/releases GOFUMPT_CMD:=mvdan.cc/gofumpt -GOFUMPT_VER:=v0.6.0 +GOFUMPT_VER:=v0.7.0 $(TOOLS_BIN)/gofumpt: $(TOOLS_DB)/gofumpt.$(GOFUMPT_VER).$(GO_VER).ver $(call go_install,gofumpt,$(GOFUMPT_CMD),$(GOFUMPT_VER)) @@ -118,7 +126,7 @@ gofmt.display: ## # https://github.com/itchyny/gojq/releases GOJQ_CMD := github.com/itchyny/gojq/cmd/gojq -GOJQ_VER := v0.12.16 +GOJQ_VER := v0.12.17 $(TOOLS_BIN)/gojq: $(TOOLS_DB)/gojq.$(GOJQ_VER).$(GO_VER).ver $(call go_install,gojq,$(GOJQ_CMD),$(GOJQ_VER)) @@ -129,7 +137,7 @@ gojq: $(TOOLS_BIN)/gojq ## # https://github.com/air-verse/air/releases AIR_CMD:=github.com/air-verse/air -AIR_VER:=v1.52.3 +AIR_VER:=v1.61.5 $(TOOLS_BIN)/air: $(TOOLS_DB)/air.$(AIR_VER).$(GO_VER).ver $(call go_install,air,$(AIR_CMD),$(AIR_VER)) @@ -141,7 +149,7 @@ air: $(TOOLS_BIN)/air ## # https://github.com/vektra/mockery/releases MOCKERY_CMD:=github.com/vektra/mockery/v2 -MOCKERY_VER:=v2.45.1 +MOCKERY_VER:=v2.50.1 $(TOOLS_BIN)/mockery: $(TOOLS_DB)/mockery.$(MOCKERY_VER).$(GO_VER).ver $(call go_install,air,$(MOCKERY_CMD),$(MOCKERY_VER)) @@ -153,13 +161,13 @@ mockery: $(TOOLS_BIN)/mockery ## # https://github.com/protocolbuffers/protobuf/releases -PROTOC_VER:=v27.3 +PROTOC_VER:=v29.2 $(TOOLS_BIN)/protoc: $(TOOLS_DB)/protoc.$(PROTOC_VER).ver ./scripts/install-protoc --version $(PROTOC_VER) --destination $(TOOLS_DIR) # https://github.com/protocolbuffers/protobuf-go/releases PROTOC-GEN-GO_CMD:=google.golang.org/protobuf/cmd/protoc-gen-go -PROTOC-GEN-GO_VER:=v1.34.2 +PROTOC-GEN-GO_VER:=v1.36.1 $(TOOLS_BIN)/protoc-gen-go: $(TOOLS_DB)/protoc-gen-go.$(PROTOC-GEN-GO_VER).$(GO_VER).ver $(call go_install,protoc-gen-go,$(PROTOC-GEN-GO_CMD),$(PROTOC-GEN-GO_VER)) @@ -168,3 +176,26 @@ proto: $(TOOLS_BIN)/protoc $(TOOLS_BIN)/protoc-gen-go $(TOOLS_BIN)/protoc --version $(TOOLS_BIN)/protoc-gen-go --version ## + +## +# https://github.com/mvdan/sh/releases +SHFMT_CMD := mvdan.cc/sh/v3/cmd/shfmt +SHFMT_VER := v3.10.0 +$(TOOLS_BIN)/shfmt: $(TOOLS_DB)/shfmt.$(SHFMT_VER).$(GO_VER).ver + $(call go_install,shfmt,$(SHFMT_CMD),$(SHFMT_VER)) + +.PHONY: shfmt +shfmt: $(TOOLS_BIN)/shfmt + @./scripts/foreach-script $(TOOLS_BIN)/shfmt --simplify --language-dialect auto --case-indent --indent 2 --write +## + +## +# https://github.com/koalaman/shellcheck/releases +SHELLCHECK_VER := v0.10.0 +$(TOOLS_BIN)/shellcheck: $(TOOLS_DB)/shellcheck.$(SHELLCHECK_VER).ver | $(TOOLS_BIN) + @./scripts/install-shellcheck --version $(SHELLCHECK_VER) --destination $(TOOLS_DIR) + +.PHONY: shellcheck +shellcheck: $(TOOLS_BIN)/shellcheck + @./scripts/foreach-script $(TOOLS_BIN)/shellcheck --external-sources --format=tty --severity=info +## diff --git a/vendor/github.com/go-viper/mapstructure/v2/decode_hooks.go b/vendor/github.com/go-viper/mapstructure/v2/decode_hooks.go index 2523c6a..1f3c69d 100644 --- a/vendor/github.com/go-viper/mapstructure/v2/decode_hooks.go +++ b/vendor/github.com/go-viper/mapstructure/v2/decode_hooks.go @@ -6,6 +6,7 @@ import ( "fmt" "net" "net/netip" + "net/url" "reflect" "strconv" "strings" @@ -176,6 +177,26 @@ func StringToTimeDurationHookFunc() DecodeHookFunc { } } +// StringToURLHookFunc returns a DecodeHookFunc that converts +// strings to *url.URL. +func StringToURLHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(&url.URL{}) { + return data, nil + } + + // Convert it by parsing + return url.Parse(data.(string)) + } +} + // StringToIPHookFunc returns a DecodeHookFunc that converts // strings to net.IP func StringToIPHookFunc() DecodeHookFunc { diff --git a/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go b/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go index 1cd6204..e77e63b 100644 --- a/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go +++ b/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go @@ -278,6 +278,10 @@ type DecoderConfig struct { // field name or tag. Defaults to `strings.EqualFold`. This can be used // to implement case-sensitive tag values, support snake casing, etc. MatchName func(mapKey, fieldName string) bool + + // DecodeNil, if set to true, will cause the DecodeHook (if present) to run + // even if the input is nil. This can be used to provide default values. + DecodeNil bool } // A Decoder takes a raw interface value and turns it into structured @@ -438,19 +442,26 @@ func (d *Decoder) Decode(input interface{}) error { return err } +// isNil returns true if the input is nil or a typed nil pointer. +func isNil(input interface{}) bool { + if input == nil { + return true + } + val := reflect.ValueOf(input) + return val.Kind() == reflect.Ptr && val.IsNil() +} + // Decodes an unknown data type into a specific reflection value. func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) error { - var inputVal reflect.Value - if input != nil { - inputVal = reflect.ValueOf(input) - - // We need to check here if input is a typed nil. Typed nils won't - // match the "input == nil" below so we check that here. - if inputVal.Kind() == reflect.Ptr && inputVal.IsNil() { - input = nil - } + var ( + inputVal = reflect.ValueOf(input) + outputKind = getKind(outVal) + decodeNil = d.config.DecodeNil && d.cachedDecodeHook != nil + ) + if isNil(input) { + // Typed nils won't match the "input == nil" below, so reset input. + input = nil } - if input == nil { // If the data is nil, then we don't set anything, unless ZeroFields is set // to true. @@ -461,17 +472,31 @@ func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) e d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) } } - return nil + if !decodeNil { + return nil + } } - if !inputVal.IsValid() { - // If the input value is invalid, then we just set the value - // to be the zero value. - outVal.Set(reflect.Zero(outVal.Type())) - if d.config.Metadata != nil && name != "" { - d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + if !decodeNil { + // If the input value is invalid, then we just set the value + // to be the zero value. + outVal.Set(reflect.Zero(outVal.Type())) + if d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } + return nil + } + // Hooks need a valid inputVal, so reset it to zero value of outVal type. + switch outputKind { + case reflect.Struct, reflect.Map: + var mapVal map[string]interface{} + inputVal = reflect.ValueOf(mapVal) // create nil map pointer + case reflect.Slice, reflect.Array: + var sliceVal []interface{} + inputVal = reflect.ValueOf(sliceVal) // create nil slice pointer + default: + inputVal = reflect.Zero(outVal.Type()) } - return nil } if d.cachedDecodeHook != nil { @@ -482,9 +507,11 @@ func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) e return fmt.Errorf("error decoding '%s': %w", name, err) } } + if isNil(input) { + return nil + } var err error - outputKind := getKind(outVal) addMetaKey := true switch outputKind { case reflect.Bool: @@ -765,8 +792,8 @@ func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) e } default: return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", - name, val.Type(), dataVal.Type(), data) + "'%s' expected type '%s', got unconvertible type '%#v', value: '%#v'", + name, val, dataVal, data) } return nil diff --git a/vendor/github.com/knadh/koanf/providers/env/env.go b/vendor/github.com/knadh/koanf/providers/env/env.go index 5ec252b..edd8e33 100644 --- a/vendor/github.com/knadh/koanf/providers/env/env.go +++ b/vendor/github.com/knadh/koanf/providers/env/env.go @@ -94,5 +94,9 @@ func (e *Env) Read() (map[string]interface{}, error) { } - return maps.Unflatten(mp, e.delim), nil + if e.delim != "" { + return maps.Unflatten(mp, e.delim), nil + } + + return mp, nil } diff --git a/vendor/github.com/knadh/koanf/providers/file/file.go b/vendor/github.com/knadh/koanf/providers/file/file.go index 20c3630..ed61051 100644 --- a/vendor/github.com/knadh/koanf/providers/file/file.go +++ b/vendor/github.com/knadh/koanf/providers/file/file.go @@ -95,18 +95,6 @@ func (f *File) Watch(cb func(event interface{}, err error)) error { evFile := filepath.Clean(event.Name) - // Since the event is triggered on a directory, is this - // one on the file being watched? - if evFile != realPath && evFile != f.path { - continue - } - - // The file was removed. - if event.Op&fsnotify.Remove != 0 { - cb(nil, fmt.Errorf("file %s was removed", event.Name)) - break loop - } - // Resolve symlink to get the real path, in case the symlink's // target has changed. curPath, err := filepath.EvalSymlinks(f.path) @@ -114,15 +102,26 @@ func (f *File) Watch(cb func(event interface{}, err error)) error { cb(nil, err) break loop } - realPath = filepath.Clean(curPath) + curPath = filepath.Clean(curPath) - // Finally, we only care about create and write. - if event.Op&(fsnotify.Write|fsnotify.Create) == 0 { - continue - } + onWatchedFile := evFile == realPath || evFile == f.path - // Trigger event. - cb(nil, nil) + // Since the event is triggered on a directory, is this + // a create or write on the file being watched? + // + // Or has the real path of the file being watched changed? + // + // If either of the above are true, trigger the callback. + if event.Has(fsnotify.Create|fsnotify.Write) && (onWatchedFile || + (curPath != "" && curPath != realPath)) { + realPath = curPath + + // Trigger event. + cb(nil, nil) + } else if onWatchedFile && event.Has(fsnotify.Remove) { + cb(nil, fmt.Errorf("file %s was removed", event.Name)) + break loop + } // There's an error. case err, ok := <-f.w.Errors: diff --git a/vendor/github.com/mattn/go-colorable/LICENSE b/vendor/github.com/mattn/go-colorable/LICENSE deleted file mode 100644 index 91b5cef..0000000 --- a/vendor/github.com/mattn/go-colorable/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Yasuhiro Matsumoto - -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. diff --git a/vendor/github.com/mattn/go-colorable/README.md b/vendor/github.com/mattn/go-colorable/README.md deleted file mode 100644 index ca04837..0000000 --- a/vendor/github.com/mattn/go-colorable/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# go-colorable - -[![Build Status](https://github.com/mattn/go-colorable/workflows/test/badge.svg)](https://github.com/mattn/go-colorable/actions?query=workflow%3Atest) -[![Codecov](https://codecov.io/gh/mattn/go-colorable/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-colorable) -[![GoDoc](https://godoc.org/github.com/mattn/go-colorable?status.svg)](http://godoc.org/github.com/mattn/go-colorable) -[![Go Report Card](https://goreportcard.com/badge/mattn/go-colorable)](https://goreportcard.com/report/mattn/go-colorable) - -Colorable writer for windows. - -For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But I don't want.) -This package is possible to handle escape sequence for ansi color on windows. - -## Too Bad! - -![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/bad.png) - - -## So Good! - -![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/good.png) - -## Usage - -```go -logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true}) -logrus.SetOutput(colorable.NewColorableStdout()) - -logrus.Info("succeeded") -logrus.Warn("not correct") -logrus.Error("something error") -logrus.Fatal("panic") -``` - -You can compile above code on non-windows OSs. - -## Installation - -``` -$ go get github.com/mattn/go-colorable -``` - -# License - -MIT - -# Author - -Yasuhiro Matsumoto (a.k.a mattn) diff --git a/vendor/github.com/mattn/go-colorable/colorable_appengine.go b/vendor/github.com/mattn/go-colorable/colorable_appengine.go deleted file mode 100644 index 416d1bb..0000000 --- a/vendor/github.com/mattn/go-colorable/colorable_appengine.go +++ /dev/null @@ -1,38 +0,0 @@ -//go:build appengine -// +build appengine - -package colorable - -import ( - "io" - "os" - - _ "github.com/mattn/go-isatty" -) - -// NewColorable returns new instance of Writer which handles escape sequence. -func NewColorable(file *os.File) io.Writer { - if file == nil { - panic("nil passed instead of *os.File to NewColorable()") - } - - return file -} - -// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. -func NewColorableStdout() io.Writer { - return os.Stdout -} - -// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. -func NewColorableStderr() io.Writer { - return os.Stderr -} - -// EnableColorsStdout enable colors if possible. -func EnableColorsStdout(enabled *bool) func() { - if enabled != nil { - *enabled = true - } - return func() {} -} diff --git a/vendor/github.com/mattn/go-colorable/colorable_others.go b/vendor/github.com/mattn/go-colorable/colorable_others.go deleted file mode 100644 index 766d946..0000000 --- a/vendor/github.com/mattn/go-colorable/colorable_others.go +++ /dev/null @@ -1,38 +0,0 @@ -//go:build !windows && !appengine -// +build !windows,!appengine - -package colorable - -import ( - "io" - "os" - - _ "github.com/mattn/go-isatty" -) - -// NewColorable returns new instance of Writer which handles escape sequence. -func NewColorable(file *os.File) io.Writer { - if file == nil { - panic("nil passed instead of *os.File to NewColorable()") - } - - return file -} - -// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. -func NewColorableStdout() io.Writer { - return os.Stdout -} - -// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. -func NewColorableStderr() io.Writer { - return os.Stderr -} - -// EnableColorsStdout enable colors if possible. -func EnableColorsStdout(enabled *bool) func() { - if enabled != nil { - *enabled = true - } - return func() {} -} diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go deleted file mode 100644 index 1846ad5..0000000 --- a/vendor/github.com/mattn/go-colorable/colorable_windows.go +++ /dev/null @@ -1,1047 +0,0 @@ -//go:build windows && !appengine -// +build windows,!appengine - -package colorable - -import ( - "bytes" - "io" - "math" - "os" - "strconv" - "strings" - "sync" - "syscall" - "unsafe" - - "github.com/mattn/go-isatty" -) - -const ( - foregroundBlue = 0x1 - foregroundGreen = 0x2 - foregroundRed = 0x4 - foregroundIntensity = 0x8 - foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) - backgroundBlue = 0x10 - backgroundGreen = 0x20 - backgroundRed = 0x40 - backgroundIntensity = 0x80 - backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) - commonLvbUnderscore = 0x8000 - - cENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4 -) - -const ( - genericRead = 0x80000000 - genericWrite = 0x40000000 -) - -const ( - consoleTextmodeBuffer = 0x1 -) - -type wchar uint16 -type short int16 -type dword uint32 -type word uint16 - -type coord struct { - x short - y short -} - -type smallRect struct { - left short - top short - right short - bottom short -} - -type consoleScreenBufferInfo struct { - size coord - cursorPosition coord - attributes word - window smallRect - maximumWindowSize coord -} - -type consoleCursorInfo struct { - size dword - visible int32 -} - -var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") - procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") - procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") - procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") - procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute") - procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") - procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") - procSetConsoleTitle = kernel32.NewProc("SetConsoleTitleW") - procGetConsoleMode = kernel32.NewProc("GetConsoleMode") - procSetConsoleMode = kernel32.NewProc("SetConsoleMode") - procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer") -) - -// Writer provides colorable Writer to the console -type Writer struct { - out io.Writer - handle syscall.Handle - althandle syscall.Handle - oldattr word - oldpos coord - rest bytes.Buffer - mutex sync.Mutex -} - -// NewColorable returns new instance of Writer which handles escape sequence from File. -func NewColorable(file *os.File) io.Writer { - if file == nil { - panic("nil passed instead of *os.File to NewColorable()") - } - - if isatty.IsTerminal(file.Fd()) { - var mode uint32 - if r, _, _ := procGetConsoleMode.Call(file.Fd(), uintptr(unsafe.Pointer(&mode))); r != 0 && mode&cENABLE_VIRTUAL_TERMINAL_PROCESSING != 0 { - return file - } - var csbi consoleScreenBufferInfo - handle := syscall.Handle(file.Fd()) - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - return &Writer{out: file, handle: handle, oldattr: csbi.attributes, oldpos: coord{0, 0}} - } - return file -} - -// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. -func NewColorableStdout() io.Writer { - return NewColorable(os.Stdout) -} - -// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. -func NewColorableStderr() io.Writer { - return NewColorable(os.Stderr) -} - -var color256 = map[int]int{ - 0: 0x000000, - 1: 0x800000, - 2: 0x008000, - 3: 0x808000, - 4: 0x000080, - 5: 0x800080, - 6: 0x008080, - 7: 0xc0c0c0, - 8: 0x808080, - 9: 0xff0000, - 10: 0x00ff00, - 11: 0xffff00, - 12: 0x0000ff, - 13: 0xff00ff, - 14: 0x00ffff, - 15: 0xffffff, - 16: 0x000000, - 17: 0x00005f, - 18: 0x000087, - 19: 0x0000af, - 20: 0x0000d7, - 21: 0x0000ff, - 22: 0x005f00, - 23: 0x005f5f, - 24: 0x005f87, - 25: 0x005faf, - 26: 0x005fd7, - 27: 0x005fff, - 28: 0x008700, - 29: 0x00875f, - 30: 0x008787, - 31: 0x0087af, - 32: 0x0087d7, - 33: 0x0087ff, - 34: 0x00af00, - 35: 0x00af5f, - 36: 0x00af87, - 37: 0x00afaf, - 38: 0x00afd7, - 39: 0x00afff, - 40: 0x00d700, - 41: 0x00d75f, - 42: 0x00d787, - 43: 0x00d7af, - 44: 0x00d7d7, - 45: 0x00d7ff, - 46: 0x00ff00, - 47: 0x00ff5f, - 48: 0x00ff87, - 49: 0x00ffaf, - 50: 0x00ffd7, - 51: 0x00ffff, - 52: 0x5f0000, - 53: 0x5f005f, - 54: 0x5f0087, - 55: 0x5f00af, - 56: 0x5f00d7, - 57: 0x5f00ff, - 58: 0x5f5f00, - 59: 0x5f5f5f, - 60: 0x5f5f87, - 61: 0x5f5faf, - 62: 0x5f5fd7, - 63: 0x5f5fff, - 64: 0x5f8700, - 65: 0x5f875f, - 66: 0x5f8787, - 67: 0x5f87af, - 68: 0x5f87d7, - 69: 0x5f87ff, - 70: 0x5faf00, - 71: 0x5faf5f, - 72: 0x5faf87, - 73: 0x5fafaf, - 74: 0x5fafd7, - 75: 0x5fafff, - 76: 0x5fd700, - 77: 0x5fd75f, - 78: 0x5fd787, - 79: 0x5fd7af, - 80: 0x5fd7d7, - 81: 0x5fd7ff, - 82: 0x5fff00, - 83: 0x5fff5f, - 84: 0x5fff87, - 85: 0x5fffaf, - 86: 0x5fffd7, - 87: 0x5fffff, - 88: 0x870000, - 89: 0x87005f, - 90: 0x870087, - 91: 0x8700af, - 92: 0x8700d7, - 93: 0x8700ff, - 94: 0x875f00, - 95: 0x875f5f, - 96: 0x875f87, - 97: 0x875faf, - 98: 0x875fd7, - 99: 0x875fff, - 100: 0x878700, - 101: 0x87875f, - 102: 0x878787, - 103: 0x8787af, - 104: 0x8787d7, - 105: 0x8787ff, - 106: 0x87af00, - 107: 0x87af5f, - 108: 0x87af87, - 109: 0x87afaf, - 110: 0x87afd7, - 111: 0x87afff, - 112: 0x87d700, - 113: 0x87d75f, - 114: 0x87d787, - 115: 0x87d7af, - 116: 0x87d7d7, - 117: 0x87d7ff, - 118: 0x87ff00, - 119: 0x87ff5f, - 120: 0x87ff87, - 121: 0x87ffaf, - 122: 0x87ffd7, - 123: 0x87ffff, - 124: 0xaf0000, - 125: 0xaf005f, - 126: 0xaf0087, - 127: 0xaf00af, - 128: 0xaf00d7, - 129: 0xaf00ff, - 130: 0xaf5f00, - 131: 0xaf5f5f, - 132: 0xaf5f87, - 133: 0xaf5faf, - 134: 0xaf5fd7, - 135: 0xaf5fff, - 136: 0xaf8700, - 137: 0xaf875f, - 138: 0xaf8787, - 139: 0xaf87af, - 140: 0xaf87d7, - 141: 0xaf87ff, - 142: 0xafaf00, - 143: 0xafaf5f, - 144: 0xafaf87, - 145: 0xafafaf, - 146: 0xafafd7, - 147: 0xafafff, - 148: 0xafd700, - 149: 0xafd75f, - 150: 0xafd787, - 151: 0xafd7af, - 152: 0xafd7d7, - 153: 0xafd7ff, - 154: 0xafff00, - 155: 0xafff5f, - 156: 0xafff87, - 157: 0xafffaf, - 158: 0xafffd7, - 159: 0xafffff, - 160: 0xd70000, - 161: 0xd7005f, - 162: 0xd70087, - 163: 0xd700af, - 164: 0xd700d7, - 165: 0xd700ff, - 166: 0xd75f00, - 167: 0xd75f5f, - 168: 0xd75f87, - 169: 0xd75faf, - 170: 0xd75fd7, - 171: 0xd75fff, - 172: 0xd78700, - 173: 0xd7875f, - 174: 0xd78787, - 175: 0xd787af, - 176: 0xd787d7, - 177: 0xd787ff, - 178: 0xd7af00, - 179: 0xd7af5f, - 180: 0xd7af87, - 181: 0xd7afaf, - 182: 0xd7afd7, - 183: 0xd7afff, - 184: 0xd7d700, - 185: 0xd7d75f, - 186: 0xd7d787, - 187: 0xd7d7af, - 188: 0xd7d7d7, - 189: 0xd7d7ff, - 190: 0xd7ff00, - 191: 0xd7ff5f, - 192: 0xd7ff87, - 193: 0xd7ffaf, - 194: 0xd7ffd7, - 195: 0xd7ffff, - 196: 0xff0000, - 197: 0xff005f, - 198: 0xff0087, - 199: 0xff00af, - 200: 0xff00d7, - 201: 0xff00ff, - 202: 0xff5f00, - 203: 0xff5f5f, - 204: 0xff5f87, - 205: 0xff5faf, - 206: 0xff5fd7, - 207: 0xff5fff, - 208: 0xff8700, - 209: 0xff875f, - 210: 0xff8787, - 211: 0xff87af, - 212: 0xff87d7, - 213: 0xff87ff, - 214: 0xffaf00, - 215: 0xffaf5f, - 216: 0xffaf87, - 217: 0xffafaf, - 218: 0xffafd7, - 219: 0xffafff, - 220: 0xffd700, - 221: 0xffd75f, - 222: 0xffd787, - 223: 0xffd7af, - 224: 0xffd7d7, - 225: 0xffd7ff, - 226: 0xffff00, - 227: 0xffff5f, - 228: 0xffff87, - 229: 0xffffaf, - 230: 0xffffd7, - 231: 0xffffff, - 232: 0x080808, - 233: 0x121212, - 234: 0x1c1c1c, - 235: 0x262626, - 236: 0x303030, - 237: 0x3a3a3a, - 238: 0x444444, - 239: 0x4e4e4e, - 240: 0x585858, - 241: 0x626262, - 242: 0x6c6c6c, - 243: 0x767676, - 244: 0x808080, - 245: 0x8a8a8a, - 246: 0x949494, - 247: 0x9e9e9e, - 248: 0xa8a8a8, - 249: 0xb2b2b2, - 250: 0xbcbcbc, - 251: 0xc6c6c6, - 252: 0xd0d0d0, - 253: 0xdadada, - 254: 0xe4e4e4, - 255: 0xeeeeee, -} - -// `\033]0;TITLESTR\007` -func doTitleSequence(er *bytes.Reader) error { - var c byte - var err error - - c, err = er.ReadByte() - if err != nil { - return err - } - if c != '0' && c != '2' { - return nil - } - c, err = er.ReadByte() - if err != nil { - return err - } - if c != ';' { - return nil - } - title := make([]byte, 0, 80) - for { - c, err = er.ReadByte() - if err != nil { - return err - } - if c == 0x07 || c == '\n' { - break - } - title = append(title, c) - } - if len(title) > 0 { - title8, err := syscall.UTF16PtrFromString(string(title)) - if err == nil { - procSetConsoleTitle.Call(uintptr(unsafe.Pointer(title8))) - } - } - return nil -} - -// returns Atoi(s) unless s == "" in which case it returns def -func atoiWithDefault(s string, def int) (int, error) { - if s == "" { - return def, nil - } - return strconv.Atoi(s) -} - -// Write writes data on console -func (w *Writer) Write(data []byte) (n int, err error) { - w.mutex.Lock() - defer w.mutex.Unlock() - var csbi consoleScreenBufferInfo - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - - handle := w.handle - - var er *bytes.Reader - if w.rest.Len() > 0 { - var rest bytes.Buffer - w.rest.WriteTo(&rest) - w.rest.Reset() - rest.Write(data) - er = bytes.NewReader(rest.Bytes()) - } else { - er = bytes.NewReader(data) - } - var plaintext bytes.Buffer -loop: - for { - c1, err := er.ReadByte() - if err != nil { - plaintext.WriteTo(w.out) - break loop - } - if c1 != 0x1b { - plaintext.WriteByte(c1) - continue - } - _, err = plaintext.WriteTo(w.out) - if err != nil { - break loop - } - c2, err := er.ReadByte() - if err != nil { - break loop - } - - switch c2 { - case '>': - continue - case ']': - w.rest.WriteByte(c1) - w.rest.WriteByte(c2) - er.WriteTo(&w.rest) - if bytes.IndexByte(w.rest.Bytes(), 0x07) == -1 { - break loop - } - er = bytes.NewReader(w.rest.Bytes()[2:]) - err := doTitleSequence(er) - if err != nil { - break loop - } - w.rest.Reset() - continue - // https://github.com/mattn/go-colorable/issues/27 - case '7': - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - w.oldpos = csbi.cursorPosition - continue - case '8': - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) - continue - case 0x5b: - // execute part after switch - default: - continue - } - - w.rest.WriteByte(c1) - w.rest.WriteByte(c2) - er.WriteTo(&w.rest) - - var buf bytes.Buffer - var m byte - for i, c := range w.rest.Bytes()[2:] { - if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { - m = c - er = bytes.NewReader(w.rest.Bytes()[2+i+1:]) - w.rest.Reset() - break - } - buf.Write([]byte(string(c))) - } - if m == 0 { - break loop - } - - switch m { - case 'A': - n, err = atoiWithDefault(buf.String(), 1) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'B': - n, err = atoiWithDefault(buf.String(), 1) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'C': - n, err = atoiWithDefault(buf.String(), 1) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x += short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'D': - n, err = atoiWithDefault(buf.String(), 1) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x -= short(n) - if csbi.cursorPosition.x < 0 { - csbi.cursorPosition.x = 0 - } - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'E': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = 0 - csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'F': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = 0 - csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'G': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - if n < 1 { - n = 1 - } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = short(n - 1) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'H', 'f': - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - if buf.Len() > 0 { - token := strings.Split(buf.String(), ";") - switch len(token) { - case 1: - n1, err := strconv.Atoi(token[0]) - if err != nil { - continue - } - csbi.cursorPosition.y = short(n1 - 1) - case 2: - n1, err := strconv.Atoi(token[0]) - if err != nil { - continue - } - n2, err := strconv.Atoi(token[1]) - if err != nil { - continue - } - csbi.cursorPosition.x = short(n2 - 1) - csbi.cursorPosition.y = short(n1 - 1) - } - } else { - csbi.cursorPosition.y = 0 - } - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'J': - n := 0 - if buf.Len() > 0 { - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - } - var count, written dword - var cursor coord - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - switch n { - case 0: - cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.size.y-csbi.cursorPosition.y)*dword(csbi.size.x) - case 1: - cursor = coord{x: csbi.window.left, y: csbi.window.top} - count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.window.top-csbi.cursorPosition.y)*dword(csbi.size.x) - case 2: - cursor = coord{x: csbi.window.left, y: csbi.window.top} - count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.size.y-csbi.cursorPosition.y)*dword(csbi.size.x) - } - procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - case 'K': - n := 0 - if buf.Len() > 0 { - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - var cursor coord - var count, written dword - switch n { - case 0: - cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - count = dword(csbi.size.x - csbi.cursorPosition.x) - case 1: - cursor = coord{x: csbi.window.left, y: csbi.cursorPosition.y} - count = dword(csbi.size.x - csbi.cursorPosition.x) - case 2: - cursor = coord{x: csbi.window.left, y: csbi.cursorPosition.y} - count = dword(csbi.size.x) - } - procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - case 'X': - n := 0 - if buf.Len() > 0 { - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - var cursor coord - var written dword - cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(n), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(n), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - case 'm': - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - attr := csbi.attributes - cs := buf.String() - if cs == "" { - procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(w.oldattr)) - continue - } - token := strings.Split(cs, ";") - for i := 0; i < len(token); i++ { - ns := token[i] - if n, err = strconv.Atoi(ns); err == nil { - switch { - case n == 0 || n == 100: - attr = w.oldattr - case n == 4: - attr |= commonLvbUnderscore - case (1 <= n && n <= 3) || n == 5: - attr |= foregroundIntensity - case n == 7 || n == 27: - attr = - (attr &^ (foregroundMask | backgroundMask)) | - ((attr & foregroundMask) << 4) | - ((attr & backgroundMask) >> 4) - case n == 22: - attr &^= foregroundIntensity - case n == 24: - attr &^= commonLvbUnderscore - case 30 <= n && n <= 37: - attr &= backgroundMask - if (n-30)&1 != 0 { - attr |= foregroundRed - } - if (n-30)&2 != 0 { - attr |= foregroundGreen - } - if (n-30)&4 != 0 { - attr |= foregroundBlue - } - case n == 38: // set foreground color. - if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") { - if n256, err := strconv.Atoi(token[i+2]); err == nil { - if n256foreAttr == nil { - n256setup() - } - attr &= backgroundMask - attr |= n256foreAttr[n256%len(n256foreAttr)] - i += 2 - } - } else if len(token) == 5 && token[i+1] == "2" { - var r, g, b int - r, _ = strconv.Atoi(token[i+2]) - g, _ = strconv.Atoi(token[i+3]) - b, _ = strconv.Atoi(token[i+4]) - i += 4 - if r > 127 { - attr |= foregroundRed - } - if g > 127 { - attr |= foregroundGreen - } - if b > 127 { - attr |= foregroundBlue - } - } else { - attr = attr & (w.oldattr & backgroundMask) - } - case n == 39: // reset foreground color. - attr &= backgroundMask - attr |= w.oldattr & foregroundMask - case 40 <= n && n <= 47: - attr &= foregroundMask - if (n-40)&1 != 0 { - attr |= backgroundRed - } - if (n-40)&2 != 0 { - attr |= backgroundGreen - } - if (n-40)&4 != 0 { - attr |= backgroundBlue - } - case n == 48: // set background color. - if i < len(token)-2 && token[i+1] == "5" { - if n256, err := strconv.Atoi(token[i+2]); err == nil { - if n256backAttr == nil { - n256setup() - } - attr &= foregroundMask - attr |= n256backAttr[n256%len(n256backAttr)] - i += 2 - } - } else if len(token) == 5 && token[i+1] == "2" { - var r, g, b int - r, _ = strconv.Atoi(token[i+2]) - g, _ = strconv.Atoi(token[i+3]) - b, _ = strconv.Atoi(token[i+4]) - i += 4 - if r > 127 { - attr |= backgroundRed - } - if g > 127 { - attr |= backgroundGreen - } - if b > 127 { - attr |= backgroundBlue - } - } else { - attr = attr & (w.oldattr & foregroundMask) - } - case n == 49: // reset foreground color. - attr &= foregroundMask - attr |= w.oldattr & backgroundMask - case 90 <= n && n <= 97: - attr = (attr & backgroundMask) - attr |= foregroundIntensity - if (n-90)&1 != 0 { - attr |= foregroundRed - } - if (n-90)&2 != 0 { - attr |= foregroundGreen - } - if (n-90)&4 != 0 { - attr |= foregroundBlue - } - case 100 <= n && n <= 107: - attr = (attr & foregroundMask) - attr |= backgroundIntensity - if (n-100)&1 != 0 { - attr |= backgroundRed - } - if (n-100)&2 != 0 { - attr |= backgroundGreen - } - if (n-100)&4 != 0 { - attr |= backgroundBlue - } - } - procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(attr)) - } - } - case 'h': - var ci consoleCursorInfo - cs := buf.String() - if cs == "5>" { - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) - ci.visible = 0 - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) - } else if cs == "?25" { - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) - ci.visible = 1 - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) - } else if cs == "?1049" { - if w.althandle == 0 { - h, _, _ := procCreateConsoleScreenBuffer.Call(uintptr(genericRead|genericWrite), 0, 0, uintptr(consoleTextmodeBuffer), 0, 0) - w.althandle = syscall.Handle(h) - if w.althandle != 0 { - handle = w.althandle - } - } - } - case 'l': - var ci consoleCursorInfo - cs := buf.String() - if cs == "5>" { - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) - ci.visible = 1 - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) - } else if cs == "?25" { - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) - ci.visible = 0 - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) - } else if cs == "?1049" { - if w.althandle != 0 { - syscall.CloseHandle(w.althandle) - w.althandle = 0 - handle = w.handle - } - } - case 's': - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - w.oldpos = csbi.cursorPosition - case 'u': - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) - } - } - - return len(data), nil -} - -type consoleColor struct { - rgb int - red bool - green bool - blue bool - intensity bool -} - -func (c consoleColor) foregroundAttr() (attr word) { - if c.red { - attr |= foregroundRed - } - if c.green { - attr |= foregroundGreen - } - if c.blue { - attr |= foregroundBlue - } - if c.intensity { - attr |= foregroundIntensity - } - return -} - -func (c consoleColor) backgroundAttr() (attr word) { - if c.red { - attr |= backgroundRed - } - if c.green { - attr |= backgroundGreen - } - if c.blue { - attr |= backgroundBlue - } - if c.intensity { - attr |= backgroundIntensity - } - return -} - -var color16 = []consoleColor{ - {0x000000, false, false, false, false}, - {0x000080, false, false, true, false}, - {0x008000, false, true, false, false}, - {0x008080, false, true, true, false}, - {0x800000, true, false, false, false}, - {0x800080, true, false, true, false}, - {0x808000, true, true, false, false}, - {0xc0c0c0, true, true, true, false}, - {0x808080, false, false, false, true}, - {0x0000ff, false, false, true, true}, - {0x00ff00, false, true, false, true}, - {0x00ffff, false, true, true, true}, - {0xff0000, true, false, false, true}, - {0xff00ff, true, false, true, true}, - {0xffff00, true, true, false, true}, - {0xffffff, true, true, true, true}, -} - -type hsv struct { - h, s, v float32 -} - -func (a hsv) dist(b hsv) float32 { - dh := a.h - b.h - switch { - case dh > 0.5: - dh = 1 - dh - case dh < -0.5: - dh = -1 - dh - } - ds := a.s - b.s - dv := a.v - b.v - return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv))) -} - -func toHSV(rgb int) hsv { - r, g, b := float32((rgb&0xFF0000)>>16)/256.0, - float32((rgb&0x00FF00)>>8)/256.0, - float32(rgb&0x0000FF)/256.0 - min, max := minmax3f(r, g, b) - h := max - min - if h > 0 { - if max == r { - h = (g - b) / h - if h < 0 { - h += 6 - } - } else if max == g { - h = 2 + (b-r)/h - } else { - h = 4 + (r-g)/h - } - } - h /= 6.0 - s := max - min - if max != 0 { - s /= max - } - v := max - return hsv{h: h, s: s, v: v} -} - -type hsvTable []hsv - -func toHSVTable(rgbTable []consoleColor) hsvTable { - t := make(hsvTable, len(rgbTable)) - for i, c := range rgbTable { - t[i] = toHSV(c.rgb) - } - return t -} - -func (t hsvTable) find(rgb int) consoleColor { - hsv := toHSV(rgb) - n := 7 - l := float32(5.0) - for i, p := range t { - d := hsv.dist(p) - if d < l { - l, n = d, i - } - } - return color16[n] -} - -func minmax3f(a, b, c float32) (min, max float32) { - if a < b { - if b < c { - return a, c - } else if a < c { - return a, b - } else { - return c, b - } - } else { - if a < c { - return b, c - } else if b < c { - return b, a - } else { - return c, a - } - } -} - -var n256foreAttr []word -var n256backAttr []word - -func n256setup() { - n256foreAttr = make([]word, 256) - n256backAttr = make([]word, 256) - t := toHSVTable(color16) - for i, rgb := range color256 { - c := t.find(rgb) - n256foreAttr[i] = c.foregroundAttr() - n256backAttr[i] = c.backgroundAttr() - } -} - -// EnableColorsStdout enable colors if possible. -func EnableColorsStdout(enabled *bool) func() { - var mode uint32 - h := os.Stdout.Fd() - if r, _, _ := procGetConsoleMode.Call(h, uintptr(unsafe.Pointer(&mode))); r != 0 { - if r, _, _ = procSetConsoleMode.Call(h, uintptr(mode|cENABLE_VIRTUAL_TERMINAL_PROCESSING)); r != 0 { - if enabled != nil { - *enabled = true - } - return func() { - procSetConsoleMode.Call(h, uintptr(mode)) - } - } - } - if enabled != nil { - *enabled = true - } - return func() {} -} diff --git a/vendor/github.com/mattn/go-colorable/go.test.sh b/vendor/github.com/mattn/go-colorable/go.test.sh deleted file mode 100644 index 012162b..0000000 --- a/vendor/github.com/mattn/go-colorable/go.test.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env bash - -set -e -echo "" > coverage.txt - -for d in $(go list ./... | grep -v vendor); do - go test -race -coverprofile=profile.out -covermode=atomic "$d" - if [ -f profile.out ]; then - cat profile.out >> coverage.txt - rm profile.out - fi -done diff --git a/vendor/github.com/mattn/go-colorable/noncolorable.go b/vendor/github.com/mattn/go-colorable/noncolorable.go deleted file mode 100644 index 05d6f74..0000000 --- a/vendor/github.com/mattn/go-colorable/noncolorable.go +++ /dev/null @@ -1,57 +0,0 @@ -package colorable - -import ( - "bytes" - "io" -) - -// NonColorable holds writer but removes escape sequence. -type NonColorable struct { - out io.Writer -} - -// NewNonColorable returns new instance of Writer which removes escape sequence from Writer. -func NewNonColorable(w io.Writer) io.Writer { - return &NonColorable{out: w} -} - -// Write writes data on console -func (w *NonColorable) Write(data []byte) (n int, err error) { - er := bytes.NewReader(data) - var plaintext bytes.Buffer -loop: - for { - c1, err := er.ReadByte() - if err != nil { - plaintext.WriteTo(w.out) - break loop - } - if c1 != 0x1b { - plaintext.WriteByte(c1) - continue - } - _, err = plaintext.WriteTo(w.out) - if err != nil { - break loop - } - c2, err := er.ReadByte() - if err != nil { - break loop - } - if c2 != 0x5b { - continue - } - - for { - c, err := er.ReadByte() - if err != nil { - break loop - } - if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { - break - } - } - } - - return len(data), nil -} diff --git a/vendor/github.com/mattn/go-isatty/LICENSE b/vendor/github.com/mattn/go-isatty/LICENSE deleted file mode 100644 index 65dc692..0000000 --- a/vendor/github.com/mattn/go-isatty/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -Copyright (c) Yasuhiro MATSUMOTO - -MIT License (Expat) - -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. diff --git a/vendor/github.com/mattn/go-isatty/README.md b/vendor/github.com/mattn/go-isatty/README.md deleted file mode 100644 index 3841835..0000000 --- a/vendor/github.com/mattn/go-isatty/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# go-isatty - -[![Godoc Reference](https://godoc.org/github.com/mattn/go-isatty?status.svg)](http://godoc.org/github.com/mattn/go-isatty) -[![Codecov](https://codecov.io/gh/mattn/go-isatty/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-isatty) -[![Coverage Status](https://coveralls.io/repos/github/mattn/go-isatty/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-isatty?branch=master) -[![Go Report Card](https://goreportcard.com/badge/mattn/go-isatty)](https://goreportcard.com/report/mattn/go-isatty) - -isatty for golang - -## Usage - -```go -package main - -import ( - "fmt" - "github.com/mattn/go-isatty" - "os" -) - -func main() { - if isatty.IsTerminal(os.Stdout.Fd()) { - fmt.Println("Is Terminal") - } else if isatty.IsCygwinTerminal(os.Stdout.Fd()) { - fmt.Println("Is Cygwin/MSYS2 Terminal") - } else { - fmt.Println("Is Not Terminal") - } -} -``` - -## Installation - -``` -$ go get github.com/mattn/go-isatty -``` - -## License - -MIT - -## Author - -Yasuhiro Matsumoto (a.k.a mattn) - -## Thanks - -* k-takata: base idea for IsCygwinTerminal - - https://github.com/k-takata/go-iscygpty diff --git a/vendor/github.com/mattn/go-isatty/doc.go b/vendor/github.com/mattn/go-isatty/doc.go deleted file mode 100644 index 17d4f90..0000000 --- a/vendor/github.com/mattn/go-isatty/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package isatty implements interface to isatty -package isatty diff --git a/vendor/github.com/mattn/go-isatty/go.test.sh b/vendor/github.com/mattn/go-isatty/go.test.sh deleted file mode 100644 index 012162b..0000000 --- a/vendor/github.com/mattn/go-isatty/go.test.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env bash - -set -e -echo "" > coverage.txt - -for d in $(go list ./... | grep -v vendor); do - go test -race -coverprofile=profile.out -covermode=atomic "$d" - if [ -f profile.out ]; then - cat profile.out >> coverage.txt - rm profile.out - fi -done diff --git a/vendor/github.com/mattn/go-isatty/isatty_bsd.go b/vendor/github.com/mattn/go-isatty/isatty_bsd.go deleted file mode 100644 index d0ea68f..0000000 --- a/vendor/github.com/mattn/go-isatty/isatty_bsd.go +++ /dev/null @@ -1,20 +0,0 @@ -//go:build (darwin || freebsd || openbsd || netbsd || dragonfly || hurd) && !appengine && !tinygo -// +build darwin freebsd openbsd netbsd dragonfly hurd -// +build !appengine -// +build !tinygo - -package isatty - -import "golang.org/x/sys/unix" - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - _, err := unix.IoctlGetTermios(int(fd), unix.TIOCGETA) - return err == nil -} - -// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_others.go b/vendor/github.com/mattn/go-isatty/isatty_others.go deleted file mode 100644 index 7402e06..0000000 --- a/vendor/github.com/mattn/go-isatty/isatty_others.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build (appengine || js || nacl || tinygo || wasm) && !windows -// +build appengine js nacl tinygo wasm -// +build !windows - -package isatty - -// IsTerminal returns true if the file descriptor is terminal which -// is always false on js and appengine classic which is a sandboxed PaaS. -func IsTerminal(fd uintptr) bool { - return false -} - -// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_plan9.go b/vendor/github.com/mattn/go-isatty/isatty_plan9.go deleted file mode 100644 index bae7f9b..0000000 --- a/vendor/github.com/mattn/go-isatty/isatty_plan9.go +++ /dev/null @@ -1,23 +0,0 @@ -//go:build plan9 -// +build plan9 - -package isatty - -import ( - "syscall" -) - -// IsTerminal returns true if the given file descriptor is a terminal. -func IsTerminal(fd uintptr) bool { - path, err := syscall.Fd2path(int(fd)) - if err != nil { - return false - } - return path == "/dev/cons" || path == "/mnt/term/dev/cons" -} - -// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_solaris.go b/vendor/github.com/mattn/go-isatty/isatty_solaris.go deleted file mode 100644 index 0c3acf2..0000000 --- a/vendor/github.com/mattn/go-isatty/isatty_solaris.go +++ /dev/null @@ -1,21 +0,0 @@ -//go:build solaris && !appengine -// +build solaris,!appengine - -package isatty - -import ( - "golang.org/x/sys/unix" -) - -// IsTerminal returns true if the given file descriptor is a terminal. -// see: https://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libc/port/gen/isatty.c -func IsTerminal(fd uintptr) bool { - _, err := unix.IoctlGetTermio(int(fd), unix.TCGETA) - return err == nil -} - -// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_tcgets.go b/vendor/github.com/mattn/go-isatty/isatty_tcgets.go deleted file mode 100644 index 0337d8c..0000000 --- a/vendor/github.com/mattn/go-isatty/isatty_tcgets.go +++ /dev/null @@ -1,20 +0,0 @@ -//go:build (linux || aix || zos) && !appengine && !tinygo -// +build linux aix zos -// +build !appengine -// +build !tinygo - -package isatty - -import "golang.org/x/sys/unix" - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - _, err := unix.IoctlGetTermios(int(fd), unix.TCGETS) - return err == nil -} - -// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_windows.go b/vendor/github.com/mattn/go-isatty/isatty_windows.go deleted file mode 100644 index 8e3c991..0000000 --- a/vendor/github.com/mattn/go-isatty/isatty_windows.go +++ /dev/null @@ -1,125 +0,0 @@ -//go:build windows && !appengine -// +build windows,!appengine - -package isatty - -import ( - "errors" - "strings" - "syscall" - "unicode/utf16" - "unsafe" -) - -const ( - objectNameInfo uintptr = 1 - fileNameInfo = 2 - fileTypePipe = 3 -) - -var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - ntdll = syscall.NewLazyDLL("ntdll.dll") - procGetConsoleMode = kernel32.NewProc("GetConsoleMode") - procGetFileInformationByHandleEx = kernel32.NewProc("GetFileInformationByHandleEx") - procGetFileType = kernel32.NewProc("GetFileType") - procNtQueryObject = ntdll.NewProc("NtQueryObject") -) - -func init() { - // Check if GetFileInformationByHandleEx is available. - if procGetFileInformationByHandleEx.Find() != nil { - procGetFileInformationByHandleEx = nil - } -} - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var st uint32 - r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) - return r != 0 && e == 0 -} - -// Check pipe name is used for cygwin/msys2 pty. -// Cygwin/MSYS2 PTY has a name like: -// \{cygwin,msys}-XXXXXXXXXXXXXXXX-ptyN-{from,to}-master -func isCygwinPipeName(name string) bool { - token := strings.Split(name, "-") - if len(token) < 5 { - return false - } - - if token[0] != `\msys` && - token[0] != `\cygwin` && - token[0] != `\Device\NamedPipe\msys` && - token[0] != `\Device\NamedPipe\cygwin` { - return false - } - - if token[1] == "" { - return false - } - - if !strings.HasPrefix(token[2], "pty") { - return false - } - - if token[3] != `from` && token[3] != `to` { - return false - } - - if token[4] != "master" { - return false - } - - return true -} - -// getFileNameByHandle use the undocomented ntdll NtQueryObject to get file full name from file handler -// since GetFileInformationByHandleEx is not available under windows Vista and still some old fashion -// guys are using Windows XP, this is a workaround for those guys, it will also work on system from -// Windows vista to 10 -// see https://stackoverflow.com/a/18792477 for details -func getFileNameByHandle(fd uintptr) (string, error) { - if procNtQueryObject == nil { - return "", errors.New("ntdll.dll: NtQueryObject not supported") - } - - var buf [4 + syscall.MAX_PATH]uint16 - var result int - r, _, e := syscall.Syscall6(procNtQueryObject.Addr(), 5, - fd, objectNameInfo, uintptr(unsafe.Pointer(&buf)), uintptr(2*len(buf)), uintptr(unsafe.Pointer(&result)), 0) - if r != 0 { - return "", e - } - return string(utf16.Decode(buf[4 : 4+buf[0]/2])), nil -} - -// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 -// terminal. -func IsCygwinTerminal(fd uintptr) bool { - if procGetFileInformationByHandleEx == nil { - name, err := getFileNameByHandle(fd) - if err != nil { - return false - } - return isCygwinPipeName(name) - } - - // Cygwin/msys's pty is a pipe. - ft, _, e := syscall.Syscall(procGetFileType.Addr(), 1, fd, 0, 0) - if ft != fileTypePipe || e != 0 { - return false - } - - var buf [2 + syscall.MAX_PATH]uint16 - r, _, e := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), - 4, fd, fileNameInfo, uintptr(unsafe.Pointer(&buf)), - uintptr(len(buf)*2), 0, 0) - if r == 0 || e != 0 { - return false - } - - l := *(*uint32)(unsafe.Pointer(&buf)) - return isCygwinPipeName(string(utf16.Decode(buf[2 : 2+l/2]))) -} diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore deleted file mode 100644 index daf913b..0000000 --- a/vendor/github.com/pkg/errors/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml deleted file mode 100644 index 9159de0..0000000 --- a/vendor/github.com/pkg/errors/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: go -go_import_path: github.com/pkg/errors -go: - - 1.11.x - - 1.12.x - - 1.13.x - - tip - -script: - - make check diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE deleted file mode 100644 index 835ba3e..0000000 --- a/vendor/github.com/pkg/errors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2015, Dave Cheney -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/errors/Makefile b/vendor/github.com/pkg/errors/Makefile deleted file mode 100644 index ce9d7cd..0000000 --- a/vendor/github.com/pkg/errors/Makefile +++ /dev/null @@ -1,44 +0,0 @@ -PKGS := github.com/pkg/errors -SRCDIRS := $(shell go list -f '{{.Dir}}' $(PKGS)) -GO := go - -check: test vet gofmt misspell unconvert staticcheck ineffassign unparam - -test: - $(GO) test $(PKGS) - -vet: | test - $(GO) vet $(PKGS) - -staticcheck: - $(GO) get honnef.co/go/tools/cmd/staticcheck - staticcheck -checks all $(PKGS) - -misspell: - $(GO) get github.com/client9/misspell/cmd/misspell - misspell \ - -locale GB \ - -error \ - *.md *.go - -unconvert: - $(GO) get github.com/mdempsky/unconvert - unconvert -v $(PKGS) - -ineffassign: - $(GO) get github.com/gordonklaus/ineffassign - find $(SRCDIRS) -name '*.go' | xargs ineffassign - -pedantic: check errcheck - -unparam: - $(GO) get mvdan.cc/unparam - unparam ./... - -errcheck: - $(GO) get github.com/kisielk/errcheck - errcheck $(PKGS) - -gofmt: - @echo Checking code is gofmted - @test -z "$(shell gofmt -s -l -d -e $(SRCDIRS) | tee /dev/stderr)" diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 54dfdcb..0000000 --- a/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) [![Sourcegraph](https://sourcegraph.com/github.com/pkg/errors/-/badge.svg)](https://sourcegraph.com/github.com/pkg/errors?badge) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. - -## Adding context to an error - -The errors.Wrap function returns a new error that adds context to the original error. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## Retrieving the cause of an error - -Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Roadmap - -With the upcoming [Go2 error proposals](https://go.googlesource.com/proposal/+/master/design/go2draft.md) this package is moving into maintenance mode. The roadmap for a 1.0 release is as follows: - -- 0.9. Remove pre Go 1.9 and Go 1.10 support, address outstanding pull requests (if possible) -- 1.0. Final release. - -## Contributing - -Because of the Go2 errors changes, this package is not accepting proposals for new functionality. With that said, we welcome pull requests, bug fixes and issue reports. - -Before sending a PR, please discuss your change by raising an issue. - -## License - -BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932ead..0000000 --- a/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go deleted file mode 100644 index 161aea2..0000000 --- a/vendor/github.com/pkg/errors/errors.go +++ /dev/null @@ -1,288 +0,0 @@ -// Package errors provides simple error handling primitives. -// -// The traditional error handling idiom in Go is roughly akin to -// -// if err != nil { -// return err -// } -// -// which when applied recursively up the call stack results in error reports -// without context or debugging information. The errors package allows -// programmers to add context to the failure path in their code in a way -// that does not destroy the original value of the error. -// -// Adding context to an error -// -// The errors.Wrap function returns a new error that adds context to the -// original error by recording a stack trace at the point Wrap is called, -// together with the supplied message. For example -// -// _, err := ioutil.ReadAll(r) -// if err != nil { -// return errors.Wrap(err, "read failed") -// } -// -// If additional control is required, the errors.WithStack and -// errors.WithMessage functions destructure errors.Wrap into its component -// operations: annotating an error with a stack trace and with a message, -// respectively. -// -// Retrieving the cause of an error -// -// Using errors.Wrap constructs a stack of errors, adding context to the -// preceding error. Depending on the nature of the error it may be necessary -// to reverse the operation of errors.Wrap to retrieve the original error -// for inspection. Any error value which implements this interface -// -// type causer interface { -// Cause() error -// } -// -// can be inspected by errors.Cause. errors.Cause will recursively retrieve -// the topmost error that does not implement causer, which is assumed to be -// the original cause. For example: -// -// switch err := errors.Cause(err).(type) { -// case *MyError: -// // handle specifically -// default: -// // unknown error -// } -// -// Although the causer interface is not exported by this package, it is -// considered a part of its stable public interface. -// -// Formatted printing of errors -// -// All error values returned from this package implement fmt.Formatter and can -// be formatted by the fmt package. The following verbs are supported: -// -// %s print the error. If the error has a Cause it will be -// printed recursively. -// %v see %s -// %+v extended format. Each Frame of the error's StackTrace will -// be printed in detail. -// -// Retrieving the stack trace of an error or wrapper -// -// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are -// invoked. This information can be retrieved with the following interface: -// -// type stackTracer interface { -// StackTrace() errors.StackTrace -// } -// -// The returned errors.StackTrace type is defined as -// -// type StackTrace []Frame -// -// The Frame type represents a call site in the stack trace. Frame supports -// the fmt.Formatter interface that can be used for printing information about -// the stack trace of this error. For example: -// -// if err, ok := err.(stackTracer); ok { -// for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d\n", f, f) -// } -// } -// -// Although the stackTracer interface is not exported by this package, it is -// considered a part of its stable public interface. -// -// See the documentation for Frame.Format for more details. -package errors - -import ( - "fmt" - "io" -) - -// New returns an error with the supplied message. -// New also records the stack trace at the point it was called. -func New(message string) error { - return &fundamental{ - msg: message, - stack: callers(), - } -} - -// Errorf formats according to a format specifier and returns the string -// as a value that satisfies error. -// Errorf also records the stack trace at the point it was called. -func Errorf(format string, args ...interface{}) error { - return &fundamental{ - msg: fmt.Sprintf(format, args...), - stack: callers(), - } -} - -// fundamental is an error that has a message and a stack, but no caller. -type fundamental struct { - msg string - *stack -} - -func (f *fundamental) Error() string { return f.msg } - -func (f *fundamental) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} - -// WithStack annotates err with a stack trace at the point WithStack was called. -// If err is nil, WithStack returns nil. -func WithStack(err error) error { - if err == nil { - return nil - } - return &withStack{ - err, - callers(), - } -} - -type withStack struct { - error - *stack -} - -func (w *withStack) Cause() error { return w.error } - -// Unwrap provides compatibility for Go 1.13 error chains. -func (w *withStack) Unwrap() error { return w.error } - -func (w *withStack) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v", w.Cause()) - w.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, w.Error()) - case 'q': - fmt.Fprintf(s, "%q", w.Error()) - } -} - -// Wrap returns an error annotating err with a stack trace -// at the point Wrap is called, and the supplied message. -// If err is nil, Wrap returns nil. -func Wrap(err error, message string) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: message, - } - return &withStack{ - err, - callers(), - } -} - -// Wrapf returns an error annotating err with a stack trace -// at the point Wrapf is called, and the format specifier. -// If err is nil, Wrapf returns nil. -func Wrapf(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } - return &withStack{ - err, - callers(), - } -} - -// WithMessage annotates err with a new message. -// If err is nil, WithMessage returns nil. -func WithMessage(err error, message string) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: message, - } -} - -// WithMessagef annotates err with the format specifier. -// If err is nil, WithMessagef returns nil. -func WithMessagef(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } -} - -type withMessage struct { - cause error - msg string -} - -func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } -func (w *withMessage) Cause() error { return w.cause } - -// Unwrap provides compatibility for Go 1.13 error chains. -func (w *withMessage) Unwrap() error { return w.cause } - -func (w *withMessage) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v\n", w.Cause()) - io.WriteString(s, w.msg) - return - } - fallthrough - case 's', 'q': - io.WriteString(s, w.Error()) - } -} - -// Cause returns the underlying cause of the error, if possible. -// An error value has a cause if it implements the following -// interface: -// -// type causer interface { -// Cause() error -// } -// -// If the error does not implement Cause, the original error will -// be returned. If the error is nil, nil will be returned without further -// investigation. -func Cause(err error) error { - type causer interface { - Cause() error - } - - for err != nil { - cause, ok := err.(causer) - if !ok { - break - } - err = cause.Cause() - } - return err -} diff --git a/vendor/github.com/pkg/errors/go113.go b/vendor/github.com/pkg/errors/go113.go deleted file mode 100644 index be0d10d..0000000 --- a/vendor/github.com/pkg/errors/go113.go +++ /dev/null @@ -1,38 +0,0 @@ -// +build go1.13 - -package errors - -import ( - stderrors "errors" -) - -// Is reports whether any error in err's chain matches target. -// -// The chain consists of err itself followed by the sequence of errors obtained by -// repeatedly calling Unwrap. -// -// An error is considered to match a target if it is equal to that target or if -// it implements a method Is(error) bool such that Is(target) returns true. -func Is(err, target error) bool { return stderrors.Is(err, target) } - -// As finds the first error in err's chain that matches target, and if so, sets -// target to that error value and returns true. -// -// The chain consists of err itself followed by the sequence of errors obtained by -// repeatedly calling Unwrap. -// -// An error matches target if the error's concrete value is assignable to the value -// pointed to by target, or if the error has a method As(interface{}) bool such that -// As(target) returns true. In the latter case, the As method is responsible for -// setting target. -// -// As will panic if target is not a non-nil pointer to either a type that implements -// error, or to any interface type. As returns false if err is nil. -func As(err error, target interface{}) bool { return stderrors.As(err, target) } - -// Unwrap returns the result of calling the Unwrap method on err, if err's -// type contains an Unwrap method returning error. -// Otherwise, Unwrap returns nil. -func Unwrap(err error) error { - return stderrors.Unwrap(err) -} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go deleted file mode 100644 index 779a834..0000000 --- a/vendor/github.com/pkg/errors/stack.go +++ /dev/null @@ -1,177 +0,0 @@ -package errors - -import ( - "fmt" - "io" - "path" - "runtime" - "strconv" - "strings" -) - -// Frame represents a program counter inside a stack frame. -// For historical reasons if Frame is interpreted as a uintptr -// its value represents the program counter + 1. -type Frame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f Frame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f Frame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f Frame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// name returns the name of this function, if known. -func (f Frame) name() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - return fn.Name() -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s function name and path of source file relative to the compile time -// GOPATH separated by \n\t (\n\t) -// %+v equivalent to %+s:%d -func (f Frame) Format(s fmt.State, verb rune) { - switch verb { - case 's': - switch { - case s.Flag('+'): - io.WriteString(s, f.name()) - io.WriteString(s, "\n\t") - io.WriteString(s, f.file()) - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - io.WriteString(s, strconv.Itoa(f.line())) - case 'n': - io.WriteString(s, funcname(f.name())) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// MarshalText formats a stacktrace Frame as a text string. The output is the -// same as that of fmt.Sprintf("%+v", f), but without newlines or tabs. -func (f Frame) MarshalText() ([]byte, error) { - name := f.name() - if name == "unknown" { - return []byte(name), nil - } - return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil -} - -// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). -type StackTrace []Frame - -// Format formats the stack of Frames according to the fmt.Formatter interface. -// -// %s lists source files for each Frame in the stack -// %v lists the source file and line number for each Frame in the stack -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+v Prints filename, function, and line number for each Frame in the stack. -func (st StackTrace) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case s.Flag('+'): - for _, f := range st { - io.WriteString(s, "\n") - f.Format(s, verb) - } - case s.Flag('#'): - fmt.Fprintf(s, "%#v", []Frame(st)) - default: - st.formatSlice(s, verb) - } - case 's': - st.formatSlice(s, verb) - } -} - -// formatSlice will format this StackTrace into the given buffer as a slice of -// Frame, only valid when called with '%s' or '%v'. -func (st StackTrace) formatSlice(s fmt.State, verb rune) { - io.WriteString(s, "[") - for i, f := range st { - if i > 0 { - io.WriteString(s, " ") - } - f.Format(s, verb) - } - io.WriteString(s, "]") -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := Frame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func (s *stack) StackTrace() StackTrace { - f := make([]Frame, len(*s)) - for i := 0; i < len(f); i++ { - f[i] = Frame((*s)[i]) - } - return f -} - -func callers() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// funcname removes the path prefix component of a function's name reported by func.Name(). -func funcname(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] -} diff --git a/vendor/github.com/rs/zerolog/.gitignore b/vendor/github.com/rs/zerolog/.gitignore deleted file mode 100644 index 8ebe58b..0000000 --- a/vendor/github.com/rs/zerolog/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test -tmp - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/rs/zerolog/CNAME b/vendor/github.com/rs/zerolog/CNAME deleted file mode 100644 index 9ce57a6..0000000 --- a/vendor/github.com/rs/zerolog/CNAME +++ /dev/null @@ -1 +0,0 @@ -zerolog.io \ No newline at end of file diff --git a/vendor/github.com/rs/zerolog/LICENSE b/vendor/github.com/rs/zerolog/LICENSE deleted file mode 100644 index 677e07f..0000000 --- a/vendor/github.com/rs/zerolog/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 Olivier Poitrey - -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. diff --git a/vendor/github.com/rs/zerolog/README.md b/vendor/github.com/rs/zerolog/README.md deleted file mode 100644 index 1306a6c..0000000 --- a/vendor/github.com/rs/zerolog/README.md +++ /dev/null @@ -1,782 +0,0 @@ -# Zero Allocation JSON Logger - -[![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/rs/zerolog) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/zerolog/master/LICENSE) [![Build Status](https://github.com/rs/zerolog/actions/workflows/test.yml/badge.svg)](https://github.com/rs/zerolog/actions/workflows/test.yml) [![Go Coverage](https://github.com/rs/zerolog/wiki/coverage.svg)](https://raw.githack.com/wiki/rs/zerolog/coverage.html) - -The zerolog package provides a fast and simple logger dedicated to JSON output. - -Zerolog's API is designed to provide both a great developer experience and stunning [performance](#benchmarks). Its unique chaining API allows zerolog to write JSON (or CBOR) log events by avoiding allocations and reflection. - -Uber's [zap](https://godoc.org/go.uber.org/zap) library pioneered this approach. Zerolog is taking this concept to the next level with a simpler to use API and even better performance. - -To keep the code base and the API simple, zerolog focuses on efficient structured logging only. Pretty logging on the console is made possible using the provided (but inefficient) [`zerolog.ConsoleWriter`](#pretty-logging). - -![Pretty Logging Image](pretty.png) - -## Who uses zerolog - -Find out [who uses zerolog](https://github.com/rs/zerolog/wiki/Who-uses-zerolog) and add your company / project to the list. - -## Features - -* [Blazing fast](#benchmarks) -* [Low to zero allocation](#benchmarks) -* [Leveled logging](#leveled-logging) -* [Sampling](#log-sampling) -* [Hooks](#hooks) -* [Contextual fields](#contextual-logging) -* [`context.Context` integration](#contextcontext-integration) -* [Integration with `net/http`](#integration-with-nethttp) -* [JSON and CBOR encoding formats](#binary-encoding) -* [Pretty logging for development](#pretty-logging) -* [Error Logging (with optional Stacktrace)](#error-logging) - -## Installation - -```bash -go get -u github.com/rs/zerolog/log -``` - -## Getting Started - -### Simple Logging Example - -For simple logging, import the global logger package **github.com/rs/zerolog/log** - -```go -package main - -import ( - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" -) - -func main() { - // UNIX Time is faster and smaller than most timestamps - zerolog.TimeFieldFormat = zerolog.TimeFormatUnix - - log.Print("hello world") -} - -// Output: {"time":1516134303,"level":"debug","message":"hello world"} -``` -> Note: By default log writes to `os.Stderr` -> Note: The default log level for `log.Print` is *trace* - -### Contextual Logging - -**zerolog** allows data to be added to log messages in the form of key:value pairs. The data added to the message adds "context" about the log event that can be critical for debugging as well as myriad other purposes. An example of this is below: - -```go -package main - -import ( - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" -) - -func main() { - zerolog.TimeFieldFormat = zerolog.TimeFormatUnix - - log.Debug(). - Str("Scale", "833 cents"). - Float64("Interval", 833.09). - Msg("Fibonacci is everywhere") - - log.Debug(). - Str("Name", "Tom"). - Send() -} - -// Output: {"level":"debug","Scale":"833 cents","Interval":833.09,"time":1562212768,"message":"Fibonacci is everywhere"} -// Output: {"level":"debug","Name":"Tom","time":1562212768} -``` - -> You'll note in the above example that when adding contextual fields, the fields are strongly typed. You can find the full list of supported fields [here](#standard-types) - -### Leveled Logging - -#### Simple Leveled Logging Example - -```go -package main - -import ( - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" -) - -func main() { - zerolog.TimeFieldFormat = zerolog.TimeFormatUnix - - log.Info().Msg("hello world") -} - -// Output: {"time":1516134303,"level":"info","message":"hello world"} -``` - -> It is very important to note that when using the **zerolog** chaining API, as shown above (`log.Info().Msg("hello world"`), the chain must have either the `Msg` or `Msgf` method call. If you forget to add either of these, the log will not occur and there is no compile time error to alert you of this. - -**zerolog** allows for logging at the following levels (from highest to lowest): - -* panic (`zerolog.PanicLevel`, 5) -* fatal (`zerolog.FatalLevel`, 4) -* error (`zerolog.ErrorLevel`, 3) -* warn (`zerolog.WarnLevel`, 2) -* info (`zerolog.InfoLevel`, 1) -* debug (`zerolog.DebugLevel`, 0) -* trace (`zerolog.TraceLevel`, -1) - -You can set the Global logging level to any of these options using the `SetGlobalLevel` function in the zerolog package, passing in one of the given constants above, e.g. `zerolog.InfoLevel` would be the "info" level. Whichever level is chosen, all logs with a level greater than or equal to that level will be written. To turn off logging entirely, pass the `zerolog.Disabled` constant. - -#### Setting Global Log Level - -This example uses command-line flags to demonstrate various outputs depending on the chosen log level. - -```go -package main - -import ( - "flag" - - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" -) - -func main() { - zerolog.TimeFieldFormat = zerolog.TimeFormatUnix - debug := flag.Bool("debug", false, "sets log level to debug") - - flag.Parse() - - // Default level for this example is info, unless debug flag is present - zerolog.SetGlobalLevel(zerolog.InfoLevel) - if *debug { - zerolog.SetGlobalLevel(zerolog.DebugLevel) - } - - log.Debug().Msg("This message appears only when log level set to Debug") - log.Info().Msg("This message appears when log level set to Debug or Info") - - if e := log.Debug(); e.Enabled() { - // Compute log output only if enabled. - value := "bar" - e.Str("foo", value).Msg("some debug message") - } -} -``` - -Info Output (no flag) - -```bash -$ ./logLevelExample -{"time":1516387492,"level":"info","message":"This message appears when log level set to Debug or Info"} -``` - -Debug Output (debug flag set) - -```bash -$ ./logLevelExample -debug -{"time":1516387573,"level":"debug","message":"This message appears only when log level set to Debug"} -{"time":1516387573,"level":"info","message":"This message appears when log level set to Debug or Info"} -{"time":1516387573,"level":"debug","foo":"bar","message":"some debug message"} -``` - -#### Logging without Level or Message - -You may choose to log without a specific level by using the `Log` method. You may also write without a message by setting an empty string in the `msg string` parameter of the `Msg` method. Both are demonstrated in the example below. - -```go -package main - -import ( - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" -) - -func main() { - zerolog.TimeFieldFormat = zerolog.TimeFormatUnix - - log.Log(). - Str("foo", "bar"). - Msg("") -} - -// Output: {"time":1494567715,"foo":"bar"} -``` - -### Error Logging - -You can log errors using the `Err` method - -```go -package main - -import ( - "errors" - - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" -) - -func main() { - zerolog.TimeFieldFormat = zerolog.TimeFormatUnix - - err := errors.New("seems we have an error here") - log.Error().Err(err).Msg("") -} - -// Output: {"level":"error","error":"seems we have an error here","time":1609085256} -``` - -> The default field name for errors is `error`, you can change this by setting `zerolog.ErrorFieldName` to meet your needs. - -#### Error Logging with Stacktrace - -Using `github.com/pkg/errors`, you can add a formatted stacktrace to your errors. - -```go -package main - -import ( - "github.com/pkg/errors" - "github.com/rs/zerolog/pkgerrors" - - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" -) - -func main() { - zerolog.TimeFieldFormat = zerolog.TimeFormatUnix - zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack - - err := outer() - log.Error().Stack().Err(err).Msg("") -} - -func inner() error { - return errors.New("seems we have an error here") -} - -func middle() error { - err := inner() - if err != nil { - return err - } - return nil -} - -func outer() error { - err := middle() - if err != nil { - return err - } - return nil -} - -// Output: {"level":"error","stack":[{"func":"inner","line":"20","source":"errors.go"},{"func":"middle","line":"24","source":"errors.go"},{"func":"outer","line":"32","source":"errors.go"},{"func":"main","line":"15","source":"errors.go"},{"func":"main","line":"204","source":"proc.go"},{"func":"goexit","line":"1374","source":"asm_amd64.s"}],"error":"seems we have an error here","time":1609086683} -``` - -> zerolog.ErrorStackMarshaler must be set in order for the stack to output anything. - -#### Logging Fatal Messages - -```go -package main - -import ( - "errors" - - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" -) - -func main() { - err := errors.New("A repo man spends his life getting into tense situations") - service := "myservice" - - zerolog.TimeFieldFormat = zerolog.TimeFormatUnix - - log.Fatal(). - Err(err). - Str("service", service). - Msgf("Cannot start %s", service) -} - -// Output: {"time":1516133263,"level":"fatal","error":"A repo man spends his life getting into tense situations","service":"myservice","message":"Cannot start myservice"} -// exit status 1 -``` - -> NOTE: Using `Msgf` generates one allocation even when the logger is disabled. - - -### Create logger instance to manage different outputs - -```go -logger := zerolog.New(os.Stderr).With().Timestamp().Logger() - -logger.Info().Str("foo", "bar").Msg("hello world") - -// Output: {"level":"info","time":1494567715,"message":"hello world","foo":"bar"} -``` - -### Sub-loggers let you chain loggers with additional context - -```go -sublogger := log.With(). - Str("component", "foo"). - Logger() -sublogger.Info().Msg("hello world") - -// Output: {"level":"info","time":1494567715,"message":"hello world","component":"foo"} -``` - -### Pretty logging - -To log a human-friendly, colorized output, use `zerolog.ConsoleWriter`: - -```go -log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) - -log.Info().Str("foo", "bar").Msg("Hello world") - -// Output: 3:04PM INF Hello World foo=bar -``` - -To customize the configuration and formatting: - -```go -output := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339} -output.FormatLevel = func(i interface{}) string { - return strings.ToUpper(fmt.Sprintf("| %-6s|", i)) -} -output.FormatMessage = func(i interface{}) string { - return fmt.Sprintf("***%s****", i) -} -output.FormatFieldName = func(i interface{}) string { - return fmt.Sprintf("%s:", i) -} -output.FormatFieldValue = func(i interface{}) string { - return strings.ToUpper(fmt.Sprintf("%s", i)) -} - -log := zerolog.New(output).With().Timestamp().Logger() - -log.Info().Str("foo", "bar").Msg("Hello World") - -// Output: 2006-01-02T15:04:05Z07:00 | INFO | ***Hello World**** foo:BAR -``` - -### Sub dictionary - -```go -log.Info(). - Str("foo", "bar"). - Dict("dict", zerolog.Dict(). - Str("bar", "baz"). - Int("n", 1), - ).Msg("hello world") - -// Output: {"level":"info","time":1494567715,"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"} -``` - -### Customize automatic field names - -```go -zerolog.TimestampFieldName = "t" -zerolog.LevelFieldName = "l" -zerolog.MessageFieldName = "m" - -log.Info().Msg("hello world") - -// Output: {"l":"info","t":1494567715,"m":"hello world"} -``` - -### Add contextual fields to the global logger - -```go -log.Logger = log.With().Str("foo", "bar").Logger() -``` - -### Add file and line number to log - -Equivalent of `Llongfile`: - -```go -log.Logger = log.With().Caller().Logger() -log.Info().Msg("hello world") - -// Output: {"level": "info", "message": "hello world", "caller": "/go/src/your_project/some_file:21"} -``` - -Equivalent of `Lshortfile`: - -```go -zerolog.CallerMarshalFunc = func(pc uintptr, file string, line int) string { - return filepath.Base(file) + ":" + strconv.Itoa(line) -} -log.Logger = log.With().Caller().Logger() -log.Info().Msg("hello world") - -// Output: {"level": "info", "message": "hello world", "caller": "some_file:21"} -``` - -### Thread-safe, lock-free, non-blocking writer - -If your writer might be slow or not thread-safe and you need your log producers to never get slowed down by a slow writer, you can use a `diode.Writer` as follows: - -```go -wr := diode.NewWriter(os.Stdout, 1000, 10*time.Millisecond, func(missed int) { - fmt.Printf("Logger Dropped %d messages", missed) - }) -log := zerolog.New(wr) -log.Print("test") -``` - -You will need to install `code.cloudfoundry.org/go-diodes` to use this feature. - -### Log Sampling - -```go -sampled := log.Sample(&zerolog.BasicSampler{N: 10}) -sampled.Info().Msg("will be logged every 10 messages") - -// Output: {"time":1494567715,"level":"info","message":"will be logged every 10 messages"} -``` - -More advanced sampling: - -```go -// Will let 5 debug messages per period of 1 second. -// Over 5 debug message, 1 every 100 debug messages are logged. -// Other levels are not sampled. -sampled := log.Sample(zerolog.LevelSampler{ - DebugSampler: &zerolog.BurstSampler{ - Burst: 5, - Period: 1*time.Second, - NextSampler: &zerolog.BasicSampler{N: 100}, - }, -}) -sampled.Debug().Msg("hello world") - -// Output: {"time":1494567715,"level":"debug","message":"hello world"} -``` - -### Hooks - -```go -type SeverityHook struct{} - -func (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) { - if level != zerolog.NoLevel { - e.Str("severity", level.String()) - } -} - -hooked := log.Hook(SeverityHook{}) -hooked.Warn().Msg("") - -// Output: {"level":"warn","severity":"warn"} -``` - -### Pass a sub-logger by context - -```go -ctx := log.With().Str("component", "module").Logger().WithContext(ctx) - -log.Ctx(ctx).Info().Msg("hello world") - -// Output: {"component":"module","level":"info","message":"hello world"} -``` - -### Set as standard logger output - -```go -log := zerolog.New(os.Stdout).With(). - Str("foo", "bar"). - Logger() - -stdlog.SetFlags(0) -stdlog.SetOutput(log) - -stdlog.Print("hello world") - -// Output: {"foo":"bar","message":"hello world"} -``` - -### context.Context integration - -Go contexts are commonly passed throughout Go code, and this can help you pass -your Logger into places it might otherwise be hard to inject. The `Logger` -instance may be attached to Go context (`context.Context`) using -`Logger.WithContext(ctx)` and extracted from it using `zerolog.Ctx(ctx)`. -For example: - -```go -func f() { - logger := zerolog.New(os.Stdout) - ctx := context.Background() - - // Attach the Logger to the context.Context - ctx = logger.WithContext(ctx) - someFunc(ctx) -} - -func someFunc(ctx context.Context) { - // Get Logger from the go Context. if it's nil, then - // `zerolog.DefaultContextLogger` is returned, if - // `DefaultContextLogger` is nil, then a disabled logger is returned. - logger := zerolog.Ctx(ctx) - logger.Info().Msg("Hello") -} -``` - -A second form of `context.Context` integration allows you to pass the current -context.Context into the logged event, and retrieve it from hooks. This can be -useful to log trace and span IDs or other information stored in the go context, -and facilitates the unification of logging and tracing in some systems: - -```go -type TracingHook struct{} - -func (h TracingHook) Run(e *zerolog.Event, level zerolog.Level, msg string) { - ctx := e.GetCtx() - spanId := getSpanIdFromContext(ctx) // as per your tracing framework - e.Str("span-id", spanId) -} - -func f() { - // Setup the logger - logger := zerolog.New(os.Stdout) - logger = logger.Hook(TracingHook{}) - - ctx := context.Background() - // Use the Ctx function to make the context available to the hook - logger.Info().Ctx(ctx).Msg("Hello") -} -``` - -### Integration with `net/http` - -The `github.com/rs/zerolog/hlog` package provides some helpers to integrate zerolog with `http.Handler`. - -In this example we use [alice](https://github.com/justinas/alice) to install logger for better readability. - -```go -log := zerolog.New(os.Stdout).With(). - Timestamp(). - Str("role", "my-service"). - Str("host", host). - Logger() - -c := alice.New() - -// Install the logger handler with default output on the console -c = c.Append(hlog.NewHandler(log)) - -// Install some provided extra handler to set some request's context fields. -// Thanks to that handler, all our logs will come with some prepopulated fields. -c = c.Append(hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) { - hlog.FromRequest(r).Info(). - Str("method", r.Method). - Stringer("url", r.URL). - Int("status", status). - Int("size", size). - Dur("duration", duration). - Msg("") -})) -c = c.Append(hlog.RemoteAddrHandler("ip")) -c = c.Append(hlog.UserAgentHandler("user_agent")) -c = c.Append(hlog.RefererHandler("referer")) -c = c.Append(hlog.RequestIDHandler("req_id", "Request-Id")) - -// Here is your final handler -h := c.Then(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Get the logger from the request's context. You can safely assume it - // will be always there: if the handler is removed, hlog.FromRequest - // will return a no-op logger. - hlog.FromRequest(r).Info(). - Str("user", "current user"). - Str("status", "ok"). - Msg("Something happened") - - // Output: {"level":"info","time":"2001-02-03T04:05:06Z","role":"my-service","host":"local-hostname","req_id":"b4g0l5t6tfid6dtrapu0","user":"current user","status":"ok","message":"Something happened"} -})) -http.Handle("/", h) - -if err := http.ListenAndServe(":8080", nil); err != nil { - log.Fatal().Err(err).Msg("Startup failed") -} -``` - -## Multiple Log Output -`zerolog.MultiLevelWriter` may be used to send the log message to multiple outputs. -In this example, we send the log message to both `os.Stdout` and the in-built ConsoleWriter. -```go -func main() { - consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout} - - multi := zerolog.MultiLevelWriter(consoleWriter, os.Stdout) - - logger := zerolog.New(multi).With().Timestamp().Logger() - - logger.Info().Msg("Hello World!") -} - -// Output (Line 1: Console; Line 2: Stdout) -// 12:36PM INF Hello World! -// {"level":"info","time":"2019-11-07T12:36:38+03:00","message":"Hello World!"} -``` - -## Global Settings - -Some settings can be changed and will be applied to all loggers: - -* `log.Logger`: You can set this value to customize the global logger (the one used by package level methods). -* `zerolog.SetGlobalLevel`: Can raise the minimum level of all loggers. Call this with `zerolog.Disabled` to disable logging altogether (quiet mode). -* `zerolog.DisableSampling`: If argument is `true`, all sampled loggers will stop sampling and issue 100% of their log events. -* `zerolog.TimestampFieldName`: Can be set to customize `Timestamp` field name. -* `zerolog.LevelFieldName`: Can be set to customize level field name. -* `zerolog.MessageFieldName`: Can be set to customize message field name. -* `zerolog.ErrorFieldName`: Can be set to customize `Err` field name. -* `zerolog.TimeFieldFormat`: Can be set to customize `Time` field value formatting. If set with `zerolog.TimeFormatUnix`, `zerolog.TimeFormatUnixMs` or `zerolog.TimeFormatUnixMicro`, times are formatted as UNIX timestamp. -* `zerolog.DurationFieldUnit`: Can be set to customize the unit for time.Duration type fields added by `Dur` (default: `time.Millisecond`). -* `zerolog.DurationFieldInteger`: If set to `true`, `Dur` fields are formatted as integers instead of floats (default: `false`). -* `zerolog.ErrorHandler`: Called whenever zerolog fails to write an event on its output. If not set, an error is printed on the stderr. This handler must be thread safe and non-blocking. -* `zerolog.FloatingPointPrecision`: If set to a value other than -1, controls the number -of digits when formatting float numbers in JSON. See -[strconv.FormatFloat](https://pkg.go.dev/strconv#FormatFloat) -for more details. - -## Field Types - -### Standard Types - -* `Str` -* `Bool` -* `Int`, `Int8`, `Int16`, `Int32`, `Int64` -* `Uint`, `Uint8`, `Uint16`, `Uint32`, `Uint64` -* `Float32`, `Float64` - -### Advanced Fields - -* `Err`: Takes an `error` and renders it as a string using the `zerolog.ErrorFieldName` field name. -* `Func`: Run a `func` only if the level is enabled. -* `Timestamp`: Inserts a timestamp field with `zerolog.TimestampFieldName` field name, formatted using `zerolog.TimeFieldFormat`. -* `Time`: Adds a field with time formatted with `zerolog.TimeFieldFormat`. -* `Dur`: Adds a field with `time.Duration`. -* `Dict`: Adds a sub-key/value as a field of the event. -* `RawJSON`: Adds a field with an already encoded JSON (`[]byte`) -* `Hex`: Adds a field with value formatted as a hexadecimal string (`[]byte`) -* `Interface`: Uses reflection to marshal the type. - -Most fields are also available in the slice format (`Strs` for `[]string`, `Errs` for `[]error` etc.) - -## Binary Encoding - -In addition to the default JSON encoding, `zerolog` can produce binary logs using [CBOR](https://cbor.io) encoding. The choice of encoding can be decided at compile time using the build tag `binary_log` as follows: - -```bash -go build -tags binary_log . -``` - -To Decode binary encoded log files you can use any CBOR decoder. One has been tested to work -with zerolog library is [CSD](https://github.com/toravir/csd/). - -## Related Projects - -* [grpc-zerolog](https://github.com/cheapRoc/grpc-zerolog): Implementation of `grpclog.LoggerV2` interface using `zerolog` -* [overlog](https://github.com/Trendyol/overlog): Implementation of `Mapped Diagnostic Context` interface using `zerolog` -* [zerologr](https://github.com/go-logr/zerologr): Implementation of `logr.LogSink` interface using `zerolog` - -## Benchmarks - -See [logbench](http://bench.zerolog.io/) for more comprehensive and up-to-date benchmarks. - -All operations are allocation free (those numbers *include* JSON encoding): - -```text -BenchmarkLogEmpty-8 100000000 19.1 ns/op 0 B/op 0 allocs/op -BenchmarkDisabled-8 500000000 4.07 ns/op 0 B/op 0 allocs/op -BenchmarkInfo-8 30000000 42.5 ns/op 0 B/op 0 allocs/op -BenchmarkContextFields-8 30000000 44.9 ns/op 0 B/op 0 allocs/op -BenchmarkLogFields-8 10000000 184 ns/op 0 B/op 0 allocs/op -``` - -There are a few Go logging benchmarks and comparisons that include zerolog. - -* [imkira/go-loggers-bench](https://github.com/imkira/go-loggers-bench) -* [uber-common/zap](https://github.com/uber-go/zap#performance) - -Using Uber's zap comparison benchmark: - -Log a message and 10 fields: - -| Library | Time | Bytes Allocated | Objects Allocated | -| :--- | :---: | :---: | :---: | -| zerolog | 767 ns/op | 552 B/op | 6 allocs/op | -| :zap: zap | 848 ns/op | 704 B/op | 2 allocs/op | -| :zap: zap (sugared) | 1363 ns/op | 1610 B/op | 20 allocs/op | -| go-kit | 3614 ns/op | 2895 B/op | 66 allocs/op | -| lion | 5392 ns/op | 5807 B/op | 63 allocs/op | -| logrus | 5661 ns/op | 6092 B/op | 78 allocs/op | -| apex/log | 15332 ns/op | 3832 B/op | 65 allocs/op | -| log15 | 20657 ns/op | 5632 B/op | 93 allocs/op | - -Log a message with a logger that already has 10 fields of context: - -| Library | Time | Bytes Allocated | Objects Allocated | -| :--- | :---: | :---: | :---: | -| zerolog | 52 ns/op | 0 B/op | 0 allocs/op | -| :zap: zap | 283 ns/op | 0 B/op | 0 allocs/op | -| :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op | -| lion | 2702 ns/op | 4074 B/op | 38 allocs/op | -| go-kit | 3378 ns/op | 3046 B/op | 52 allocs/op | -| logrus | 4309 ns/op | 4564 B/op | 63 allocs/op | -| apex/log | 13456 ns/op | 2898 B/op | 51 allocs/op | -| log15 | 14179 ns/op | 2642 B/op | 44 allocs/op | - -Log a static string, without any context or `printf`-style templating: - -| Library | Time | Bytes Allocated | Objects Allocated | -| :--- | :---: | :---: | :---: | -| zerolog | 50 ns/op | 0 B/op | 0 allocs/op | -| :zap: zap | 236 ns/op | 0 B/op | 0 allocs/op | -| standard library | 453 ns/op | 80 B/op | 2 allocs/op | -| :zap: zap (sugared) | 337 ns/op | 80 B/op | 2 allocs/op | -| go-kit | 508 ns/op | 656 B/op | 13 allocs/op | -| lion | 771 ns/op | 1224 B/op | 10 allocs/op | -| logrus | 1244 ns/op | 1505 B/op | 27 allocs/op | -| apex/log | 2751 ns/op | 584 B/op | 11 allocs/op | -| log15 | 5181 ns/op | 1592 B/op | 26 allocs/op | - -## Caveats - -### Field duplication - -Note that zerolog does no de-duplication of fields. Using the same key multiple times creates multiple keys in final JSON: - -```go -logger := zerolog.New(os.Stderr).With().Timestamp().Logger() -logger.Info(). - Timestamp(). - Msg("dup") -// Output: {"level":"info","time":1494567715,"time":1494567715,"message":"dup"} -``` - -In this case, many consumers will take the last value, but this is not guaranteed; check yours if in doubt. - -### Concurrency safety - -Be careful when calling UpdateContext. It is not concurrency safe. Use the With method to create a child logger: - -```go -func handler(w http.ResponseWriter, r *http.Request) { - // Create a child logger for concurrency safety - logger := log.Logger.With().Logger() - - // Add context fields, for example User-Agent from HTTP headers - logger.UpdateContext(func(c zerolog.Context) zerolog.Context { - ... - }) -} -``` diff --git a/vendor/github.com/rs/zerolog/_config.yml b/vendor/github.com/rs/zerolog/_config.yml deleted file mode 100644 index a1e896d..0000000 --- a/vendor/github.com/rs/zerolog/_config.yml +++ /dev/null @@ -1 +0,0 @@ -remote_theme: rs/gh-readme diff --git a/vendor/github.com/rs/zerolog/array.go b/vendor/github.com/rs/zerolog/array.go deleted file mode 100644 index ba35b28..0000000 --- a/vendor/github.com/rs/zerolog/array.go +++ /dev/null @@ -1,240 +0,0 @@ -package zerolog - -import ( - "net" - "sync" - "time" -) - -var arrayPool = &sync.Pool{ - New: func() interface{} { - return &Array{ - buf: make([]byte, 0, 500), - } - }, -} - -// Array is used to prepopulate an array of items -// which can be re-used to add to log messages. -type Array struct { - buf []byte -} - -func putArray(a *Array) { - // Proper usage of a sync.Pool requires each entry to have approximately - // the same memory cost. To obtain this property when the stored type - // contains a variably-sized buffer, we add a hard limit on the maximum buffer - // to place back in the pool. - // - // See https://golang.org/issue/23199 - const maxSize = 1 << 16 // 64KiB - if cap(a.buf) > maxSize { - return - } - arrayPool.Put(a) -} - -// Arr creates an array to be added to an Event or Context. -func Arr() *Array { - a := arrayPool.Get().(*Array) - a.buf = a.buf[:0] - return a -} - -// MarshalZerologArray method here is no-op - since data is -// already in the needed format. -func (*Array) MarshalZerologArray(*Array) { -} - -func (a *Array) write(dst []byte) []byte { - dst = enc.AppendArrayStart(dst) - if len(a.buf) > 0 { - dst = append(dst, a.buf...) - } - dst = enc.AppendArrayEnd(dst) - putArray(a) - return dst -} - -// Object marshals an object that implement the LogObjectMarshaler -// interface and appends it to the array. -func (a *Array) Object(obj LogObjectMarshaler) *Array { - e := Dict() - obj.MarshalZerologObject(e) - e.buf = enc.AppendEndMarker(e.buf) - a.buf = append(enc.AppendArrayDelim(a.buf), e.buf...) - putEvent(e) - return a -} - -// Str appends the val as a string to the array. -func (a *Array) Str(val string) *Array { - a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), val) - return a -} - -// Bytes appends the val as a string to the array. -func (a *Array) Bytes(val []byte) *Array { - a.buf = enc.AppendBytes(enc.AppendArrayDelim(a.buf), val) - return a -} - -// Hex appends the val as a hex string to the array. -func (a *Array) Hex(val []byte) *Array { - a.buf = enc.AppendHex(enc.AppendArrayDelim(a.buf), val) - return a -} - -// RawJSON adds already encoded JSON to the array. -func (a *Array) RawJSON(val []byte) *Array { - a.buf = appendJSON(enc.AppendArrayDelim(a.buf), val) - return a -} - -// Err serializes and appends the err to the array. -func (a *Array) Err(err error) *Array { - switch m := ErrorMarshalFunc(err).(type) { - case LogObjectMarshaler: - e := newEvent(nil, 0) - e.buf = e.buf[:0] - e.appendObject(m) - a.buf = append(enc.AppendArrayDelim(a.buf), e.buf...) - putEvent(e) - case error: - if m == nil || isNilValue(m) { - a.buf = enc.AppendNil(enc.AppendArrayDelim(a.buf)) - } else { - a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), m.Error()) - } - case string: - a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), m) - default: - a.buf = enc.AppendInterface(enc.AppendArrayDelim(a.buf), m) - } - - return a -} - -// Bool appends the val as a bool to the array. -func (a *Array) Bool(b bool) *Array { - a.buf = enc.AppendBool(enc.AppendArrayDelim(a.buf), b) - return a -} - -// Int appends i as a int to the array. -func (a *Array) Int(i int) *Array { - a.buf = enc.AppendInt(enc.AppendArrayDelim(a.buf), i) - return a -} - -// Int8 appends i as a int8 to the array. -func (a *Array) Int8(i int8) *Array { - a.buf = enc.AppendInt8(enc.AppendArrayDelim(a.buf), i) - return a -} - -// Int16 appends i as a int16 to the array. -func (a *Array) Int16(i int16) *Array { - a.buf = enc.AppendInt16(enc.AppendArrayDelim(a.buf), i) - return a -} - -// Int32 appends i as a int32 to the array. -func (a *Array) Int32(i int32) *Array { - a.buf = enc.AppendInt32(enc.AppendArrayDelim(a.buf), i) - return a -} - -// Int64 appends i as a int64 to the array. -func (a *Array) Int64(i int64) *Array { - a.buf = enc.AppendInt64(enc.AppendArrayDelim(a.buf), i) - return a -} - -// Uint appends i as a uint to the array. -func (a *Array) Uint(i uint) *Array { - a.buf = enc.AppendUint(enc.AppendArrayDelim(a.buf), i) - return a -} - -// Uint8 appends i as a uint8 to the array. -func (a *Array) Uint8(i uint8) *Array { - a.buf = enc.AppendUint8(enc.AppendArrayDelim(a.buf), i) - return a -} - -// Uint16 appends i as a uint16 to the array. -func (a *Array) Uint16(i uint16) *Array { - a.buf = enc.AppendUint16(enc.AppendArrayDelim(a.buf), i) - return a -} - -// Uint32 appends i as a uint32 to the array. -func (a *Array) Uint32(i uint32) *Array { - a.buf = enc.AppendUint32(enc.AppendArrayDelim(a.buf), i) - return a -} - -// Uint64 appends i as a uint64 to the array. -func (a *Array) Uint64(i uint64) *Array { - a.buf = enc.AppendUint64(enc.AppendArrayDelim(a.buf), i) - return a -} - -// Float32 appends f as a float32 to the array. -func (a *Array) Float32(f float32) *Array { - a.buf = enc.AppendFloat32(enc.AppendArrayDelim(a.buf), f, FloatingPointPrecision) - return a -} - -// Float64 appends f as a float64 to the array. -func (a *Array) Float64(f float64) *Array { - a.buf = enc.AppendFloat64(enc.AppendArrayDelim(a.buf), f, FloatingPointPrecision) - return a -} - -// Time appends t formatted as string using zerolog.TimeFieldFormat. -func (a *Array) Time(t time.Time) *Array { - a.buf = enc.AppendTime(enc.AppendArrayDelim(a.buf), t, TimeFieldFormat) - return a -} - -// Dur appends d to the array. -func (a *Array) Dur(d time.Duration) *Array { - a.buf = enc.AppendDuration(enc.AppendArrayDelim(a.buf), d, DurationFieldUnit, DurationFieldInteger, FloatingPointPrecision) - return a -} - -// Interface appends i marshaled using reflection. -func (a *Array) Interface(i interface{}) *Array { - if obj, ok := i.(LogObjectMarshaler); ok { - return a.Object(obj) - } - a.buf = enc.AppendInterface(enc.AppendArrayDelim(a.buf), i) - return a -} - -// IPAddr adds IPv4 or IPv6 address to the array -func (a *Array) IPAddr(ip net.IP) *Array { - a.buf = enc.AppendIPAddr(enc.AppendArrayDelim(a.buf), ip) - return a -} - -// IPPrefix adds IPv4 or IPv6 Prefix (IP + mask) to the array -func (a *Array) IPPrefix(pfx net.IPNet) *Array { - a.buf = enc.AppendIPPrefix(enc.AppendArrayDelim(a.buf), pfx) - return a -} - -// MACAddr adds a MAC (Ethernet) address to the array -func (a *Array) MACAddr(ha net.HardwareAddr) *Array { - a.buf = enc.AppendMACAddr(enc.AppendArrayDelim(a.buf), ha) - return a -} - -// Dict adds the dict Event to the array -func (a *Array) Dict(dict *Event) *Array { - dict.buf = enc.AppendEndMarker(dict.buf) - a.buf = append(enc.AppendArrayDelim(a.buf), dict.buf...) - return a -} diff --git a/vendor/github.com/rs/zerolog/console.go b/vendor/github.com/rs/zerolog/console.go deleted file mode 100644 index 7e65e86..0000000 --- a/vendor/github.com/rs/zerolog/console.go +++ /dev/null @@ -1,520 +0,0 @@ -package zerolog - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "strconv" - "strings" - "sync" - "time" - - "github.com/mattn/go-colorable" -) - -const ( - colorBlack = iota + 30 - colorRed - colorGreen - colorYellow - colorBlue - colorMagenta - colorCyan - colorWhite - - colorBold = 1 - colorDarkGray = 90 - - unknownLevel = "???" -) - -var ( - consoleBufPool = sync.Pool{ - New: func() interface{} { - return bytes.NewBuffer(make([]byte, 0, 100)) - }, - } -) - -const ( - consoleDefaultTimeFormat = time.Kitchen -) - -// Formatter transforms the input into a formatted string. -type Formatter func(interface{}) string - -// ConsoleWriter parses the JSON input and writes it in an -// (optionally) colorized, human-friendly format to Out. -type ConsoleWriter struct { - // Out is the output destination. - Out io.Writer - - // NoColor disables the colorized output. - NoColor bool - - // TimeFormat specifies the format for timestamp in output. - TimeFormat string - - // TimeLocation tells ConsoleWriter’s default FormatTimestamp - // how to localize the time. - TimeLocation *time.Location - - // PartsOrder defines the order of parts in output. - PartsOrder []string - - // PartsExclude defines parts to not display in output. - PartsExclude []string - - // FieldsOrder defines the order of contextual fields in output. - FieldsOrder []string - - fieldIsOrdered map[string]int - - // FieldsExclude defines contextual fields to not display in output. - FieldsExclude []string - - FormatTimestamp Formatter - FormatLevel Formatter - FormatCaller Formatter - FormatMessage Formatter - FormatFieldName Formatter - FormatFieldValue Formatter - FormatErrFieldName Formatter - FormatErrFieldValue Formatter - - FormatExtra func(map[string]interface{}, *bytes.Buffer) error - - FormatPrepare func(map[string]interface{}) error -} - -// NewConsoleWriter creates and initializes a new ConsoleWriter. -func NewConsoleWriter(options ...func(w *ConsoleWriter)) ConsoleWriter { - w := ConsoleWriter{ - Out: os.Stdout, - TimeFormat: consoleDefaultTimeFormat, - PartsOrder: consoleDefaultPartsOrder(), - } - - for _, opt := range options { - opt(&w) - } - - // Fix color on Windows - if w.Out == os.Stdout || w.Out == os.Stderr { - w.Out = colorable.NewColorable(w.Out.(*os.File)) - } - - return w -} - -// Write transforms the JSON input with formatters and appends to w.Out. -func (w ConsoleWriter) Write(p []byte) (n int, err error) { - // Fix color on Windows - if w.Out == os.Stdout || w.Out == os.Stderr { - w.Out = colorable.NewColorable(w.Out.(*os.File)) - } - - if w.PartsOrder == nil { - w.PartsOrder = consoleDefaultPartsOrder() - } - - var buf = consoleBufPool.Get().(*bytes.Buffer) - defer func() { - buf.Reset() - consoleBufPool.Put(buf) - }() - - var evt map[string]interface{} - p = decodeIfBinaryToBytes(p) - d := json.NewDecoder(bytes.NewReader(p)) - d.UseNumber() - err = d.Decode(&evt) - if err != nil { - return n, fmt.Errorf("cannot decode event: %s", err) - } - - if w.FormatPrepare != nil { - err = w.FormatPrepare(evt) - if err != nil { - return n, err - } - } - - for _, p := range w.PartsOrder { - w.writePart(buf, evt, p) - } - - w.writeFields(evt, buf) - - if w.FormatExtra != nil { - err = w.FormatExtra(evt, buf) - if err != nil { - return n, err - } - } - - err = buf.WriteByte('\n') - if err != nil { - return n, err - } - - _, err = buf.WriteTo(w.Out) - return len(p), err -} - -// Call the underlying writer's Close method if it is an io.Closer. Otherwise -// does nothing. -func (w ConsoleWriter) Close() error { - if closer, ok := w.Out.(io.Closer); ok { - return closer.Close() - } - return nil -} - -// writeFields appends formatted key-value pairs to buf. -func (w ConsoleWriter) writeFields(evt map[string]interface{}, buf *bytes.Buffer) { - var fields = make([]string, 0, len(evt)) - for field := range evt { - var isExcluded bool - for _, excluded := range w.FieldsExclude { - if field == excluded { - isExcluded = true - break - } - } - if isExcluded { - continue - } - - switch field { - case LevelFieldName, TimestampFieldName, MessageFieldName, CallerFieldName: - continue - } - fields = append(fields, field) - } - - if len(w.FieldsOrder) > 0 { - w.orderFields(fields) - } else { - sort.Strings(fields) - } - - // Write space only if something has already been written to the buffer, and if there are fields. - if buf.Len() > 0 && len(fields) > 0 { - buf.WriteByte(' ') - } - - // Move the "error" field to the front - ei := sort.Search(len(fields), func(i int) bool { return fields[i] >= ErrorFieldName }) - if ei < len(fields) && fields[ei] == ErrorFieldName { - fields[ei] = "" - fields = append([]string{ErrorFieldName}, fields...) - var xfields = make([]string, 0, len(fields)) - for _, field := range fields { - if field == "" { // Skip empty fields - continue - } - xfields = append(xfields, field) - } - fields = xfields - } - - for i, field := range fields { - var fn Formatter - var fv Formatter - - if field == ErrorFieldName { - if w.FormatErrFieldName == nil { - fn = consoleDefaultFormatErrFieldName(w.NoColor) - } else { - fn = w.FormatErrFieldName - } - - if w.FormatErrFieldValue == nil { - fv = consoleDefaultFormatErrFieldValue(w.NoColor) - } else { - fv = w.FormatErrFieldValue - } - } else { - if w.FormatFieldName == nil { - fn = consoleDefaultFormatFieldName(w.NoColor) - } else { - fn = w.FormatFieldName - } - - if w.FormatFieldValue == nil { - fv = consoleDefaultFormatFieldValue - } else { - fv = w.FormatFieldValue - } - } - - buf.WriteString(fn(field)) - - switch fValue := evt[field].(type) { - case string: - if needsQuote(fValue) { - buf.WriteString(fv(strconv.Quote(fValue))) - } else { - buf.WriteString(fv(fValue)) - } - case json.Number: - buf.WriteString(fv(fValue)) - default: - b, err := InterfaceMarshalFunc(fValue) - if err != nil { - fmt.Fprintf(buf, colorize("[error: %v]", colorRed, w.NoColor), err) - } else { - fmt.Fprint(buf, fv(b)) - } - } - - if i < len(fields)-1 { // Skip space for last field - buf.WriteByte(' ') - } - } -} - -// writePart appends a formatted part to buf. -func (w ConsoleWriter) writePart(buf *bytes.Buffer, evt map[string]interface{}, p string) { - var f Formatter - - if w.PartsExclude != nil && len(w.PartsExclude) > 0 { - for _, exclude := range w.PartsExclude { - if exclude == p { - return - } - } - } - - switch p { - case LevelFieldName: - if w.FormatLevel == nil { - f = consoleDefaultFormatLevel(w.NoColor) - } else { - f = w.FormatLevel - } - case TimestampFieldName: - if w.FormatTimestamp == nil { - f = consoleDefaultFormatTimestamp(w.TimeFormat, w.TimeLocation, w.NoColor) - } else { - f = w.FormatTimestamp - } - case MessageFieldName: - if w.FormatMessage == nil { - f = consoleDefaultFormatMessage(w.NoColor, evt[LevelFieldName]) - } else { - f = w.FormatMessage - } - case CallerFieldName: - if w.FormatCaller == nil { - f = consoleDefaultFormatCaller(w.NoColor) - } else { - f = w.FormatCaller - } - default: - if w.FormatFieldValue == nil { - f = consoleDefaultFormatFieldValue - } else { - f = w.FormatFieldValue - } - } - - var s = f(evt[p]) - - if len(s) > 0 { - if buf.Len() > 0 { - buf.WriteByte(' ') // Write space only if not the first part - } - buf.WriteString(s) - } -} - -// orderFields takes an array of field names and an array representing field order -// and returns an array with any ordered fields at the beginning, in order, -// and the remaining fields after in their original order. -func (w ConsoleWriter) orderFields(fields []string) { - if w.fieldIsOrdered == nil { - w.fieldIsOrdered = make(map[string]int) - for i, fieldName := range w.FieldsOrder { - w.fieldIsOrdered[fieldName] = i - } - } - sort.Slice(fields, func(i, j int) bool { - ii, iOrdered := w.fieldIsOrdered[fields[i]] - jj, jOrdered := w.fieldIsOrdered[fields[j]] - if iOrdered && jOrdered { - return ii < jj - } - if iOrdered { - return true - } - if jOrdered { - return false - } - return fields[i] < fields[j] - }) -} - -// needsQuote returns true when the string s should be quoted in output. -func needsQuote(s string) bool { - for i := range s { - if s[i] < 0x20 || s[i] > 0x7e || s[i] == ' ' || s[i] == '\\' || s[i] == '"' { - return true - } - } - return false -} - -// colorize returns the string s wrapped in ANSI code c, unless disabled is true or c is 0. -func colorize(s interface{}, c int, disabled bool) string { - e := os.Getenv("NO_COLOR") - if e != "" || c == 0 { - disabled = true - } - - if disabled { - return fmt.Sprintf("%s", s) - } - return fmt.Sprintf("\x1b[%dm%v\x1b[0m", c, s) -} - -// ----- DEFAULT FORMATTERS --------------------------------------------------- - -func consoleDefaultPartsOrder() []string { - return []string{ - TimestampFieldName, - LevelFieldName, - CallerFieldName, - MessageFieldName, - } -} - -func consoleDefaultFormatTimestamp(timeFormat string, location *time.Location, noColor bool) Formatter { - if timeFormat == "" { - timeFormat = consoleDefaultTimeFormat - } - if location == nil { - location = time.Local - } - - return func(i interface{}) string { - t := "" - switch tt := i.(type) { - case string: - ts, err := time.ParseInLocation(TimeFieldFormat, tt, location) - if err != nil { - t = tt - } else { - t = ts.In(location).Format(timeFormat) - } - case json.Number: - i, err := tt.Int64() - if err != nil { - t = tt.String() - } else { - var sec, nsec int64 - - switch TimeFieldFormat { - case TimeFormatUnixNano: - sec, nsec = 0, i - case TimeFormatUnixMicro: - sec, nsec = 0, int64(time.Duration(i)*time.Microsecond) - case TimeFormatUnixMs: - sec, nsec = 0, int64(time.Duration(i)*time.Millisecond) - default: - sec, nsec = i, 0 - } - - ts := time.Unix(sec, nsec) - t = ts.In(location).Format(timeFormat) - } - } - return colorize(t, colorDarkGray, noColor) - } -} - -func stripLevel(ll string) string { - if len(ll) == 0 { - return unknownLevel - } - if len(ll) > 3 { - ll = ll[:3] - } - return strings.ToUpper(ll) -} - -func consoleDefaultFormatLevel(noColor bool) Formatter { - return func(i interface{}) string { - if ll, ok := i.(string); ok { - level, _ := ParseLevel(ll) - fl, ok := FormattedLevels[level] - if ok { - return colorize(fl, LevelColors[level], noColor) - } - return stripLevel(ll) - } - if i == nil { - return unknownLevel - } - return stripLevel(fmt.Sprintf("%s", i)) - } -} - -func consoleDefaultFormatCaller(noColor bool) Formatter { - return func(i interface{}) string { - var c string - if cc, ok := i.(string); ok { - c = cc - } - if len(c) > 0 { - if cwd, err := os.Getwd(); err == nil { - if rel, err := filepath.Rel(cwd, c); err == nil { - c = rel - } - } - c = colorize(c, colorBold, noColor) + colorize(" >", colorCyan, noColor) - } - return c - } -} - -func consoleDefaultFormatMessage(noColor bool, level interface{}) Formatter { - return func(i interface{}) string { - if i == nil || i == "" { - return "" - } - switch level { - case LevelInfoValue, LevelWarnValue, LevelErrorValue, LevelFatalValue, LevelPanicValue: - return colorize(fmt.Sprintf("%s", i), colorBold, noColor) - default: - return fmt.Sprintf("%s", i) - } - } -} - -func consoleDefaultFormatFieldName(noColor bool) Formatter { - return func(i interface{}) string { - return colorize(fmt.Sprintf("%s=", i), colorCyan, noColor) - } -} - -func consoleDefaultFormatFieldValue(i interface{}) string { - return fmt.Sprintf("%s", i) -} - -func consoleDefaultFormatErrFieldName(noColor bool) Formatter { - return func(i interface{}) string { - return colorize(fmt.Sprintf("%s=", i), colorCyan, noColor) - } -} - -func consoleDefaultFormatErrFieldValue(noColor bool) Formatter { - return func(i interface{}) string { - return colorize(colorize(fmt.Sprintf("%s", i), colorBold, noColor), colorRed, noColor) - } -} diff --git a/vendor/github.com/rs/zerolog/context.go b/vendor/github.com/rs/zerolog/context.go deleted file mode 100644 index ff9a3ae..0000000 --- a/vendor/github.com/rs/zerolog/context.go +++ /dev/null @@ -1,480 +0,0 @@ -package zerolog - -import ( - "context" - "fmt" - "io" - "math" - "net" - "time" -) - -// Context configures a new sub-logger with contextual fields. -type Context struct { - l Logger -} - -// Logger returns the logger with the context previously set. -func (c Context) Logger() Logger { - return c.l -} - -// Fields is a helper function to use a map or slice to set fields using type assertion. -// Only map[string]interface{} and []interface{} are accepted. []interface{} must -// alternate string keys and arbitrary values, and extraneous ones are ignored. -func (c Context) Fields(fields interface{}) Context { - c.l.context = appendFields(c.l.context, fields, c.l.stack) - return c -} - -// Dict adds the field key with the dict to the logger context. -func (c Context) Dict(key string, dict *Event) Context { - dict.buf = enc.AppendEndMarker(dict.buf) - c.l.context = append(enc.AppendKey(c.l.context, key), dict.buf...) - putEvent(dict) - return c -} - -// Array adds the field key with an array to the event context. -// Use zerolog.Arr() to create the array or pass a type that -// implement the LogArrayMarshaler interface. -func (c Context) Array(key string, arr LogArrayMarshaler) Context { - c.l.context = enc.AppendKey(c.l.context, key) - if arr, ok := arr.(*Array); ok { - c.l.context = arr.write(c.l.context) - return c - } - var a *Array - if aa, ok := arr.(*Array); ok { - a = aa - } else { - a = Arr() - arr.MarshalZerologArray(a) - } - c.l.context = a.write(c.l.context) - return c -} - -// Object marshals an object that implement the LogObjectMarshaler interface. -func (c Context) Object(key string, obj LogObjectMarshaler) Context { - e := newEvent(LevelWriterAdapter{io.Discard}, 0) - e.Object(key, obj) - c.l.context = enc.AppendObjectData(c.l.context, e.buf) - putEvent(e) - return c -} - -// EmbedObject marshals and Embeds an object that implement the LogObjectMarshaler interface. -func (c Context) EmbedObject(obj LogObjectMarshaler) Context { - e := newEvent(LevelWriterAdapter{io.Discard}, 0) - e.EmbedObject(obj) - c.l.context = enc.AppendObjectData(c.l.context, e.buf) - putEvent(e) - return c -} - -// Str adds the field key with val as a string to the logger context. -func (c Context) Str(key, val string) Context { - c.l.context = enc.AppendString(enc.AppendKey(c.l.context, key), val) - return c -} - -// Strs adds the field key with val as a string to the logger context. -func (c Context) Strs(key string, vals []string) Context { - c.l.context = enc.AppendStrings(enc.AppendKey(c.l.context, key), vals) - return c -} - -// Stringer adds the field key with val.String() (or null if val is nil) to the logger context. -func (c Context) Stringer(key string, val fmt.Stringer) Context { - if val != nil { - c.l.context = enc.AppendString(enc.AppendKey(c.l.context, key), val.String()) - return c - } - - c.l.context = enc.AppendInterface(enc.AppendKey(c.l.context, key), nil) - return c -} - -// Bytes adds the field key with val as a []byte to the logger context. -func (c Context) Bytes(key string, val []byte) Context { - c.l.context = enc.AppendBytes(enc.AppendKey(c.l.context, key), val) - return c -} - -// Hex adds the field key with val as a hex string to the logger context. -func (c Context) Hex(key string, val []byte) Context { - c.l.context = enc.AppendHex(enc.AppendKey(c.l.context, key), val) - return c -} - -// RawJSON adds already encoded JSON to context. -// -// No sanity check is performed on b; it must not contain carriage returns and -// be valid JSON. -func (c Context) RawJSON(key string, b []byte) Context { - c.l.context = appendJSON(enc.AppendKey(c.l.context, key), b) - return c -} - -// AnErr adds the field key with serialized err to the logger context. -func (c Context) AnErr(key string, err error) Context { - switch m := ErrorMarshalFunc(err).(type) { - case nil: - return c - case LogObjectMarshaler: - return c.Object(key, m) - case error: - if m == nil || isNilValue(m) { - return c - } else { - return c.Str(key, m.Error()) - } - case string: - return c.Str(key, m) - default: - return c.Interface(key, m) - } -} - -// Errs adds the field key with errs as an array of serialized errors to the -// logger context. -func (c Context) Errs(key string, errs []error) Context { - arr := Arr() - for _, err := range errs { - switch m := ErrorMarshalFunc(err).(type) { - case LogObjectMarshaler: - arr = arr.Object(m) - case error: - if m == nil || isNilValue(m) { - arr = arr.Interface(nil) - } else { - arr = arr.Str(m.Error()) - } - case string: - arr = arr.Str(m) - default: - arr = arr.Interface(m) - } - } - - return c.Array(key, arr) -} - -// Err adds the field "error" with serialized err to the logger context. -func (c Context) Err(err error) Context { - if c.l.stack && ErrorStackMarshaler != nil { - switch m := ErrorStackMarshaler(err).(type) { - case nil: - case LogObjectMarshaler: - c = c.Object(ErrorStackFieldName, m) - case error: - if m != nil && !isNilValue(m) { - c = c.Str(ErrorStackFieldName, m.Error()) - } - case string: - c = c.Str(ErrorStackFieldName, m) - default: - c = c.Interface(ErrorStackFieldName, m) - } - } - - return c.AnErr(ErrorFieldName, err) -} - -// Ctx adds the context.Context to the logger context. The context.Context is -// not rendered in the error message, but is made available for hooks to use. -// A typical use case is to extract tracing information from the -// context.Context. -func (c Context) Ctx(ctx context.Context) Context { - c.l.ctx = ctx - return c -} - -// Bool adds the field key with val as a bool to the logger context. -func (c Context) Bool(key string, b bool) Context { - c.l.context = enc.AppendBool(enc.AppendKey(c.l.context, key), b) - return c -} - -// Bools adds the field key with val as a []bool to the logger context. -func (c Context) Bools(key string, b []bool) Context { - c.l.context = enc.AppendBools(enc.AppendKey(c.l.context, key), b) - return c -} - -// Int adds the field key with i as a int to the logger context. -func (c Context) Int(key string, i int) Context { - c.l.context = enc.AppendInt(enc.AppendKey(c.l.context, key), i) - return c -} - -// Ints adds the field key with i as a []int to the logger context. -func (c Context) Ints(key string, i []int) Context { - c.l.context = enc.AppendInts(enc.AppendKey(c.l.context, key), i) - return c -} - -// Int8 adds the field key with i as a int8 to the logger context. -func (c Context) Int8(key string, i int8) Context { - c.l.context = enc.AppendInt8(enc.AppendKey(c.l.context, key), i) - return c -} - -// Ints8 adds the field key with i as a []int8 to the logger context. -func (c Context) Ints8(key string, i []int8) Context { - c.l.context = enc.AppendInts8(enc.AppendKey(c.l.context, key), i) - return c -} - -// Int16 adds the field key with i as a int16 to the logger context. -func (c Context) Int16(key string, i int16) Context { - c.l.context = enc.AppendInt16(enc.AppendKey(c.l.context, key), i) - return c -} - -// Ints16 adds the field key with i as a []int16 to the logger context. -func (c Context) Ints16(key string, i []int16) Context { - c.l.context = enc.AppendInts16(enc.AppendKey(c.l.context, key), i) - return c -} - -// Int32 adds the field key with i as a int32 to the logger context. -func (c Context) Int32(key string, i int32) Context { - c.l.context = enc.AppendInt32(enc.AppendKey(c.l.context, key), i) - return c -} - -// Ints32 adds the field key with i as a []int32 to the logger context. -func (c Context) Ints32(key string, i []int32) Context { - c.l.context = enc.AppendInts32(enc.AppendKey(c.l.context, key), i) - return c -} - -// Int64 adds the field key with i as a int64 to the logger context. -func (c Context) Int64(key string, i int64) Context { - c.l.context = enc.AppendInt64(enc.AppendKey(c.l.context, key), i) - return c -} - -// Ints64 adds the field key with i as a []int64 to the logger context. -func (c Context) Ints64(key string, i []int64) Context { - c.l.context = enc.AppendInts64(enc.AppendKey(c.l.context, key), i) - return c -} - -// Uint adds the field key with i as a uint to the logger context. -func (c Context) Uint(key string, i uint) Context { - c.l.context = enc.AppendUint(enc.AppendKey(c.l.context, key), i) - return c -} - -// Uints adds the field key with i as a []uint to the logger context. -func (c Context) Uints(key string, i []uint) Context { - c.l.context = enc.AppendUints(enc.AppendKey(c.l.context, key), i) - return c -} - -// Uint8 adds the field key with i as a uint8 to the logger context. -func (c Context) Uint8(key string, i uint8) Context { - c.l.context = enc.AppendUint8(enc.AppendKey(c.l.context, key), i) - return c -} - -// Uints8 adds the field key with i as a []uint8 to the logger context. -func (c Context) Uints8(key string, i []uint8) Context { - c.l.context = enc.AppendUints8(enc.AppendKey(c.l.context, key), i) - return c -} - -// Uint16 adds the field key with i as a uint16 to the logger context. -func (c Context) Uint16(key string, i uint16) Context { - c.l.context = enc.AppendUint16(enc.AppendKey(c.l.context, key), i) - return c -} - -// Uints16 adds the field key with i as a []uint16 to the logger context. -func (c Context) Uints16(key string, i []uint16) Context { - c.l.context = enc.AppendUints16(enc.AppendKey(c.l.context, key), i) - return c -} - -// Uint32 adds the field key with i as a uint32 to the logger context. -func (c Context) Uint32(key string, i uint32) Context { - c.l.context = enc.AppendUint32(enc.AppendKey(c.l.context, key), i) - return c -} - -// Uints32 adds the field key with i as a []uint32 to the logger context. -func (c Context) Uints32(key string, i []uint32) Context { - c.l.context = enc.AppendUints32(enc.AppendKey(c.l.context, key), i) - return c -} - -// Uint64 adds the field key with i as a uint64 to the logger context. -func (c Context) Uint64(key string, i uint64) Context { - c.l.context = enc.AppendUint64(enc.AppendKey(c.l.context, key), i) - return c -} - -// Uints64 adds the field key with i as a []uint64 to the logger context. -func (c Context) Uints64(key string, i []uint64) Context { - c.l.context = enc.AppendUints64(enc.AppendKey(c.l.context, key), i) - return c -} - -// Float32 adds the field key with f as a float32 to the logger context. -func (c Context) Float32(key string, f float32) Context { - c.l.context = enc.AppendFloat32(enc.AppendKey(c.l.context, key), f, FloatingPointPrecision) - return c -} - -// Floats32 adds the field key with f as a []float32 to the logger context. -func (c Context) Floats32(key string, f []float32) Context { - c.l.context = enc.AppendFloats32(enc.AppendKey(c.l.context, key), f, FloatingPointPrecision) - return c -} - -// Float64 adds the field key with f as a float64 to the logger context. -func (c Context) Float64(key string, f float64) Context { - c.l.context = enc.AppendFloat64(enc.AppendKey(c.l.context, key), f, FloatingPointPrecision) - return c -} - -// Floats64 adds the field key with f as a []float64 to the logger context. -func (c Context) Floats64(key string, f []float64) Context { - c.l.context = enc.AppendFloats64(enc.AppendKey(c.l.context, key), f, FloatingPointPrecision) - return c -} - -type timestampHook struct{} - -func (ts timestampHook) Run(e *Event, level Level, msg string) { - e.Timestamp() -} - -var th = timestampHook{} - -// Timestamp adds the current local time to the logger context with the "time" key, formatted using zerolog.TimeFieldFormat. -// To customize the key name, change zerolog.TimestampFieldName. -// To customize the time format, change zerolog.TimeFieldFormat. -// -// NOTE: It won't dedupe the "time" key if the *Context has one already. -func (c Context) Timestamp() Context { - c.l = c.l.Hook(th) - return c -} - -// Time adds the field key with t formatted as string using zerolog.TimeFieldFormat. -func (c Context) Time(key string, t time.Time) Context { - c.l.context = enc.AppendTime(enc.AppendKey(c.l.context, key), t, TimeFieldFormat) - return c -} - -// Times adds the field key with t formatted as string using zerolog.TimeFieldFormat. -func (c Context) Times(key string, t []time.Time) Context { - c.l.context = enc.AppendTimes(enc.AppendKey(c.l.context, key), t, TimeFieldFormat) - return c -} - -// Dur adds the fields key with d divided by unit and stored as a float. -func (c Context) Dur(key string, d time.Duration) Context { - c.l.context = enc.AppendDuration(enc.AppendKey(c.l.context, key), d, DurationFieldUnit, DurationFieldInteger, FloatingPointPrecision) - return c -} - -// Durs adds the fields key with d divided by unit and stored as a float. -func (c Context) Durs(key string, d []time.Duration) Context { - c.l.context = enc.AppendDurations(enc.AppendKey(c.l.context, key), d, DurationFieldUnit, DurationFieldInteger, FloatingPointPrecision) - return c -} - -// Interface adds the field key with obj marshaled using reflection. -func (c Context) Interface(key string, i interface{}) Context { - if obj, ok := i.(LogObjectMarshaler); ok { - return c.Object(key, obj) - } - c.l.context = enc.AppendInterface(enc.AppendKey(c.l.context, key), i) - return c -} - -// Type adds the field key with val's type using reflection. -func (c Context) Type(key string, val interface{}) Context { - c.l.context = enc.AppendType(enc.AppendKey(c.l.context, key), val) - return c -} - -// Any is a wrapper around Context.Interface. -func (c Context) Any(key string, i interface{}) Context { - return c.Interface(key, i) -} - -// Reset removes all the context fields. -func (c Context) Reset() Context { - c.l.context = enc.AppendBeginMarker(make([]byte, 0, 500)) - return c -} - -type callerHook struct { - callerSkipFrameCount int -} - -func newCallerHook(skipFrameCount int) callerHook { - return callerHook{callerSkipFrameCount: skipFrameCount} -} - -func (ch callerHook) Run(e *Event, level Level, msg string) { - switch ch.callerSkipFrameCount { - case useGlobalSkipFrameCount: - // Extra frames to skip (added by hook infra). - e.caller(CallerSkipFrameCount + contextCallerSkipFrameCount) - default: - // Extra frames to skip (added by hook infra). - e.caller(ch.callerSkipFrameCount + contextCallerSkipFrameCount) - } -} - -// useGlobalSkipFrameCount acts as a flag to informat callerHook.Run -// to use the global CallerSkipFrameCount. -const useGlobalSkipFrameCount = math.MinInt32 - -// ch is the default caller hook using the global CallerSkipFrameCount. -var ch = newCallerHook(useGlobalSkipFrameCount) - -// Caller adds the file:line of the caller with the zerolog.CallerFieldName key. -func (c Context) Caller() Context { - c.l = c.l.Hook(ch) - return c -} - -// CallerWithSkipFrameCount adds the file:line of the caller with the zerolog.CallerFieldName key. -// The specified skipFrameCount int will override the global CallerSkipFrameCount for this context's respective logger. -// If set to -1 the global CallerSkipFrameCount will be used. -func (c Context) CallerWithSkipFrameCount(skipFrameCount int) Context { - c.l = c.l.Hook(newCallerHook(skipFrameCount)) - return c -} - -// Stack enables stack trace printing for the error passed to Err(). -func (c Context) Stack() Context { - c.l.stack = true - return c -} - -// IPAddr adds IPv4 or IPv6 Address to the context -func (c Context) IPAddr(key string, ip net.IP) Context { - c.l.context = enc.AppendIPAddr(enc.AppendKey(c.l.context, key), ip) - return c -} - -// IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the context -func (c Context) IPPrefix(key string, pfx net.IPNet) Context { - c.l.context = enc.AppendIPPrefix(enc.AppendKey(c.l.context, key), pfx) - return c -} - -// MACAddr adds MAC address to the context -func (c Context) MACAddr(key string, ha net.HardwareAddr) Context { - c.l.context = enc.AppendMACAddr(enc.AppendKey(c.l.context, key), ha) - return c -} diff --git a/vendor/github.com/rs/zerolog/ctx.go b/vendor/github.com/rs/zerolog/ctx.go deleted file mode 100644 index 60432d1..0000000 --- a/vendor/github.com/rs/zerolog/ctx.go +++ /dev/null @@ -1,52 +0,0 @@ -package zerolog - -import ( - "context" -) - -var disabledLogger *Logger - -func init() { - SetGlobalLevel(TraceLevel) - l := Nop() - disabledLogger = &l -} - -type ctxKey struct{} - -// WithContext returns a copy of ctx with the receiver attached. The Logger -// attached to the provided Context (if any) will not be effected. If the -// receiver's log level is Disabled it will only be attached to the returned -// Context if the provided Context has a previously attached Logger. If the -// provided Context has no attached Logger, a Disabled Logger will not be -// attached. -// -// Note: to modify the existing Logger attached to a Context (instead of -// replacing it in a new Context), use UpdateContext with the following -// notation: -// -// ctx := r.Context() -// l := zerolog.Ctx(ctx) -// l.UpdateContext(func(c Context) Context { -// return c.Str("bar", "baz") -// }) -// -func (l Logger) WithContext(ctx context.Context) context.Context { - if _, ok := ctx.Value(ctxKey{}).(*Logger); !ok && l.level == Disabled { - // Do not store disabled logger. - return ctx - } - return context.WithValue(ctx, ctxKey{}, &l) -} - -// Ctx returns the Logger associated with the ctx. If no logger -// is associated, DefaultContextLogger is returned, unless DefaultContextLogger -// is nil, in which case a disabled logger is returned. -func Ctx(ctx context.Context) *Logger { - if l, ok := ctx.Value(ctxKey{}).(*Logger); ok { - return l - } else if l = DefaultContextLogger; l != nil { - return l - } - return disabledLogger -} diff --git a/vendor/github.com/rs/zerolog/encoder.go b/vendor/github.com/rs/zerolog/encoder.go deleted file mode 100644 index 4dbaf38..0000000 --- a/vendor/github.com/rs/zerolog/encoder.go +++ /dev/null @@ -1,56 +0,0 @@ -package zerolog - -import ( - "net" - "time" -) - -type encoder interface { - AppendArrayDelim(dst []byte) []byte - AppendArrayEnd(dst []byte) []byte - AppendArrayStart(dst []byte) []byte - AppendBeginMarker(dst []byte) []byte - AppendBool(dst []byte, val bool) []byte - AppendBools(dst []byte, vals []bool) []byte - AppendBytes(dst, s []byte) []byte - AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool, precision int) []byte - AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool, precision int) []byte - AppendEndMarker(dst []byte) []byte - AppendFloat32(dst []byte, val float32, precision int) []byte - AppendFloat64(dst []byte, val float64, precision int) []byte - AppendFloats32(dst []byte, vals []float32, precision int) []byte - AppendFloats64(dst []byte, vals []float64, precision int) []byte - AppendHex(dst, s []byte) []byte - AppendIPAddr(dst []byte, ip net.IP) []byte - AppendIPPrefix(dst []byte, pfx net.IPNet) []byte - AppendInt(dst []byte, val int) []byte - AppendInt16(dst []byte, val int16) []byte - AppendInt32(dst []byte, val int32) []byte - AppendInt64(dst []byte, val int64) []byte - AppendInt8(dst []byte, val int8) []byte - AppendInterface(dst []byte, i interface{}) []byte - AppendInts(dst []byte, vals []int) []byte - AppendInts16(dst []byte, vals []int16) []byte - AppendInts32(dst []byte, vals []int32) []byte - AppendInts64(dst []byte, vals []int64) []byte - AppendInts8(dst []byte, vals []int8) []byte - AppendKey(dst []byte, key string) []byte - AppendLineBreak(dst []byte) []byte - AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte - AppendNil(dst []byte) []byte - AppendObjectData(dst []byte, o []byte) []byte - AppendString(dst []byte, s string) []byte - AppendStrings(dst []byte, vals []string) []byte - AppendTime(dst []byte, t time.Time, format string) []byte - AppendTimes(dst []byte, vals []time.Time, format string) []byte - AppendUint(dst []byte, val uint) []byte - AppendUint16(dst []byte, val uint16) []byte - AppendUint32(dst []byte, val uint32) []byte - AppendUint64(dst []byte, val uint64) []byte - AppendUint8(dst []byte, val uint8) []byte - AppendUints(dst []byte, vals []uint) []byte - AppendUints16(dst []byte, vals []uint16) []byte - AppendUints32(dst []byte, vals []uint32) []byte - AppendUints64(dst []byte, vals []uint64) []byte - AppendUints8(dst []byte, vals []uint8) []byte -} diff --git a/vendor/github.com/rs/zerolog/encoder_cbor.go b/vendor/github.com/rs/zerolog/encoder_cbor.go deleted file mode 100644 index 36cb994..0000000 --- a/vendor/github.com/rs/zerolog/encoder_cbor.go +++ /dev/null @@ -1,45 +0,0 @@ -// +build binary_log - -package zerolog - -// This file contains bindings to do binary encoding. - -import ( - "github.com/rs/zerolog/internal/cbor" -) - -var ( - _ encoder = (*cbor.Encoder)(nil) - - enc = cbor.Encoder{} -) - -func init() { - // using closure to reflect the changes at runtime. - cbor.JSONMarshalFunc = func(v interface{}) ([]byte, error) { - return InterfaceMarshalFunc(v) - } -} - -func appendJSON(dst []byte, j []byte) []byte { - return cbor.AppendEmbeddedJSON(dst, j) -} -func appendCBOR(dst []byte, c []byte) []byte { - return cbor.AppendEmbeddedCBOR(dst, c) -} - -// decodeIfBinaryToString - converts a binary formatted log msg to a -// JSON formatted String Log message. -func decodeIfBinaryToString(in []byte) string { - return cbor.DecodeIfBinaryToString(in) -} - -func decodeObjectToStr(in []byte) string { - return cbor.DecodeObjectToStr(in) -} - -// decodeIfBinaryToBytes - converts a binary formatted log msg to a -// JSON formatted Bytes Log message. -func decodeIfBinaryToBytes(in []byte) []byte { - return cbor.DecodeIfBinaryToBytes(in) -} diff --git a/vendor/github.com/rs/zerolog/encoder_json.go b/vendor/github.com/rs/zerolog/encoder_json.go deleted file mode 100644 index 6f96c68..0000000 --- a/vendor/github.com/rs/zerolog/encoder_json.go +++ /dev/null @@ -1,51 +0,0 @@ -// +build !binary_log - -package zerolog - -// encoder_json.go file contains bindings to generate -// JSON encoded byte stream. - -import ( - "encoding/base64" - "github.com/rs/zerolog/internal/json" -) - -var ( - _ encoder = (*json.Encoder)(nil) - - enc = json.Encoder{} -) - -func init() { - // using closure to reflect the changes at runtime. - json.JSONMarshalFunc = func(v interface{}) ([]byte, error) { - return InterfaceMarshalFunc(v) - } -} - -func appendJSON(dst []byte, j []byte) []byte { - return append(dst, j...) -} -func appendCBOR(dst []byte, cbor []byte) []byte { - dst = append(dst, []byte("\"data:application/cbor;base64,")...) - l := len(dst) - enc := base64.StdEncoding - n := enc.EncodedLen(len(cbor)) - for i := 0; i < n; i++ { - dst = append(dst, '.') - } - enc.Encode(dst[l:], cbor) - return append(dst, '"') -} - -func decodeIfBinaryToString(in []byte) string { - return string(in) -} - -func decodeObjectToStr(in []byte) string { - return string(in) -} - -func decodeIfBinaryToBytes(in []byte) []byte { - return in -} diff --git a/vendor/github.com/rs/zerolog/event.go b/vendor/github.com/rs/zerolog/event.go deleted file mode 100644 index 56de606..0000000 --- a/vendor/github.com/rs/zerolog/event.go +++ /dev/null @@ -1,830 +0,0 @@ -package zerolog - -import ( - "context" - "fmt" - "net" - "os" - "runtime" - "sync" - "time" -) - -var eventPool = &sync.Pool{ - New: func() interface{} { - return &Event{ - buf: make([]byte, 0, 500), - } - }, -} - -// Event represents a log event. It is instanced by one of the level method of -// Logger and finalized by the Msg or Msgf method. -type Event struct { - buf []byte - w LevelWriter - level Level - done func(msg string) - stack bool // enable error stack trace - ch []Hook // hooks from context - skipFrame int // The number of additional frames to skip when printing the caller. - ctx context.Context // Optional Go context for event -} - -func putEvent(e *Event) { - // Proper usage of a sync.Pool requires each entry to have approximately - // the same memory cost. To obtain this property when the stored type - // contains a variably-sized buffer, we add a hard limit on the maximum buffer - // to place back in the pool. - // - // See https://golang.org/issue/23199 - const maxSize = 1 << 16 // 64KiB - if cap(e.buf) > maxSize { - return - } - eventPool.Put(e) -} - -// LogObjectMarshaler provides a strongly-typed and encoding-agnostic interface -// to be implemented by types used with Event/Context's Object methods. -type LogObjectMarshaler interface { - MarshalZerologObject(e *Event) -} - -// LogArrayMarshaler provides a strongly-typed and encoding-agnostic interface -// to be implemented by types used with Event/Context's Array methods. -type LogArrayMarshaler interface { - MarshalZerologArray(a *Array) -} - -func newEvent(w LevelWriter, level Level) *Event { - e := eventPool.Get().(*Event) - e.buf = e.buf[:0] - e.ch = nil - e.buf = enc.AppendBeginMarker(e.buf) - e.w = w - e.level = level - e.stack = false - e.skipFrame = 0 - return e -} - -func (e *Event) write() (err error) { - if e == nil { - return nil - } - if e.level != Disabled { - e.buf = enc.AppendEndMarker(e.buf) - e.buf = enc.AppendLineBreak(e.buf) - if e.w != nil { - _, err = e.w.WriteLevel(e.level, e.buf) - } - } - putEvent(e) - return -} - -// Enabled return false if the *Event is going to be filtered out by -// log level or sampling. -func (e *Event) Enabled() bool { - return e != nil && e.level != Disabled -} - -// Discard disables the event so Msg(f) won't print it. -func (e *Event) Discard() *Event { - if e == nil { - return e - } - e.level = Disabled - return nil -} - -// Msg sends the *Event with msg added as the message field if not empty. -// -// NOTICE: once this method is called, the *Event should be disposed. -// Calling Msg twice can have unexpected result. -func (e *Event) Msg(msg string) { - if e == nil { - return - } - e.msg(msg) -} - -// Send is equivalent to calling Msg(""). -// -// NOTICE: once this method is called, the *Event should be disposed. -func (e *Event) Send() { - if e == nil { - return - } - e.msg("") -} - -// Msgf sends the event with formatted msg added as the message field if not empty. -// -// NOTICE: once this method is called, the *Event should be disposed. -// Calling Msgf twice can have unexpected result. -func (e *Event) Msgf(format string, v ...interface{}) { - if e == nil { - return - } - e.msg(fmt.Sprintf(format, v...)) -} - -func (e *Event) MsgFunc(createMsg func() string) { - if e == nil { - return - } - e.msg(createMsg()) -} - -func (e *Event) msg(msg string) { - for _, hook := range e.ch { - hook.Run(e, e.level, msg) - } - if msg != "" { - e.buf = enc.AppendString(enc.AppendKey(e.buf, MessageFieldName), msg) - } - if e.done != nil { - defer e.done(msg) - } - if err := e.write(); err != nil { - if ErrorHandler != nil { - ErrorHandler(err) - } else { - fmt.Fprintf(os.Stderr, "zerolog: could not write event: %v\n", err) - } - } -} - -// Fields is a helper function to use a map or slice to set fields using type assertion. -// Only map[string]interface{} and []interface{} are accepted. []interface{} must -// alternate string keys and arbitrary values, and extraneous ones are ignored. -func (e *Event) Fields(fields interface{}) *Event { - if e == nil { - return e - } - e.buf = appendFields(e.buf, fields, e.stack) - return e -} - -// Dict adds the field key with a dict to the event context. -// Use zerolog.Dict() to create the dictionary. -func (e *Event) Dict(key string, dict *Event) *Event { - if e == nil { - return e - } - dict.buf = enc.AppendEndMarker(dict.buf) - e.buf = append(enc.AppendKey(e.buf, key), dict.buf...) - putEvent(dict) - return e -} - -// Dict creates an Event to be used with the *Event.Dict method. -// Call usual field methods like Str, Int etc to add fields to this -// event and give it as argument the *Event.Dict method. -func Dict() *Event { - return newEvent(nil, 0) -} - -// Array adds the field key with an array to the event context. -// Use zerolog.Arr() to create the array or pass a type that -// implement the LogArrayMarshaler interface. -func (e *Event) Array(key string, arr LogArrayMarshaler) *Event { - if e == nil { - return e - } - e.buf = enc.AppendKey(e.buf, key) - var a *Array - if aa, ok := arr.(*Array); ok { - a = aa - } else { - a = Arr() - arr.MarshalZerologArray(a) - } - e.buf = a.write(e.buf) - return e -} - -func (e *Event) appendObject(obj LogObjectMarshaler) { - e.buf = enc.AppendBeginMarker(e.buf) - obj.MarshalZerologObject(e) - e.buf = enc.AppendEndMarker(e.buf) -} - -// Object marshals an object that implement the LogObjectMarshaler interface. -func (e *Event) Object(key string, obj LogObjectMarshaler) *Event { - if e == nil { - return e - } - e.buf = enc.AppendKey(e.buf, key) - if obj == nil { - e.buf = enc.AppendNil(e.buf) - - return e - } - - e.appendObject(obj) - return e -} - -// Func allows an anonymous func to run only if the event is enabled. -func (e *Event) Func(f func(e *Event)) *Event { - if e != nil && e.Enabled() { - f(e) - } - return e -} - -// EmbedObject marshals an object that implement the LogObjectMarshaler interface. -func (e *Event) EmbedObject(obj LogObjectMarshaler) *Event { - if e == nil { - return e - } - if obj == nil { - return e - } - obj.MarshalZerologObject(e) - return e -} - -// Str adds the field key with val as a string to the *Event context. -func (e *Event) Str(key, val string) *Event { - if e == nil { - return e - } - e.buf = enc.AppendString(enc.AppendKey(e.buf, key), val) - return e -} - -// Strs adds the field key with vals as a []string to the *Event context. -func (e *Event) Strs(key string, vals []string) *Event { - if e == nil { - return e - } - e.buf = enc.AppendStrings(enc.AppendKey(e.buf, key), vals) - return e -} - -// Stringer adds the field key with val.String() (or null if val is nil) -// to the *Event context. -func (e *Event) Stringer(key string, val fmt.Stringer) *Event { - if e == nil { - return e - } - e.buf = enc.AppendStringer(enc.AppendKey(e.buf, key), val) - return e -} - -// Stringers adds the field key with vals where each individual val -// is used as val.String() (or null if val is empty) to the *Event -// context. -func (e *Event) Stringers(key string, vals []fmt.Stringer) *Event { - if e == nil { - return e - } - e.buf = enc.AppendStringers(enc.AppendKey(e.buf, key), vals) - return e -} - -// Bytes adds the field key with val as a string to the *Event context. -// -// Runes outside of normal ASCII ranges will be hex-encoded in the resulting -// JSON. -func (e *Event) Bytes(key string, val []byte) *Event { - if e == nil { - return e - } - e.buf = enc.AppendBytes(enc.AppendKey(e.buf, key), val) - return e -} - -// Hex adds the field key with val as a hex string to the *Event context. -func (e *Event) Hex(key string, val []byte) *Event { - if e == nil { - return e - } - e.buf = enc.AppendHex(enc.AppendKey(e.buf, key), val) - return e -} - -// RawJSON adds already encoded JSON to the log line under key. -// -// No sanity check is performed on b; it must not contain carriage returns and -// be valid JSON. -func (e *Event) RawJSON(key string, b []byte) *Event { - if e == nil { - return e - } - e.buf = appendJSON(enc.AppendKey(e.buf, key), b) - return e -} - -// RawCBOR adds already encoded CBOR to the log line under key. -// -// No sanity check is performed on b -// Note: The full featureset of CBOR is supported as data will not be mapped to json but stored as data-url -func (e *Event) RawCBOR(key string, b []byte) *Event { - if e == nil { - return e - } - e.buf = appendCBOR(enc.AppendKey(e.buf, key), b) - return e -} - -// AnErr adds the field key with serialized err to the *Event context. -// If err is nil, no field is added. -func (e *Event) AnErr(key string, err error) *Event { - if e == nil { - return e - } - switch m := ErrorMarshalFunc(err).(type) { - case nil: - return e - case LogObjectMarshaler: - return e.Object(key, m) - case error: - if m == nil || isNilValue(m) { - return e - } else { - return e.Str(key, m.Error()) - } - case string: - return e.Str(key, m) - default: - return e.Interface(key, m) - } -} - -// Errs adds the field key with errs as an array of serialized errors to the -// *Event context. -func (e *Event) Errs(key string, errs []error) *Event { - if e == nil { - return e - } - arr := Arr() - for _, err := range errs { - switch m := ErrorMarshalFunc(err).(type) { - case LogObjectMarshaler: - arr = arr.Object(m) - case error: - arr = arr.Err(m) - case string: - arr = arr.Str(m) - default: - arr = arr.Interface(m) - } - } - - return e.Array(key, arr) -} - -// Err adds the field "error" with serialized err to the *Event context. -// If err is nil, no field is added. -// -// To customize the key name, change zerolog.ErrorFieldName. -// -// If Stack() has been called before and zerolog.ErrorStackMarshaler is defined, -// the err is passed to ErrorStackMarshaler and the result is appended to the -// zerolog.ErrorStackFieldName. -func (e *Event) Err(err error) *Event { - if e == nil { - return e - } - if e.stack && ErrorStackMarshaler != nil { - switch m := ErrorStackMarshaler(err).(type) { - case nil: - case LogObjectMarshaler: - e.Object(ErrorStackFieldName, m) - case error: - if m != nil && !isNilValue(m) { - e.Str(ErrorStackFieldName, m.Error()) - } - case string: - e.Str(ErrorStackFieldName, m) - default: - e.Interface(ErrorStackFieldName, m) - } - } - return e.AnErr(ErrorFieldName, err) -} - -// Stack enables stack trace printing for the error passed to Err(). -// -// ErrorStackMarshaler must be set for this method to do something. -func (e *Event) Stack() *Event { - if e != nil { - e.stack = true - } - return e -} - -// Ctx adds the Go Context to the *Event context. The context is not rendered -// in the output message, but is available to hooks and to Func() calls via the -// GetCtx() accessor. A typical use case is to extract tracing information from -// the Go Ctx. -func (e *Event) Ctx(ctx context.Context) *Event { - if e != nil { - e.ctx = ctx - } - return e -} - -// GetCtx retrieves the Go context.Context which is optionally stored in the -// Event. This allows Hooks and functions passed to Func() to retrieve values -// which are stored in the context.Context. This can be useful in tracing, -// where span information is commonly propagated in the context.Context. -func (e *Event) GetCtx() context.Context { - if e == nil || e.ctx == nil { - return context.Background() - } - return e.ctx -} - -// Bool adds the field key with val as a bool to the *Event context. -func (e *Event) Bool(key string, b bool) *Event { - if e == nil { - return e - } - e.buf = enc.AppendBool(enc.AppendKey(e.buf, key), b) - return e -} - -// Bools adds the field key with val as a []bool to the *Event context. -func (e *Event) Bools(key string, b []bool) *Event { - if e == nil { - return e - } - e.buf = enc.AppendBools(enc.AppendKey(e.buf, key), b) - return e -} - -// Int adds the field key with i as a int to the *Event context. -func (e *Event) Int(key string, i int) *Event { - if e == nil { - return e - } - e.buf = enc.AppendInt(enc.AppendKey(e.buf, key), i) - return e -} - -// Ints adds the field key with i as a []int to the *Event context. -func (e *Event) Ints(key string, i []int) *Event { - if e == nil { - return e - } - e.buf = enc.AppendInts(enc.AppendKey(e.buf, key), i) - return e -} - -// Int8 adds the field key with i as a int8 to the *Event context. -func (e *Event) Int8(key string, i int8) *Event { - if e == nil { - return e - } - e.buf = enc.AppendInt8(enc.AppendKey(e.buf, key), i) - return e -} - -// Ints8 adds the field key with i as a []int8 to the *Event context. -func (e *Event) Ints8(key string, i []int8) *Event { - if e == nil { - return e - } - e.buf = enc.AppendInts8(enc.AppendKey(e.buf, key), i) - return e -} - -// Int16 adds the field key with i as a int16 to the *Event context. -func (e *Event) Int16(key string, i int16) *Event { - if e == nil { - return e - } - e.buf = enc.AppendInt16(enc.AppendKey(e.buf, key), i) - return e -} - -// Ints16 adds the field key with i as a []int16 to the *Event context. -func (e *Event) Ints16(key string, i []int16) *Event { - if e == nil { - return e - } - e.buf = enc.AppendInts16(enc.AppendKey(e.buf, key), i) - return e -} - -// Int32 adds the field key with i as a int32 to the *Event context. -func (e *Event) Int32(key string, i int32) *Event { - if e == nil { - return e - } - e.buf = enc.AppendInt32(enc.AppendKey(e.buf, key), i) - return e -} - -// Ints32 adds the field key with i as a []int32 to the *Event context. -func (e *Event) Ints32(key string, i []int32) *Event { - if e == nil { - return e - } - e.buf = enc.AppendInts32(enc.AppendKey(e.buf, key), i) - return e -} - -// Int64 adds the field key with i as a int64 to the *Event context. -func (e *Event) Int64(key string, i int64) *Event { - if e == nil { - return e - } - e.buf = enc.AppendInt64(enc.AppendKey(e.buf, key), i) - return e -} - -// Ints64 adds the field key with i as a []int64 to the *Event context. -func (e *Event) Ints64(key string, i []int64) *Event { - if e == nil { - return e - } - e.buf = enc.AppendInts64(enc.AppendKey(e.buf, key), i) - return e -} - -// Uint adds the field key with i as a uint to the *Event context. -func (e *Event) Uint(key string, i uint) *Event { - if e == nil { - return e - } - e.buf = enc.AppendUint(enc.AppendKey(e.buf, key), i) - return e -} - -// Uints adds the field key with i as a []int to the *Event context. -func (e *Event) Uints(key string, i []uint) *Event { - if e == nil { - return e - } - e.buf = enc.AppendUints(enc.AppendKey(e.buf, key), i) - return e -} - -// Uint8 adds the field key with i as a uint8 to the *Event context. -func (e *Event) Uint8(key string, i uint8) *Event { - if e == nil { - return e - } - e.buf = enc.AppendUint8(enc.AppendKey(e.buf, key), i) - return e -} - -// Uints8 adds the field key with i as a []int8 to the *Event context. -func (e *Event) Uints8(key string, i []uint8) *Event { - if e == nil { - return e - } - e.buf = enc.AppendUints8(enc.AppendKey(e.buf, key), i) - return e -} - -// Uint16 adds the field key with i as a uint16 to the *Event context. -func (e *Event) Uint16(key string, i uint16) *Event { - if e == nil { - return e - } - e.buf = enc.AppendUint16(enc.AppendKey(e.buf, key), i) - return e -} - -// Uints16 adds the field key with i as a []int16 to the *Event context. -func (e *Event) Uints16(key string, i []uint16) *Event { - if e == nil { - return e - } - e.buf = enc.AppendUints16(enc.AppendKey(e.buf, key), i) - return e -} - -// Uint32 adds the field key with i as a uint32 to the *Event context. -func (e *Event) Uint32(key string, i uint32) *Event { - if e == nil { - return e - } - e.buf = enc.AppendUint32(enc.AppendKey(e.buf, key), i) - return e -} - -// Uints32 adds the field key with i as a []int32 to the *Event context. -func (e *Event) Uints32(key string, i []uint32) *Event { - if e == nil { - return e - } - e.buf = enc.AppendUints32(enc.AppendKey(e.buf, key), i) - return e -} - -// Uint64 adds the field key with i as a uint64 to the *Event context. -func (e *Event) Uint64(key string, i uint64) *Event { - if e == nil { - return e - } - e.buf = enc.AppendUint64(enc.AppendKey(e.buf, key), i) - return e -} - -// Uints64 adds the field key with i as a []int64 to the *Event context. -func (e *Event) Uints64(key string, i []uint64) *Event { - if e == nil { - return e - } - e.buf = enc.AppendUints64(enc.AppendKey(e.buf, key), i) - return e -} - -// Float32 adds the field key with f as a float32 to the *Event context. -func (e *Event) Float32(key string, f float32) *Event { - if e == nil { - return e - } - e.buf = enc.AppendFloat32(enc.AppendKey(e.buf, key), f, FloatingPointPrecision) - return e -} - -// Floats32 adds the field key with f as a []float32 to the *Event context. -func (e *Event) Floats32(key string, f []float32) *Event { - if e == nil { - return e - } - e.buf = enc.AppendFloats32(enc.AppendKey(e.buf, key), f, FloatingPointPrecision) - return e -} - -// Float64 adds the field key with f as a float64 to the *Event context. -func (e *Event) Float64(key string, f float64) *Event { - if e == nil { - return e - } - e.buf = enc.AppendFloat64(enc.AppendKey(e.buf, key), f, FloatingPointPrecision) - return e -} - -// Floats64 adds the field key with f as a []float64 to the *Event context. -func (e *Event) Floats64(key string, f []float64) *Event { - if e == nil { - return e - } - e.buf = enc.AppendFloats64(enc.AppendKey(e.buf, key), f, FloatingPointPrecision) - return e -} - -// Timestamp adds the current local time as UNIX timestamp to the *Event context with the "time" key. -// To customize the key name, change zerolog.TimestampFieldName. -// -// NOTE: It won't dedupe the "time" key if the *Event (or *Context) has one -// already. -func (e *Event) Timestamp() *Event { - if e == nil { - return e - } - e.buf = enc.AppendTime(enc.AppendKey(e.buf, TimestampFieldName), TimestampFunc(), TimeFieldFormat) - return e -} - -// Time adds the field key with t formatted as string using zerolog.TimeFieldFormat. -func (e *Event) Time(key string, t time.Time) *Event { - if e == nil { - return e - } - e.buf = enc.AppendTime(enc.AppendKey(e.buf, key), t, TimeFieldFormat) - return e -} - -// Times adds the field key with t formatted as string using zerolog.TimeFieldFormat. -func (e *Event) Times(key string, t []time.Time) *Event { - if e == nil { - return e - } - e.buf = enc.AppendTimes(enc.AppendKey(e.buf, key), t, TimeFieldFormat) - return e -} - -// Dur adds the field key with duration d stored as zerolog.DurationFieldUnit. -// If zerolog.DurationFieldInteger is true, durations are rendered as integer -// instead of float. -func (e *Event) Dur(key string, d time.Duration) *Event { - if e == nil { - return e - } - e.buf = enc.AppendDuration(enc.AppendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger, FloatingPointPrecision) - return e -} - -// Durs adds the field key with duration d stored as zerolog.DurationFieldUnit. -// If zerolog.DurationFieldInteger is true, durations are rendered as integer -// instead of float. -func (e *Event) Durs(key string, d []time.Duration) *Event { - if e == nil { - return e - } - e.buf = enc.AppendDurations(enc.AppendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger, FloatingPointPrecision) - return e -} - -// TimeDiff adds the field key with positive duration between time t and start. -// If time t is not greater than start, duration will be 0. -// Duration format follows the same principle as Dur(). -func (e *Event) TimeDiff(key string, t time.Time, start time.Time) *Event { - if e == nil { - return e - } - var d time.Duration - if t.After(start) { - d = t.Sub(start) - } - e.buf = enc.AppendDuration(enc.AppendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger, FloatingPointPrecision) - return e -} - -// Any is a wrapper around Event.Interface. -func (e *Event) Any(key string, i interface{}) *Event { - return e.Interface(key, i) -} - -// Interface adds the field key with i marshaled using reflection. -func (e *Event) Interface(key string, i interface{}) *Event { - if e == nil { - return e - } - if obj, ok := i.(LogObjectMarshaler); ok { - return e.Object(key, obj) - } - e.buf = enc.AppendInterface(enc.AppendKey(e.buf, key), i) - return e -} - -// Type adds the field key with val's type using reflection. -func (e *Event) Type(key string, val interface{}) *Event { - if e == nil { - return e - } - e.buf = enc.AppendType(enc.AppendKey(e.buf, key), val) - return e -} - -// CallerSkipFrame instructs any future Caller calls to skip the specified number of frames. -// This includes those added via hooks from the context. -func (e *Event) CallerSkipFrame(skip int) *Event { - if e == nil { - return e - } - e.skipFrame += skip - return e -} - -// Caller adds the file:line of the caller with the zerolog.CallerFieldName key. -// The argument skip is the number of stack frames to ascend -// Skip If not passed, use the global variable CallerSkipFrameCount -func (e *Event) Caller(skip ...int) *Event { - sk := CallerSkipFrameCount - if len(skip) > 0 { - sk = skip[0] + CallerSkipFrameCount - } - return e.caller(sk) -} - -func (e *Event) caller(skip int) *Event { - if e == nil { - return e - } - pc, file, line, ok := runtime.Caller(skip + e.skipFrame) - if !ok { - return e - } - e.buf = enc.AppendString(enc.AppendKey(e.buf, CallerFieldName), CallerMarshalFunc(pc, file, line)) - return e -} - -// IPAddr adds IPv4 or IPv6 Address to the event -func (e *Event) IPAddr(key string, ip net.IP) *Event { - if e == nil { - return e - } - e.buf = enc.AppendIPAddr(enc.AppendKey(e.buf, key), ip) - return e -} - -// IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the event -func (e *Event) IPPrefix(key string, pfx net.IPNet) *Event { - if e == nil { - return e - } - e.buf = enc.AppendIPPrefix(enc.AppendKey(e.buf, key), pfx) - return e -} - -// MACAddr adds MAC address to the event -func (e *Event) MACAddr(key string, ha net.HardwareAddr) *Event { - if e == nil { - return e - } - e.buf = enc.AppendMACAddr(enc.AppendKey(e.buf, key), ha) - return e -} diff --git a/vendor/github.com/rs/zerolog/example.jsonl b/vendor/github.com/rs/zerolog/example.jsonl deleted file mode 100644 index d73193d..0000000 --- a/vendor/github.com/rs/zerolog/example.jsonl +++ /dev/null @@ -1,7 +0,0 @@ -{"time":"5:41PM","level":"info","message":"Starting listener","listen":":8080","pid":37556} -{"time":"5:41PM","level":"debug","message":"Access","database":"myapp","host":"localhost:4962","pid":37556} -{"time":"5:41PM","level":"info","message":"Access","method":"GET","path":"/users","pid":37556,"resp_time":23} -{"time":"5:41PM","level":"info","message":"Access","method":"POST","path":"/posts","pid":37556,"resp_time":532} -{"time":"5:41PM","level":"warn","message":"Slow request","method":"POST","path":"/posts","pid":37556,"resp_time":532} -{"time":"5:41PM","level":"info","message":"Access","method":"GET","path":"/users","pid":37556,"resp_time":10} -{"time":"5:41PM","level":"error","message":"Database connection lost","database":"myapp","pid":37556,"error":"connection reset by peer"} diff --git a/vendor/github.com/rs/zerolog/fields.go b/vendor/github.com/rs/zerolog/fields.go deleted file mode 100644 index 99f5271..0000000 --- a/vendor/github.com/rs/zerolog/fields.go +++ /dev/null @@ -1,292 +0,0 @@ -package zerolog - -import ( - "encoding/json" - "net" - "sort" - "time" - "unsafe" -) - -func isNilValue(i interface{}) bool { - return (*[2]uintptr)(unsafe.Pointer(&i))[1] == 0 -} - -func appendFields(dst []byte, fields interface{}, stack bool) []byte { - switch fields := fields.(type) { - case []interface{}: - if n := len(fields); n&0x1 == 1 { // odd number - fields = fields[:n-1] - } - dst = appendFieldList(dst, fields, stack) - case map[string]interface{}: - keys := make([]string, 0, len(fields)) - for key := range fields { - keys = append(keys, key) - } - sort.Strings(keys) - kv := make([]interface{}, 2) - for _, key := range keys { - kv[0], kv[1] = key, fields[key] - dst = appendFieldList(dst, kv, stack) - } - } - return dst -} - -func appendFieldList(dst []byte, kvList []interface{}, stack bool) []byte { - for i, n := 0, len(kvList); i < n; i += 2 { - key, val := kvList[i], kvList[i+1] - if key, ok := key.(string); ok { - dst = enc.AppendKey(dst, key) - } else { - continue - } - if val, ok := val.(LogObjectMarshaler); ok { - e := newEvent(nil, 0) - e.buf = e.buf[:0] - e.appendObject(val) - dst = append(dst, e.buf...) - putEvent(e) - continue - } - switch val := val.(type) { - case string: - dst = enc.AppendString(dst, val) - case []byte: - dst = enc.AppendBytes(dst, val) - case error: - switch m := ErrorMarshalFunc(val).(type) { - case LogObjectMarshaler: - e := newEvent(nil, 0) - e.buf = e.buf[:0] - e.appendObject(m) - dst = append(dst, e.buf...) - putEvent(e) - case error: - if m == nil || isNilValue(m) { - dst = enc.AppendNil(dst) - } else { - dst = enc.AppendString(dst, m.Error()) - } - case string: - dst = enc.AppendString(dst, m) - default: - dst = enc.AppendInterface(dst, m) - } - - if stack && ErrorStackMarshaler != nil { - dst = enc.AppendKey(dst, ErrorStackFieldName) - switch m := ErrorStackMarshaler(val).(type) { - case nil: - case error: - if m != nil && !isNilValue(m) { - dst = enc.AppendString(dst, m.Error()) - } - case string: - dst = enc.AppendString(dst, m) - default: - dst = enc.AppendInterface(dst, m) - } - } - case []error: - dst = enc.AppendArrayStart(dst) - for i, err := range val { - switch m := ErrorMarshalFunc(err).(type) { - case LogObjectMarshaler: - e := newEvent(nil, 0) - e.buf = e.buf[:0] - e.appendObject(m) - dst = append(dst, e.buf...) - putEvent(e) - case error: - if m == nil || isNilValue(m) { - dst = enc.AppendNil(dst) - } else { - dst = enc.AppendString(dst, m.Error()) - } - case string: - dst = enc.AppendString(dst, m) - default: - dst = enc.AppendInterface(dst, m) - } - - if i < (len(val) - 1) { - enc.AppendArrayDelim(dst) - } - } - dst = enc.AppendArrayEnd(dst) - case bool: - dst = enc.AppendBool(dst, val) - case int: - dst = enc.AppendInt(dst, val) - case int8: - dst = enc.AppendInt8(dst, val) - case int16: - dst = enc.AppendInt16(dst, val) - case int32: - dst = enc.AppendInt32(dst, val) - case int64: - dst = enc.AppendInt64(dst, val) - case uint: - dst = enc.AppendUint(dst, val) - case uint8: - dst = enc.AppendUint8(dst, val) - case uint16: - dst = enc.AppendUint16(dst, val) - case uint32: - dst = enc.AppendUint32(dst, val) - case uint64: - dst = enc.AppendUint64(dst, val) - case float32: - dst = enc.AppendFloat32(dst, val, FloatingPointPrecision) - case float64: - dst = enc.AppendFloat64(dst, val, FloatingPointPrecision) - case time.Time: - dst = enc.AppendTime(dst, val, TimeFieldFormat) - case time.Duration: - dst = enc.AppendDuration(dst, val, DurationFieldUnit, DurationFieldInteger, FloatingPointPrecision) - case *string: - if val != nil { - dst = enc.AppendString(dst, *val) - } else { - dst = enc.AppendNil(dst) - } - case *bool: - if val != nil { - dst = enc.AppendBool(dst, *val) - } else { - dst = enc.AppendNil(dst) - } - case *int: - if val != nil { - dst = enc.AppendInt(dst, *val) - } else { - dst = enc.AppendNil(dst) - } - case *int8: - if val != nil { - dst = enc.AppendInt8(dst, *val) - } else { - dst = enc.AppendNil(dst) - } - case *int16: - if val != nil { - dst = enc.AppendInt16(dst, *val) - } else { - dst = enc.AppendNil(dst) - } - case *int32: - if val != nil { - dst = enc.AppendInt32(dst, *val) - } else { - dst = enc.AppendNil(dst) - } - case *int64: - if val != nil { - dst = enc.AppendInt64(dst, *val) - } else { - dst = enc.AppendNil(dst) - } - case *uint: - if val != nil { - dst = enc.AppendUint(dst, *val) - } else { - dst = enc.AppendNil(dst) - } - case *uint8: - if val != nil { - dst = enc.AppendUint8(dst, *val) - } else { - dst = enc.AppendNil(dst) - } - case *uint16: - if val != nil { - dst = enc.AppendUint16(dst, *val) - } else { - dst = enc.AppendNil(dst) - } - case *uint32: - if val != nil { - dst = enc.AppendUint32(dst, *val) - } else { - dst = enc.AppendNil(dst) - } - case *uint64: - if val != nil { - dst = enc.AppendUint64(dst, *val) - } else { - dst = enc.AppendNil(dst) - } - case *float32: - if val != nil { - dst = enc.AppendFloat32(dst, *val, FloatingPointPrecision) - } else { - dst = enc.AppendNil(dst) - } - case *float64: - if val != nil { - dst = enc.AppendFloat64(dst, *val, FloatingPointPrecision) - } else { - dst = enc.AppendNil(dst) - } - case *time.Time: - if val != nil { - dst = enc.AppendTime(dst, *val, TimeFieldFormat) - } else { - dst = enc.AppendNil(dst) - } - case *time.Duration: - if val != nil { - dst = enc.AppendDuration(dst, *val, DurationFieldUnit, DurationFieldInteger, FloatingPointPrecision) - } else { - dst = enc.AppendNil(dst) - } - case []string: - dst = enc.AppendStrings(dst, val) - case []bool: - dst = enc.AppendBools(dst, val) - case []int: - dst = enc.AppendInts(dst, val) - case []int8: - dst = enc.AppendInts8(dst, val) - case []int16: - dst = enc.AppendInts16(dst, val) - case []int32: - dst = enc.AppendInts32(dst, val) - case []int64: - dst = enc.AppendInts64(dst, val) - case []uint: - dst = enc.AppendUints(dst, val) - // case []uint8: - // dst = enc.AppendUints8(dst, val) - case []uint16: - dst = enc.AppendUints16(dst, val) - case []uint32: - dst = enc.AppendUints32(dst, val) - case []uint64: - dst = enc.AppendUints64(dst, val) - case []float32: - dst = enc.AppendFloats32(dst, val, FloatingPointPrecision) - case []float64: - dst = enc.AppendFloats64(dst, val, FloatingPointPrecision) - case []time.Time: - dst = enc.AppendTimes(dst, val, TimeFieldFormat) - case []time.Duration: - dst = enc.AppendDurations(dst, val, DurationFieldUnit, DurationFieldInteger, FloatingPointPrecision) - case nil: - dst = enc.AppendNil(dst) - case net.IP: - dst = enc.AppendIPAddr(dst, val) - case net.IPNet: - dst = enc.AppendIPPrefix(dst, val) - case net.HardwareAddr: - dst = enc.AppendMACAddr(dst, val) - case json.RawMessage: - dst = appendJSON(dst, val) - default: - dst = enc.AppendInterface(dst, val) - } - } - return dst -} diff --git a/vendor/github.com/rs/zerolog/globals.go b/vendor/github.com/rs/zerolog/globals.go deleted file mode 100644 index 9a9be71..0000000 --- a/vendor/github.com/rs/zerolog/globals.go +++ /dev/null @@ -1,190 +0,0 @@ -package zerolog - -import ( - "bytes" - "encoding/json" - "strconv" - "sync/atomic" - "time" -) - -const ( - // TimeFormatUnix defines a time format that makes time fields to be - // serialized as Unix timestamp integers. - TimeFormatUnix = "" - - // TimeFormatUnixMs defines a time format that makes time fields to be - // serialized as Unix timestamp integers in milliseconds. - TimeFormatUnixMs = "UNIXMS" - - // TimeFormatUnixMicro defines a time format that makes time fields to be - // serialized as Unix timestamp integers in microseconds. - TimeFormatUnixMicro = "UNIXMICRO" - - // TimeFormatUnixNano defines a time format that makes time fields to be - // serialized as Unix timestamp integers in nanoseconds. - TimeFormatUnixNano = "UNIXNANO" -) - -var ( - // TimestampFieldName is the field name used for the timestamp field. - TimestampFieldName = "time" - - // LevelFieldName is the field name used for the level field. - LevelFieldName = "level" - - // LevelTraceValue is the value used for the trace level field. - LevelTraceValue = "trace" - // LevelDebugValue is the value used for the debug level field. - LevelDebugValue = "debug" - // LevelInfoValue is the value used for the info level field. - LevelInfoValue = "info" - // LevelWarnValue is the value used for the warn level field. - LevelWarnValue = "warn" - // LevelErrorValue is the value used for the error level field. - LevelErrorValue = "error" - // LevelFatalValue is the value used for the fatal level field. - LevelFatalValue = "fatal" - // LevelPanicValue is the value used for the panic level field. - LevelPanicValue = "panic" - - // LevelFieldMarshalFunc allows customization of global level field marshaling. - LevelFieldMarshalFunc = func(l Level) string { - return l.String() - } - - // MessageFieldName is the field name used for the message field. - MessageFieldName = "message" - - // ErrorFieldName is the field name used for error fields. - ErrorFieldName = "error" - - // CallerFieldName is the field name used for caller field. - CallerFieldName = "caller" - - // CallerSkipFrameCount is the number of stack frames to skip to find the caller. - CallerSkipFrameCount = 2 - - // CallerMarshalFunc allows customization of global caller marshaling - CallerMarshalFunc = func(pc uintptr, file string, line int) string { - return file + ":" + strconv.Itoa(line) - } - - // ErrorStackFieldName is the field name used for error stacks. - ErrorStackFieldName = "stack" - - // ErrorStackMarshaler extract the stack from err if any. - ErrorStackMarshaler func(err error) interface{} - - // ErrorMarshalFunc allows customization of global error marshaling - ErrorMarshalFunc = func(err error) interface{} { - return err - } - - // InterfaceMarshalFunc allows customization of interface marshaling. - // Default: "encoding/json.Marshal" with disabled HTML escaping - InterfaceMarshalFunc = func(v interface{}) ([]byte, error) { - var buf bytes.Buffer - encoder := json.NewEncoder(&buf) - encoder.SetEscapeHTML(false) - err := encoder.Encode(v) - if err != nil { - return nil, err - } - b := buf.Bytes() - if len(b) > 0 { - // Remove trailing \n which is added by Encode. - return b[:len(b)-1], nil - } - return b, nil - } - - // TimeFieldFormat defines the time format of the Time field type. If set to - // TimeFormatUnix, TimeFormatUnixMs, TimeFormatUnixMicro or TimeFormatUnixNano, the time is formatted as a UNIX - // timestamp as integer. - TimeFieldFormat = time.RFC3339 - - // TimestampFunc defines the function called to generate a timestamp. - TimestampFunc = time.Now - - // DurationFieldUnit defines the unit for time.Duration type fields added - // using the Dur method. - DurationFieldUnit = time.Millisecond - - // DurationFieldInteger renders Dur fields as integer instead of float if - // set to true. - DurationFieldInteger = false - - // ErrorHandler is called whenever zerolog fails to write an event on its - // output. If not set, an error is printed on the stderr. This handler must - // be thread safe and non-blocking. - ErrorHandler func(err error) - - // DefaultContextLogger is returned from Ctx() if there is no logger associated - // with the context. - DefaultContextLogger *Logger - - // LevelColors are used by ConsoleWriter's consoleDefaultFormatLevel to color - // log levels. - LevelColors = map[Level]int{ - TraceLevel: colorBlue, - DebugLevel: 0, - InfoLevel: colorGreen, - WarnLevel: colorYellow, - ErrorLevel: colorRed, - FatalLevel: colorRed, - PanicLevel: colorRed, - } - - // FormattedLevels are used by ConsoleWriter's consoleDefaultFormatLevel - // for a short level name. - FormattedLevels = map[Level]string{ - TraceLevel: "TRC", - DebugLevel: "DBG", - InfoLevel: "INF", - WarnLevel: "WRN", - ErrorLevel: "ERR", - FatalLevel: "FTL", - PanicLevel: "PNC", - } - - // TriggerLevelWriterBufferReuseLimit is a limit in bytes that a buffer is dropped - // from the TriggerLevelWriter buffer pool if the buffer grows above the limit. - TriggerLevelWriterBufferReuseLimit = 64 * 1024 - - // FloatingPointPrecision, if set to a value other than -1, controls the number - // of digits when formatting float numbers in JSON. See strconv.FormatFloat for - // more details. - FloatingPointPrecision = -1 -) - -var ( - gLevel = new(int32) - disableSampling = new(int32) -) - -// SetGlobalLevel sets the global override for log level. If this -// values is raised, all Loggers will use at least this value. -// -// To globally disable logs, set GlobalLevel to Disabled. -func SetGlobalLevel(l Level) { - atomic.StoreInt32(gLevel, int32(l)) -} - -// GlobalLevel returns the current global log level -func GlobalLevel() Level { - return Level(atomic.LoadInt32(gLevel)) -} - -// DisableSampling will disable sampling in all Loggers if true. -func DisableSampling(v bool) { - var i int32 - if v { - i = 1 - } - atomic.StoreInt32(disableSampling, i) -} - -func samplingDisabled() bool { - return atomic.LoadInt32(disableSampling) == 1 -} diff --git a/vendor/github.com/rs/zerolog/go112.go b/vendor/github.com/rs/zerolog/go112.go deleted file mode 100644 index e7b5a1b..0000000 --- a/vendor/github.com/rs/zerolog/go112.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build go1.12 - -package zerolog - -// Since go 1.12, some auto generated init functions are hidden from -// runtime.Caller. -const contextCallerSkipFrameCount = 2 diff --git a/vendor/github.com/rs/zerolog/hook.go b/vendor/github.com/rs/zerolog/hook.go deleted file mode 100644 index ec6effc..0000000 --- a/vendor/github.com/rs/zerolog/hook.go +++ /dev/null @@ -1,64 +0,0 @@ -package zerolog - -// Hook defines an interface to a log hook. -type Hook interface { - // Run runs the hook with the event. - Run(e *Event, level Level, message string) -} - -// HookFunc is an adaptor to allow the use of an ordinary function -// as a Hook. -type HookFunc func(e *Event, level Level, message string) - -// Run implements the Hook interface. -func (h HookFunc) Run(e *Event, level Level, message string) { - h(e, level, message) -} - -// LevelHook applies a different hook for each level. -type LevelHook struct { - NoLevelHook, TraceHook, DebugHook, InfoHook, WarnHook, ErrorHook, FatalHook, PanicHook Hook -} - -// Run implements the Hook interface. -func (h LevelHook) Run(e *Event, level Level, message string) { - switch level { - case TraceLevel: - if h.TraceHook != nil { - h.TraceHook.Run(e, level, message) - } - case DebugLevel: - if h.DebugHook != nil { - h.DebugHook.Run(e, level, message) - } - case InfoLevel: - if h.InfoHook != nil { - h.InfoHook.Run(e, level, message) - } - case WarnLevel: - if h.WarnHook != nil { - h.WarnHook.Run(e, level, message) - } - case ErrorLevel: - if h.ErrorHook != nil { - h.ErrorHook.Run(e, level, message) - } - case FatalLevel: - if h.FatalHook != nil { - h.FatalHook.Run(e, level, message) - } - case PanicLevel: - if h.PanicHook != nil { - h.PanicHook.Run(e, level, message) - } - case NoLevel: - if h.NoLevelHook != nil { - h.NoLevelHook.Run(e, level, message) - } - } -} - -// NewLevelHook returns a new LevelHook. -func NewLevelHook() LevelHook { - return LevelHook{} -} diff --git a/vendor/github.com/rs/zerolog/internal/cbor/README.md b/vendor/github.com/rs/zerolog/internal/cbor/README.md deleted file mode 100644 index 92c2e8c..0000000 --- a/vendor/github.com/rs/zerolog/internal/cbor/README.md +++ /dev/null @@ -1,56 +0,0 @@ -## Reference: - CBOR Encoding is described in [RFC7049](https://tools.ietf.org/html/rfc7049) - -## Comparison of JSON vs CBOR - -Two main areas of reduction are: - -1. CPU usage to write a log msg -2. Size (in bytes) of log messages. - - -CPU Usage savings are below: -``` -name JSON time/op CBOR time/op delta -Info-32 15.3ns ± 1% 11.7ns ± 3% -23.78% (p=0.000 n=9+10) -ContextFields-32 16.2ns ± 2% 12.3ns ± 3% -23.97% (p=0.000 n=9+9) -ContextAppend-32 6.70ns ± 0% 6.20ns ± 0% -7.44% (p=0.000 n=9+9) -LogFields-32 66.4ns ± 0% 24.6ns ± 2% -62.89% (p=0.000 n=10+9) -LogArrayObject-32 911ns ±11% 768ns ± 6% -15.64% (p=0.000 n=10+10) -LogFieldType/Floats-32 70.3ns ± 2% 29.5ns ± 1% -57.98% (p=0.000 n=10+10) -LogFieldType/Err-32 14.0ns ± 3% 12.1ns ± 8% -13.20% (p=0.000 n=8+10) -LogFieldType/Dur-32 17.2ns ± 2% 13.1ns ± 1% -24.27% (p=0.000 n=10+9) -LogFieldType/Object-32 54.3ns ±11% 52.3ns ± 7% ~ (p=0.239 n=10+10) -LogFieldType/Ints-32 20.3ns ± 2% 15.1ns ± 2% -25.50% (p=0.000 n=9+10) -LogFieldType/Interfaces-32 642ns ±11% 621ns ± 9% ~ (p=0.118 n=10+10) -LogFieldType/Interface(Objects)-32 635ns ±13% 632ns ± 9% ~ (p=0.592 n=10+10) -LogFieldType/Times-32 294ns ± 0% 27ns ± 1% -90.71% (p=0.000 n=10+9) -LogFieldType/Durs-32 121ns ± 0% 33ns ± 2% -72.44% (p=0.000 n=9+9) -LogFieldType/Interface(Object)-32 56.6ns ± 8% 52.3ns ± 8% -7.54% (p=0.007 n=10+10) -LogFieldType/Errs-32 17.8ns ± 3% 16.1ns ± 2% -9.71% (p=0.000 n=10+9) -LogFieldType/Time-32 40.5ns ± 1% 12.7ns ± 6% -68.66% (p=0.000 n=8+9) -LogFieldType/Bool-32 12.0ns ± 5% 10.2ns ± 2% -15.18% (p=0.000 n=10+8) -LogFieldType/Bools-32 17.2ns ± 2% 12.6ns ± 4% -26.63% (p=0.000 n=10+10) -LogFieldType/Int-32 12.3ns ± 2% 11.2ns ± 4% -9.27% (p=0.000 n=9+10) -LogFieldType/Float-32 16.7ns ± 1% 12.6ns ± 2% -24.42% (p=0.000 n=7+9) -LogFieldType/Str-32 12.7ns ± 7% 11.3ns ± 7% -10.88% (p=0.000 n=10+9) -LogFieldType/Strs-32 20.3ns ± 3% 18.2ns ± 3% -10.25% (p=0.000 n=9+10) -LogFieldType/Interface-32 183ns ±12% 175ns ± 9% ~ (p=0.078 n=10+10) -``` - -Log message size savings is greatly dependent on the number and type of fields in the log message. -Assuming this log message (with an Integer, timestamp and string, in addition to level). - -`{"level":"error","Fault":41650,"time":"2018-04-01T15:18:19-07:00","message":"Some Message"}` - -Two measurements were done for the log file sizes - one without any compression, second -using [compress/zlib](https://golang.org/pkg/compress/zlib/). - -Results for 10,000 log messages: - -| Log Format | Plain File Size (in KB) | Compressed File Size (in KB) | -| :--- | :---: | :---: | -| JSON | 920 | 28 | -| CBOR | 550 | 28 | - -The example used to calculate the above data is available in [Examples](examples). diff --git a/vendor/github.com/rs/zerolog/internal/cbor/base.go b/vendor/github.com/rs/zerolog/internal/cbor/base.go deleted file mode 100644 index 51fe86c..0000000 --- a/vendor/github.com/rs/zerolog/internal/cbor/base.go +++ /dev/null @@ -1,19 +0,0 @@ -package cbor - -// JSONMarshalFunc is used to marshal interface to JSON encoded byte slice. -// Making it package level instead of embedded in Encoder brings -// some extra efforts at importing, but avoids value copy when the functions -// of Encoder being invoked. -// DO REMEMBER to set this variable at importing, or -// you might get a nil pointer dereference panic at runtime. -var JSONMarshalFunc func(v interface{}) ([]byte, error) - -type Encoder struct{} - -// AppendKey adds a key (string) to the binary encoded log message -func (e Encoder) AppendKey(dst []byte, key string) []byte { - if len(dst) < 1 { - dst = e.AppendBeginMarker(dst) - } - return e.AppendString(dst, key) -} diff --git a/vendor/github.com/rs/zerolog/internal/cbor/cbor.go b/vendor/github.com/rs/zerolog/internal/cbor/cbor.go deleted file mode 100644 index 1bf1443..0000000 --- a/vendor/github.com/rs/zerolog/internal/cbor/cbor.go +++ /dev/null @@ -1,102 +0,0 @@ -// Package cbor provides primitives for storing different data -// in the CBOR (binary) format. CBOR is defined in RFC7049. -package cbor - -import "time" - -const ( - majorOffset = 5 - additionalMax = 23 - - // Non Values. - additionalTypeBoolFalse byte = 20 - additionalTypeBoolTrue byte = 21 - additionalTypeNull byte = 22 - - // Integer (+ve and -ve) Sub-types. - additionalTypeIntUint8 byte = 24 - additionalTypeIntUint16 byte = 25 - additionalTypeIntUint32 byte = 26 - additionalTypeIntUint64 byte = 27 - - // Float Sub-types. - additionalTypeFloat16 byte = 25 - additionalTypeFloat32 byte = 26 - additionalTypeFloat64 byte = 27 - additionalTypeBreak byte = 31 - - // Tag Sub-types. - additionalTypeTimestamp byte = 01 - additionalTypeEmbeddedCBOR byte = 63 - - // Extended Tags - from https://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml - additionalTypeTagNetworkAddr uint16 = 260 - additionalTypeTagNetworkPrefix uint16 = 261 - additionalTypeEmbeddedJSON uint16 = 262 - additionalTypeTagHexString uint16 = 263 - - // Unspecified number of elements. - additionalTypeInfiniteCount byte = 31 -) -const ( - majorTypeUnsignedInt byte = iota << majorOffset // Major type 0 - majorTypeNegativeInt // Major type 1 - majorTypeByteString // Major type 2 - majorTypeUtf8String // Major type 3 - majorTypeArray // Major type 4 - majorTypeMap // Major type 5 - majorTypeTags // Major type 6 - majorTypeSimpleAndFloat // Major type 7 -) - -const ( - maskOutAdditionalType byte = (7 << majorOffset) - maskOutMajorType byte = 31 -) - -const ( - float32Nan = "\xfa\x7f\xc0\x00\x00" - float32PosInfinity = "\xfa\x7f\x80\x00\x00" - float32NegInfinity = "\xfa\xff\x80\x00\x00" - float64Nan = "\xfb\x7f\xf8\x00\x00\x00\x00\x00\x00" - float64PosInfinity = "\xfb\x7f\xf0\x00\x00\x00\x00\x00\x00" - float64NegInfinity = "\xfb\xff\xf0\x00\x00\x00\x00\x00\x00" -) - -// IntegerTimeFieldFormat indicates the format of timestamp decoded -// from an integer (time in seconds). -var IntegerTimeFieldFormat = time.RFC3339 - -// NanoTimeFieldFormat indicates the format of timestamp decoded -// from a float value (time in seconds and nanoseconds). -var NanoTimeFieldFormat = time.RFC3339Nano - -func appendCborTypePrefix(dst []byte, major byte, number uint64) []byte { - byteCount := 8 - var minor byte - switch { - case number < 256: - byteCount = 1 - minor = additionalTypeIntUint8 - - case number < 65536: - byteCount = 2 - minor = additionalTypeIntUint16 - - case number < 4294967296: - byteCount = 4 - minor = additionalTypeIntUint32 - - default: - byteCount = 8 - minor = additionalTypeIntUint64 - - } - - dst = append(dst, major|minor) - byteCount-- - for ; byteCount >= 0; byteCount-- { - dst = append(dst, byte(number>>(uint(byteCount)*8))) - } - return dst -} diff --git a/vendor/github.com/rs/zerolog/internal/cbor/decode_stream.go b/vendor/github.com/rs/zerolog/internal/cbor/decode_stream.go deleted file mode 100644 index 5633e66..0000000 --- a/vendor/github.com/rs/zerolog/internal/cbor/decode_stream.go +++ /dev/null @@ -1,654 +0,0 @@ -package cbor - -// This file contains code to decode a stream of CBOR Data into JSON. - -import ( - "bufio" - "bytes" - "encoding/base64" - "fmt" - "io" - "math" - "net" - "runtime" - "strconv" - "strings" - "time" - "unicode/utf8" -) - -var decodeTimeZone *time.Location - -const hexTable = "0123456789abcdef" - -const isFloat32 = 4 -const isFloat64 = 8 - -func readNBytes(src *bufio.Reader, n int) []byte { - ret := make([]byte, n) - for i := 0; i < n; i++ { - ch, e := src.ReadByte() - if e != nil { - panic(fmt.Errorf("Tried to Read %d Bytes.. But hit end of file", n)) - } - ret[i] = ch - } - return ret -} - -func readByte(src *bufio.Reader) byte { - b, e := src.ReadByte() - if e != nil { - panic(fmt.Errorf("Tried to Read 1 Byte.. But hit end of file")) - } - return b -} - -func decodeIntAdditionalType(src *bufio.Reader, minor byte) int64 { - val := int64(0) - if minor <= 23 { - val = int64(minor) - } else { - bytesToRead := 0 - switch minor { - case additionalTypeIntUint8: - bytesToRead = 1 - case additionalTypeIntUint16: - bytesToRead = 2 - case additionalTypeIntUint32: - bytesToRead = 4 - case additionalTypeIntUint64: - bytesToRead = 8 - default: - panic(fmt.Errorf("Invalid Additional Type: %d in decodeInteger (expected <28)", minor)) - } - pb := readNBytes(src, bytesToRead) - for i := 0; i < bytesToRead; i++ { - val = val * 256 - val += int64(pb[i]) - } - } - return val -} - -func decodeInteger(src *bufio.Reader) int64 { - pb := readByte(src) - major := pb & maskOutAdditionalType - minor := pb & maskOutMajorType - if major != majorTypeUnsignedInt && major != majorTypeNegativeInt { - panic(fmt.Errorf("Major type is: %d in decodeInteger!! (expected 0 or 1)", major)) - } - val := decodeIntAdditionalType(src, minor) - if major == 0 { - return val - } - return (-1 - val) -} - -func decodeFloat(src *bufio.Reader) (float64, int) { - pb := readByte(src) - major := pb & maskOutAdditionalType - minor := pb & maskOutMajorType - if major != majorTypeSimpleAndFloat { - panic(fmt.Errorf("Incorrect Major type is: %d in decodeFloat", major)) - } - - switch minor { - case additionalTypeFloat16: - panic(fmt.Errorf("float16 is not supported in decodeFloat")) - - case additionalTypeFloat32: - pb := readNBytes(src, 4) - switch string(pb) { - case float32Nan: - return math.NaN(), isFloat32 - case float32PosInfinity: - return math.Inf(0), isFloat32 - case float32NegInfinity: - return math.Inf(-1), isFloat32 - } - n := uint32(0) - for i := 0; i < 4; i++ { - n = n * 256 - n += uint32(pb[i]) - } - val := math.Float32frombits(n) - return float64(val), isFloat32 - case additionalTypeFloat64: - pb := readNBytes(src, 8) - switch string(pb) { - case float64Nan: - return math.NaN(), isFloat64 - case float64PosInfinity: - return math.Inf(0), isFloat64 - case float64NegInfinity: - return math.Inf(-1), isFloat64 - } - n := uint64(0) - for i := 0; i < 8; i++ { - n = n * 256 - n += uint64(pb[i]) - } - val := math.Float64frombits(n) - return val, isFloat64 - } - panic(fmt.Errorf("Invalid Additional Type: %d in decodeFloat", minor)) -} - -func decodeStringComplex(dst []byte, s string, pos uint) []byte { - i := int(pos) - start := 0 - - for i < len(s) { - b := s[i] - if b >= utf8.RuneSelf { - r, size := utf8.DecodeRuneInString(s[i:]) - if r == utf8.RuneError && size == 1 { - // In case of error, first append previous simple characters to - // the byte slice if any and append a replacement character code - // in place of the invalid sequence. - if start < i { - dst = append(dst, s[start:i]...) - } - dst = append(dst, `\ufffd`...) - i += size - start = i - continue - } - i += size - continue - } - if b >= 0x20 && b <= 0x7e && b != '\\' && b != '"' { - i++ - continue - } - // We encountered a character that needs to be encoded. - // Let's append the previous simple characters to the byte slice - // and switch our operation to read and encode the remainder - // characters byte-by-byte. - if start < i { - dst = append(dst, s[start:i]...) - } - switch b { - case '"', '\\': - dst = append(dst, '\\', b) - case '\b': - dst = append(dst, '\\', 'b') - case '\f': - dst = append(dst, '\\', 'f') - case '\n': - dst = append(dst, '\\', 'n') - case '\r': - dst = append(dst, '\\', 'r') - case '\t': - dst = append(dst, '\\', 't') - default: - dst = append(dst, '\\', 'u', '0', '0', hexTable[b>>4], hexTable[b&0xF]) - } - i++ - start = i - } - if start < len(s) { - dst = append(dst, s[start:]...) - } - return dst -} - -func decodeString(src *bufio.Reader, noQuotes bool) []byte { - pb := readByte(src) - major := pb & maskOutAdditionalType - minor := pb & maskOutMajorType - if major != majorTypeByteString { - panic(fmt.Errorf("Major type is: %d in decodeString", major)) - } - result := []byte{} - if !noQuotes { - result = append(result, '"') - } - length := decodeIntAdditionalType(src, minor) - len := int(length) - pbs := readNBytes(src, len) - result = append(result, pbs...) - if noQuotes { - return result - } - return append(result, '"') -} -func decodeStringToDataUrl(src *bufio.Reader, mimeType string) []byte { - pb := readByte(src) - major := pb & maskOutAdditionalType - minor := pb & maskOutMajorType - if major != majorTypeByteString { - panic(fmt.Errorf("Major type is: %d in decodeString", major)) - } - length := decodeIntAdditionalType(src, minor) - l := int(length) - enc := base64.StdEncoding - lEnc := enc.EncodedLen(l) - result := make([]byte, len("\"data:;base64,\"")+len(mimeType)+lEnc) - dest := result - u := copy(dest, "\"data:") - dest = dest[u:] - u = copy(dest, mimeType) - dest = dest[u:] - u = copy(dest, ";base64,") - dest = dest[u:] - pbs := readNBytes(src, l) - enc.Encode(dest, pbs) - dest = dest[lEnc:] - dest[0] = '"' - return result -} - -func decodeUTF8String(src *bufio.Reader) []byte { - pb := readByte(src) - major := pb & maskOutAdditionalType - minor := pb & maskOutMajorType - if major != majorTypeUtf8String { - panic(fmt.Errorf("Major type is: %d in decodeUTF8String", major)) - } - result := []byte{'"'} - length := decodeIntAdditionalType(src, minor) - len := int(length) - pbs := readNBytes(src, len) - - for i := 0; i < len; i++ { - // Check if the character needs encoding. Control characters, slashes, - // and the double quote need json encoding. Bytes above the ascii - // boundary needs utf8 encoding. - if pbs[i] < 0x20 || pbs[i] > 0x7e || pbs[i] == '\\' || pbs[i] == '"' { - // We encountered a character that needs to be encoded. Switch - // to complex version of the algorithm. - dst := []byte{'"'} - dst = decodeStringComplex(dst, string(pbs), uint(i)) - return append(dst, '"') - } - } - // The string has no need for encoding and therefore is directly - // appended to the byte slice. - result = append(result, pbs...) - return append(result, '"') -} - -func array2Json(src *bufio.Reader, dst io.Writer) { - dst.Write([]byte{'['}) - pb := readByte(src) - major := pb & maskOutAdditionalType - minor := pb & maskOutMajorType - if major != majorTypeArray { - panic(fmt.Errorf("Major type is: %d in array2Json", major)) - } - len := 0 - unSpecifiedCount := false - if minor == additionalTypeInfiniteCount { - unSpecifiedCount = true - } else { - length := decodeIntAdditionalType(src, minor) - len = int(length) - } - for i := 0; unSpecifiedCount || i < len; i++ { - if unSpecifiedCount { - pb, e := src.Peek(1) - if e != nil { - panic(e) - } - if pb[0] == majorTypeSimpleAndFloat|additionalTypeBreak { - readByte(src) - break - } - } - cbor2JsonOneObject(src, dst) - if unSpecifiedCount { - pb, e := src.Peek(1) - if e != nil { - panic(e) - } - if pb[0] == majorTypeSimpleAndFloat|additionalTypeBreak { - readByte(src) - break - } - dst.Write([]byte{','}) - } else if i+1 < len { - dst.Write([]byte{','}) - } - } - dst.Write([]byte{']'}) -} - -func map2Json(src *bufio.Reader, dst io.Writer) { - pb := readByte(src) - major := pb & maskOutAdditionalType - minor := pb & maskOutMajorType - if major != majorTypeMap { - panic(fmt.Errorf("Major type is: %d in map2Json", major)) - } - len := 0 - unSpecifiedCount := false - if minor == additionalTypeInfiniteCount { - unSpecifiedCount = true - } else { - length := decodeIntAdditionalType(src, minor) - len = int(length) - } - dst.Write([]byte{'{'}) - for i := 0; unSpecifiedCount || i < len; i++ { - if unSpecifiedCount { - pb, e := src.Peek(1) - if e != nil { - panic(e) - } - if pb[0] == majorTypeSimpleAndFloat|additionalTypeBreak { - readByte(src) - break - } - } - cbor2JsonOneObject(src, dst) - if i%2 == 0 { - // Even position values are keys. - dst.Write([]byte{':'}) - } else { - if unSpecifiedCount { - pb, e := src.Peek(1) - if e != nil { - panic(e) - } - if pb[0] == majorTypeSimpleAndFloat|additionalTypeBreak { - readByte(src) - break - } - dst.Write([]byte{','}) - } else if i+1 < len { - dst.Write([]byte{','}) - } - } - } - dst.Write([]byte{'}'}) -} - -func decodeTagData(src *bufio.Reader) []byte { - pb := readByte(src) - major := pb & maskOutAdditionalType - minor := pb & maskOutMajorType - if major != majorTypeTags { - panic(fmt.Errorf("Major type is: %d in decodeTagData", major)) - } - switch minor { - case additionalTypeTimestamp: - return decodeTimeStamp(src) - case additionalTypeIntUint8: - val := decodeIntAdditionalType(src, minor) - switch byte(val) { - case additionalTypeEmbeddedCBOR: - pb := readByte(src) - dataMajor := pb & maskOutAdditionalType - if dataMajor != majorTypeByteString { - panic(fmt.Errorf("Unsupported embedded Type: %d in decodeEmbeddedCBOR", dataMajor)) - } - src.UnreadByte() - return decodeStringToDataUrl(src, "application/cbor") - default: - panic(fmt.Errorf("Unsupported Additional Tag Type: %d in decodeTagData", val)) - } - - // Tag value is larger than 256 (so uint16). - case additionalTypeIntUint16: - val := decodeIntAdditionalType(src, minor) - - switch uint16(val) { - case additionalTypeEmbeddedJSON: - pb := readByte(src) - dataMajor := pb & maskOutAdditionalType - if dataMajor != majorTypeByteString { - panic(fmt.Errorf("Unsupported embedded Type: %d in decodeEmbeddedJSON", dataMajor)) - } - src.UnreadByte() - return decodeString(src, true) - - case additionalTypeTagNetworkAddr: - octets := decodeString(src, true) - ss := []byte{'"'} - switch len(octets) { - case 6: // MAC address. - ha := net.HardwareAddr(octets) - ss = append(append(ss, ha.String()...), '"') - case 4: // IPv4 address. - fallthrough - case 16: // IPv6 address. - ip := net.IP(octets) - ss = append(append(ss, ip.String()...), '"') - default: - panic(fmt.Errorf("Unexpected Network Address length: %d (expected 4,6,16)", len(octets))) - } - return ss - - case additionalTypeTagNetworkPrefix: - pb := readByte(src) - if pb != majorTypeMap|0x1 { - panic(fmt.Errorf("IP Prefix is NOT of MAP of 1 elements as expected")) - } - octets := decodeString(src, true) - val := decodeInteger(src) - ip := net.IP(octets) - var mask net.IPMask - pfxLen := int(val) - if len(octets) == 4 { - mask = net.CIDRMask(pfxLen, 32) - } else { - mask = net.CIDRMask(pfxLen, 128) - } - ipPfx := net.IPNet{IP: ip, Mask: mask} - ss := []byte{'"'} - ss = append(append(ss, ipPfx.String()...), '"') - return ss - - case additionalTypeTagHexString: - octets := decodeString(src, true) - ss := []byte{'"'} - for _, v := range octets { - ss = append(ss, hexTable[v>>4], hexTable[v&0x0f]) - } - return append(ss, '"') - - default: - panic(fmt.Errorf("Unsupported Additional Tag Type: %d in decodeTagData", val)) - } - } - panic(fmt.Errorf("Unsupported Additional Type: %d in decodeTagData", minor)) -} - -func decodeTimeStamp(src *bufio.Reader) []byte { - pb := readByte(src) - src.UnreadByte() - tsMajor := pb & maskOutAdditionalType - if tsMajor == majorTypeUnsignedInt || tsMajor == majorTypeNegativeInt { - n := decodeInteger(src) - t := time.Unix(n, 0) - if decodeTimeZone != nil { - t = t.In(decodeTimeZone) - } else { - t = t.In(time.UTC) - } - tsb := []byte{} - tsb = append(tsb, '"') - tsb = t.AppendFormat(tsb, IntegerTimeFieldFormat) - tsb = append(tsb, '"') - return tsb - } else if tsMajor == majorTypeSimpleAndFloat { - n, _ := decodeFloat(src) - secs := int64(n) - n -= float64(secs) - n *= float64(1e9) - t := time.Unix(secs, int64(n)) - if decodeTimeZone != nil { - t = t.In(decodeTimeZone) - } else { - t = t.In(time.UTC) - } - tsb := []byte{} - tsb = append(tsb, '"') - tsb = t.AppendFormat(tsb, NanoTimeFieldFormat) - tsb = append(tsb, '"') - return tsb - } - panic(fmt.Errorf("TS format is neigther int nor float: %d", tsMajor)) -} - -func decodeSimpleFloat(src *bufio.Reader) []byte { - pb := readByte(src) - major := pb & maskOutAdditionalType - minor := pb & maskOutMajorType - if major != majorTypeSimpleAndFloat { - panic(fmt.Errorf("Major type is: %d in decodeSimpleFloat", major)) - } - switch minor { - case additionalTypeBoolTrue: - return []byte("true") - case additionalTypeBoolFalse: - return []byte("false") - case additionalTypeNull: - return []byte("null") - case additionalTypeFloat16: - fallthrough - case additionalTypeFloat32: - fallthrough - case additionalTypeFloat64: - src.UnreadByte() - v, bc := decodeFloat(src) - ba := []byte{} - switch { - case math.IsNaN(v): - return []byte("\"NaN\"") - case math.IsInf(v, 1): - return []byte("\"+Inf\"") - case math.IsInf(v, -1): - return []byte("\"-Inf\"") - } - if bc == isFloat32 { - ba = strconv.AppendFloat(ba, v, 'f', -1, 32) - } else if bc == isFloat64 { - ba = strconv.AppendFloat(ba, v, 'f', -1, 64) - } else { - panic(fmt.Errorf("Invalid Float precision from decodeFloat: %d", bc)) - } - return ba - default: - panic(fmt.Errorf("Invalid Additional Type: %d in decodeSimpleFloat", minor)) - } -} - -func cbor2JsonOneObject(src *bufio.Reader, dst io.Writer) { - pb, e := src.Peek(1) - if e != nil { - panic(e) - } - major := (pb[0] & maskOutAdditionalType) - - switch major { - case majorTypeUnsignedInt: - fallthrough - case majorTypeNegativeInt: - n := decodeInteger(src) - dst.Write([]byte(strconv.Itoa(int(n)))) - - case majorTypeByteString: - s := decodeString(src, false) - dst.Write(s) - - case majorTypeUtf8String: - s := decodeUTF8String(src) - dst.Write(s) - - case majorTypeArray: - array2Json(src, dst) - - case majorTypeMap: - map2Json(src, dst) - - case majorTypeTags: - s := decodeTagData(src) - dst.Write(s) - - case majorTypeSimpleAndFloat: - s := decodeSimpleFloat(src) - dst.Write(s) - } -} - -func moreBytesToRead(src *bufio.Reader) bool { - _, e := src.ReadByte() - if e == nil { - src.UnreadByte() - return true - } - return false -} - -// Cbor2JsonManyObjects decodes all the CBOR Objects read from src -// reader. It keeps on decoding until reader returns EOF (error when reading). -// Decoded string is written to the dst. At the end of every CBOR Object -// newline is written to the output stream. -// -// Returns error (if any) that was encountered during decode. -// The child functions will generate a panic when error is encountered and -// this function will recover non-runtime Errors and return the reason as error. -func Cbor2JsonManyObjects(src io.Reader, dst io.Writer) (err error) { - defer func() { - if r := recover(); r != nil { - if _, ok := r.(runtime.Error); ok { - panic(r) - } - err = r.(error) - } - }() - bufRdr := bufio.NewReader(src) - for moreBytesToRead(bufRdr) { - cbor2JsonOneObject(bufRdr, dst) - dst.Write([]byte("\n")) - } - return nil -} - -// Detect if the bytes to be printed is Binary or not. -func binaryFmt(p []byte) bool { - if len(p) > 0 && p[0] > 0x7F { - return true - } - return false -} - -func getReader(str string) *bufio.Reader { - return bufio.NewReader(strings.NewReader(str)) -} - -// DecodeIfBinaryToString converts a binary formatted log msg to a -// JSON formatted String Log message - suitable for printing to Console/Syslog. -func DecodeIfBinaryToString(in []byte) string { - if binaryFmt(in) { - var b bytes.Buffer - Cbor2JsonManyObjects(strings.NewReader(string(in)), &b) - return b.String() - } - return string(in) -} - -// DecodeObjectToStr checks if the input is a binary format, if so, -// it will decode a single Object and return the decoded string. -func DecodeObjectToStr(in []byte) string { - if binaryFmt(in) { - var b bytes.Buffer - cbor2JsonOneObject(getReader(string(in)), &b) - return b.String() - } - return string(in) -} - -// DecodeIfBinaryToBytes checks if the input is a binary format, if so, -// it will decode all Objects and return the decoded string as byte array. -func DecodeIfBinaryToBytes(in []byte) []byte { - if binaryFmt(in) { - var b bytes.Buffer - Cbor2JsonManyObjects(bytes.NewReader(in), &b) - return b.Bytes() - } - return in -} diff --git a/vendor/github.com/rs/zerolog/internal/cbor/string.go b/vendor/github.com/rs/zerolog/internal/cbor/string.go deleted file mode 100644 index 9fc9a4f..0000000 --- a/vendor/github.com/rs/zerolog/internal/cbor/string.go +++ /dev/null @@ -1,117 +0,0 @@ -package cbor - -import "fmt" - -// AppendStrings encodes and adds an array of strings to the dst byte array. -func (e Encoder) AppendStrings(dst []byte, vals []string) []byte { - major := majorTypeArray - l := len(vals) - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendString(dst, v) - } - return dst -} - -// AppendString encodes and adds a string to the dst byte array. -func (Encoder) AppendString(dst []byte, s string) []byte { - major := majorTypeUtf8String - - l := len(s) - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, majorTypeUtf8String, uint64(l)) - } - return append(dst, s...) -} - -// AppendStringers encodes and adds an array of Stringer values -// to the dst byte array. -func (e Encoder) AppendStringers(dst []byte, vals []fmt.Stringer) []byte { - if len(vals) == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - dst = e.AppendArrayStart(dst) - dst = e.AppendStringer(dst, vals[0]) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = e.AppendStringer(dst, val) - } - } - return e.AppendArrayEnd(dst) -} - -// AppendStringer encodes and adds the Stringer value to the dst -// byte array. -func (e Encoder) AppendStringer(dst []byte, val fmt.Stringer) []byte { - if val == nil { - return e.AppendNil(dst) - } - return e.AppendString(dst, val.String()) -} - -// AppendBytes encodes and adds an array of bytes to the dst byte array. -func (Encoder) AppendBytes(dst, s []byte) []byte { - major := majorTypeByteString - - l := len(s) - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - return append(dst, s...) -} - -// AppendEmbeddedJSON adds a tag and embeds input JSON as such. -func AppendEmbeddedJSON(dst, s []byte) []byte { - major := majorTypeTags - minor := additionalTypeEmbeddedJSON - - // Append the TAG to indicate this is Embedded JSON. - dst = append(dst, major|additionalTypeIntUint16) - dst = append(dst, byte(minor>>8)) - dst = append(dst, byte(minor&0xff)) - - // Append the JSON Object as Byte String. - major = majorTypeByteString - - l := len(s) - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - return append(dst, s...) -} - -// AppendEmbeddedCBOR adds a tag and embeds input CBOR as such. -func AppendEmbeddedCBOR(dst, s []byte) []byte { - major := majorTypeTags - minor := additionalTypeEmbeddedCBOR - - // Append the TAG to indicate this is Embedded JSON. - dst = append(dst, major|additionalTypeIntUint8) - dst = append(dst, minor) - - // Append the CBOR Object as Byte String. - major = majorTypeByteString - - l := len(s) - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - return append(dst, s...) -} diff --git a/vendor/github.com/rs/zerolog/internal/cbor/time.go b/vendor/github.com/rs/zerolog/internal/cbor/time.go deleted file mode 100644 index 7c0ecce..0000000 --- a/vendor/github.com/rs/zerolog/internal/cbor/time.go +++ /dev/null @@ -1,93 +0,0 @@ -package cbor - -import ( - "time" -) - -func appendIntegerTimestamp(dst []byte, t time.Time) []byte { - major := majorTypeTags - minor := additionalTypeTimestamp - dst = append(dst, major|minor) - secs := t.Unix() - var val uint64 - if secs < 0 { - major = majorTypeNegativeInt - val = uint64(-secs - 1) - } else { - major = majorTypeUnsignedInt - val = uint64(secs) - } - dst = appendCborTypePrefix(dst, major, val) - return dst -} - -func (e Encoder) appendFloatTimestamp(dst []byte, t time.Time) []byte { - major := majorTypeTags - minor := additionalTypeTimestamp - dst = append(dst, major|minor) - secs := t.Unix() - nanos := t.Nanosecond() - var val float64 - val = float64(secs)*1.0 + float64(nanos)*1e-9 - return e.AppendFloat64(dst, val, -1) -} - -// AppendTime encodes and adds a timestamp to the dst byte array. -func (e Encoder) AppendTime(dst []byte, t time.Time, unused string) []byte { - utc := t.UTC() - if utc.Nanosecond() == 0 { - return appendIntegerTimestamp(dst, utc) - } - return e.appendFloatTimestamp(dst, utc) -} - -// AppendTimes encodes and adds an array of timestamps to the dst byte array. -func (e Encoder) AppendTimes(dst []byte, vals []time.Time, unused string) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - - for _, t := range vals { - dst = e.AppendTime(dst, t, unused) - } - return dst -} - -// AppendDuration encodes and adds a duration to the dst byte array. -// useInt field indicates whether to store the duration as seconds (integer) or -// as seconds+nanoseconds (float). -func (e Encoder) AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool, unused int) []byte { - if useInt { - return e.AppendInt64(dst, int64(d/unit)) - } - return e.AppendFloat64(dst, float64(d)/float64(unit), unused) -} - -// AppendDurations encodes and adds an array of durations to the dst byte array. -// useInt field indicates whether to store the duration as seconds (integer) or -// as seconds+nanoseconds (float). -func (e Encoder) AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool, unused int) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, d := range vals { - dst = e.AppendDuration(dst, d, unit, useInt, unused) - } - return dst -} diff --git a/vendor/github.com/rs/zerolog/internal/cbor/types.go b/vendor/github.com/rs/zerolog/internal/cbor/types.go deleted file mode 100644 index 454d68b..0000000 --- a/vendor/github.com/rs/zerolog/internal/cbor/types.go +++ /dev/null @@ -1,486 +0,0 @@ -package cbor - -import ( - "fmt" - "math" - "net" - "reflect" -) - -// AppendNil inserts a 'Nil' object into the dst byte array. -func (Encoder) AppendNil(dst []byte) []byte { - return append(dst, majorTypeSimpleAndFloat|additionalTypeNull) -} - -// AppendBeginMarker inserts a map start into the dst byte array. -func (Encoder) AppendBeginMarker(dst []byte) []byte { - return append(dst, majorTypeMap|additionalTypeInfiniteCount) -} - -// AppendEndMarker inserts a map end into the dst byte array. -func (Encoder) AppendEndMarker(dst []byte) []byte { - return append(dst, majorTypeSimpleAndFloat|additionalTypeBreak) -} - -// AppendObjectData takes an object in form of a byte array and appends to dst. -func (Encoder) AppendObjectData(dst []byte, o []byte) []byte { - // BeginMarker is present in the dst, which - // should not be copied when appending to existing data. - return append(dst, o[1:]...) -} - -// AppendArrayStart adds markers to indicate the start of an array. -func (Encoder) AppendArrayStart(dst []byte) []byte { - return append(dst, majorTypeArray|additionalTypeInfiniteCount) -} - -// AppendArrayEnd adds markers to indicate the end of an array. -func (Encoder) AppendArrayEnd(dst []byte) []byte { - return append(dst, majorTypeSimpleAndFloat|additionalTypeBreak) -} - -// AppendArrayDelim adds markers to indicate end of a particular array element. -func (Encoder) AppendArrayDelim(dst []byte) []byte { - //No delimiters needed in cbor - return dst -} - -// AppendLineBreak is a noop that keep API compat with json encoder. -func (Encoder) AppendLineBreak(dst []byte) []byte { - // No line breaks needed in binary format. - return dst -} - -// AppendBool encodes and inserts a boolean value into the dst byte array. -func (Encoder) AppendBool(dst []byte, val bool) []byte { - b := additionalTypeBoolFalse - if val { - b = additionalTypeBoolTrue - } - return append(dst, majorTypeSimpleAndFloat|b) -} - -// AppendBools encodes and inserts an array of boolean values into the dst byte array. -func (e Encoder) AppendBools(dst []byte, vals []bool) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendBool(dst, v) - } - return dst -} - -// AppendInt encodes and inserts an integer value into the dst byte array. -func (Encoder) AppendInt(dst []byte, val int) []byte { - major := majorTypeUnsignedInt - contentVal := val - if val < 0 { - major = majorTypeNegativeInt - contentVal = -val - 1 - } - if contentVal <= additionalMax { - lb := byte(contentVal) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(contentVal)) - } - return dst -} - -// AppendInts encodes and inserts an array of integer values into the dst byte array. -func (e Encoder) AppendInts(dst []byte, vals []int) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendInt(dst, v) - } - return dst -} - -// AppendInt8 encodes and inserts an int8 value into the dst byte array. -func (e Encoder) AppendInt8(dst []byte, val int8) []byte { - return e.AppendInt(dst, int(val)) -} - -// AppendInts8 encodes and inserts an array of integer values into the dst byte array. -func (e Encoder) AppendInts8(dst []byte, vals []int8) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendInt(dst, int(v)) - } - return dst -} - -// AppendInt16 encodes and inserts a int16 value into the dst byte array. -func (e Encoder) AppendInt16(dst []byte, val int16) []byte { - return e.AppendInt(dst, int(val)) -} - -// AppendInts16 encodes and inserts an array of int16 values into the dst byte array. -func (e Encoder) AppendInts16(dst []byte, vals []int16) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendInt(dst, int(v)) - } - return dst -} - -// AppendInt32 encodes and inserts a int32 value into the dst byte array. -func (e Encoder) AppendInt32(dst []byte, val int32) []byte { - return e.AppendInt(dst, int(val)) -} - -// AppendInts32 encodes and inserts an array of int32 values into the dst byte array. -func (e Encoder) AppendInts32(dst []byte, vals []int32) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendInt(dst, int(v)) - } - return dst -} - -// AppendInt64 encodes and inserts a int64 value into the dst byte array. -func (Encoder) AppendInt64(dst []byte, val int64) []byte { - major := majorTypeUnsignedInt - contentVal := val - if val < 0 { - major = majorTypeNegativeInt - contentVal = -val - 1 - } - if contentVal <= additionalMax { - lb := byte(contentVal) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(contentVal)) - } - return dst -} - -// AppendInts64 encodes and inserts an array of int64 values into the dst byte array. -func (e Encoder) AppendInts64(dst []byte, vals []int64) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendInt64(dst, v) - } - return dst -} - -// AppendUint encodes and inserts an unsigned integer value into the dst byte array. -func (e Encoder) AppendUint(dst []byte, val uint) []byte { - return e.AppendInt64(dst, int64(val)) -} - -// AppendUints encodes and inserts an array of unsigned integer values into the dst byte array. -func (e Encoder) AppendUints(dst []byte, vals []uint) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendUint(dst, v) - } - return dst -} - -// AppendUint8 encodes and inserts a unsigned int8 value into the dst byte array. -func (e Encoder) AppendUint8(dst []byte, val uint8) []byte { - return e.AppendUint(dst, uint(val)) -} - -// AppendUints8 encodes and inserts an array of uint8 values into the dst byte array. -func (e Encoder) AppendUints8(dst []byte, vals []uint8) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendUint8(dst, v) - } - return dst -} - -// AppendUint16 encodes and inserts a uint16 value into the dst byte array. -func (e Encoder) AppendUint16(dst []byte, val uint16) []byte { - return e.AppendUint(dst, uint(val)) -} - -// AppendUints16 encodes and inserts an array of uint16 values into the dst byte array. -func (e Encoder) AppendUints16(dst []byte, vals []uint16) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendUint16(dst, v) - } - return dst -} - -// AppendUint32 encodes and inserts a uint32 value into the dst byte array. -func (e Encoder) AppendUint32(dst []byte, val uint32) []byte { - return e.AppendUint(dst, uint(val)) -} - -// AppendUints32 encodes and inserts an array of uint32 values into the dst byte array. -func (e Encoder) AppendUints32(dst []byte, vals []uint32) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendUint32(dst, v) - } - return dst -} - -// AppendUint64 encodes and inserts a uint64 value into the dst byte array. -func (Encoder) AppendUint64(dst []byte, val uint64) []byte { - major := majorTypeUnsignedInt - contentVal := val - if contentVal <= additionalMax { - lb := byte(contentVal) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, contentVal) - } - return dst -} - -// AppendUints64 encodes and inserts an array of uint64 values into the dst byte array. -func (e Encoder) AppendUints64(dst []byte, vals []uint64) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendUint64(dst, v) - } - return dst -} - -// AppendFloat32 encodes and inserts a single precision float value into the dst byte array. -func (Encoder) AppendFloat32(dst []byte, val float32, unused int) []byte { - switch { - case math.IsNaN(float64(val)): - return append(dst, "\xfa\x7f\xc0\x00\x00"...) - case math.IsInf(float64(val), 1): - return append(dst, "\xfa\x7f\x80\x00\x00"...) - case math.IsInf(float64(val), -1): - return append(dst, "\xfa\xff\x80\x00\x00"...) - } - major := majorTypeSimpleAndFloat - subType := additionalTypeFloat32 - n := math.Float32bits(val) - var buf [4]byte - for i := uint(0); i < 4; i++ { - buf[i] = byte(n >> ((3 - i) * 8)) - } - return append(append(dst, major|subType), buf[0], buf[1], buf[2], buf[3]) -} - -// AppendFloats32 encodes and inserts an array of single precision float value into the dst byte array. -func (e Encoder) AppendFloats32(dst []byte, vals []float32, unused int) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendFloat32(dst, v, unused) - } - return dst -} - -// AppendFloat64 encodes and inserts a double precision float value into the dst byte array. -func (Encoder) AppendFloat64(dst []byte, val float64, unused int) []byte { - switch { - case math.IsNaN(val): - return append(dst, "\xfb\x7f\xf8\x00\x00\x00\x00\x00\x00"...) - case math.IsInf(val, 1): - return append(dst, "\xfb\x7f\xf0\x00\x00\x00\x00\x00\x00"...) - case math.IsInf(val, -1): - return append(dst, "\xfb\xff\xf0\x00\x00\x00\x00\x00\x00"...) - } - major := majorTypeSimpleAndFloat - subType := additionalTypeFloat64 - n := math.Float64bits(val) - dst = append(dst, major|subType) - for i := uint(1); i <= 8; i++ { - b := byte(n >> ((8 - i) * 8)) - dst = append(dst, b) - } - return dst -} - -// AppendFloats64 encodes and inserts an array of double precision float values into the dst byte array. -func (e Encoder) AppendFloats64(dst []byte, vals []float64, unused int) []byte { - major := majorTypeArray - l := len(vals) - if l == 0 { - return e.AppendArrayEnd(e.AppendArrayStart(dst)) - } - if l <= additionalMax { - lb := byte(l) - dst = append(dst, major|lb) - } else { - dst = appendCborTypePrefix(dst, major, uint64(l)) - } - for _, v := range vals { - dst = e.AppendFloat64(dst, v, unused) - } - return dst -} - -// AppendInterface takes an arbitrary object and converts it to JSON and embeds it dst. -func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte { - marshaled, err := JSONMarshalFunc(i) - if err != nil { - return e.AppendString(dst, fmt.Sprintf("marshaling error: %v", err)) - } - return AppendEmbeddedJSON(dst, marshaled) -} - -// AppendType appends the parameter type (as a string) to the input byte slice. -func (e Encoder) AppendType(dst []byte, i interface{}) []byte { - if i == nil { - return e.AppendString(dst, "") - } - return e.AppendString(dst, reflect.TypeOf(i).String()) -} - -// AppendIPAddr encodes and inserts an IP Address (IPv4 or IPv6). -func (e Encoder) AppendIPAddr(dst []byte, ip net.IP) []byte { - dst = append(dst, majorTypeTags|additionalTypeIntUint16) - dst = append(dst, byte(additionalTypeTagNetworkAddr>>8)) - dst = append(dst, byte(additionalTypeTagNetworkAddr&0xff)) - return e.AppendBytes(dst, ip) -} - -// AppendIPPrefix encodes and inserts an IP Address Prefix (Address + Mask Length). -func (e Encoder) AppendIPPrefix(dst []byte, pfx net.IPNet) []byte { - dst = append(dst, majorTypeTags|additionalTypeIntUint16) - dst = append(dst, byte(additionalTypeTagNetworkPrefix>>8)) - dst = append(dst, byte(additionalTypeTagNetworkPrefix&0xff)) - - // Prefix is a tuple (aka MAP of 1 pair of elements) - - // first element is prefix, second is mask length. - dst = append(dst, majorTypeMap|0x1) - dst = e.AppendBytes(dst, pfx.IP) - maskLen, _ := pfx.Mask.Size() - return e.AppendUint8(dst, uint8(maskLen)) -} - -// AppendMACAddr encodes and inserts a Hardware (MAC) address. -func (e Encoder) AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte { - dst = append(dst, majorTypeTags|additionalTypeIntUint16) - dst = append(dst, byte(additionalTypeTagNetworkAddr>>8)) - dst = append(dst, byte(additionalTypeTagNetworkAddr&0xff)) - return e.AppendBytes(dst, ha) -} - -// AppendHex adds a TAG and inserts a hex bytes as a string. -func (e Encoder) AppendHex(dst []byte, val []byte) []byte { - dst = append(dst, majorTypeTags|additionalTypeIntUint16) - dst = append(dst, byte(additionalTypeTagHexString>>8)) - dst = append(dst, byte(additionalTypeTagHexString&0xff)) - return e.AppendBytes(dst, val) -} diff --git a/vendor/github.com/rs/zerolog/internal/json/base.go b/vendor/github.com/rs/zerolog/internal/json/base.go deleted file mode 100644 index 09ec59f..0000000 --- a/vendor/github.com/rs/zerolog/internal/json/base.go +++ /dev/null @@ -1,19 +0,0 @@ -package json - -// JSONMarshalFunc is used to marshal interface to JSON encoded byte slice. -// Making it package level instead of embedded in Encoder brings -// some extra efforts at importing, but avoids value copy when the functions -// of Encoder being invoked. -// DO REMEMBER to set this variable at importing, or -// you might get a nil pointer dereference panic at runtime. -var JSONMarshalFunc func(v interface{}) ([]byte, error) - -type Encoder struct{} - -// AppendKey appends a new key to the output JSON. -func (e Encoder) AppendKey(dst []byte, key string) []byte { - if dst[len(dst)-1] != '{' { - dst = append(dst, ',') - } - return append(e.AppendString(dst, key), ':') -} diff --git a/vendor/github.com/rs/zerolog/internal/json/bytes.go b/vendor/github.com/rs/zerolog/internal/json/bytes.go deleted file mode 100644 index de64120..0000000 --- a/vendor/github.com/rs/zerolog/internal/json/bytes.go +++ /dev/null @@ -1,85 +0,0 @@ -package json - -import "unicode/utf8" - -// AppendBytes is a mirror of appendString with []byte arg -func (Encoder) AppendBytes(dst, s []byte) []byte { - dst = append(dst, '"') - for i := 0; i < len(s); i++ { - if !noEscapeTable[s[i]] { - dst = appendBytesComplex(dst, s, i) - return append(dst, '"') - } - } - dst = append(dst, s...) - return append(dst, '"') -} - -// AppendHex encodes the input bytes to a hex string and appends -// the encoded string to the input byte slice. -// -// The operation loops though each byte and encodes it as hex using -// the hex lookup table. -func (Encoder) AppendHex(dst, s []byte) []byte { - dst = append(dst, '"') - for _, v := range s { - dst = append(dst, hex[v>>4], hex[v&0x0f]) - } - return append(dst, '"') -} - -// appendBytesComplex is a mirror of the appendStringComplex -// with []byte arg -func appendBytesComplex(dst, s []byte, i int) []byte { - start := 0 - for i < len(s) { - b := s[i] - if b >= utf8.RuneSelf { - r, size := utf8.DecodeRune(s[i:]) - if r == utf8.RuneError && size == 1 { - if start < i { - dst = append(dst, s[start:i]...) - } - dst = append(dst, `\ufffd`...) - i += size - start = i - continue - } - i += size - continue - } - if noEscapeTable[b] { - i++ - continue - } - // We encountered a character that needs to be encoded. - // Let's append the previous simple characters to the byte slice - // and switch our operation to read and encode the remainder - // characters byte-by-byte. - if start < i { - dst = append(dst, s[start:i]...) - } - switch b { - case '"', '\\': - dst = append(dst, '\\', b) - case '\b': - dst = append(dst, '\\', 'b') - case '\f': - dst = append(dst, '\\', 'f') - case '\n': - dst = append(dst, '\\', 'n') - case '\r': - dst = append(dst, '\\', 'r') - case '\t': - dst = append(dst, '\\', 't') - default: - dst = append(dst, '\\', 'u', '0', '0', hex[b>>4], hex[b&0xF]) - } - i++ - start = i - } - if start < len(s) { - dst = append(dst, s[start:]...) - } - return dst -} diff --git a/vendor/github.com/rs/zerolog/internal/json/string.go b/vendor/github.com/rs/zerolog/internal/json/string.go deleted file mode 100644 index fd7770f..0000000 --- a/vendor/github.com/rs/zerolog/internal/json/string.go +++ /dev/null @@ -1,149 +0,0 @@ -package json - -import ( - "fmt" - "unicode/utf8" -) - -const hex = "0123456789abcdef" - -var noEscapeTable = [256]bool{} - -func init() { - for i := 0; i <= 0x7e; i++ { - noEscapeTable[i] = i >= 0x20 && i != '\\' && i != '"' - } -} - -// AppendStrings encodes the input strings to json and -// appends the encoded string list to the input byte slice. -func (e Encoder) AppendStrings(dst []byte, vals []string) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = e.AppendString(dst, vals[0]) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = e.AppendString(append(dst, ','), val) - } - } - dst = append(dst, ']') - return dst -} - -// AppendString encodes the input string to json and appends -// the encoded string to the input byte slice. -// -// The operation loops though each byte in the string looking -// for characters that need json or utf8 encoding. If the string -// does not need encoding, then the string is appended in its -// entirety to the byte slice. -// If we encounter a byte that does need encoding, switch up -// the operation and perform a byte-by-byte read-encode-append. -func (Encoder) AppendString(dst []byte, s string) []byte { - // Start with a double quote. - dst = append(dst, '"') - // Loop through each character in the string. - for i := 0; i < len(s); i++ { - // Check if the character needs encoding. Control characters, slashes, - // and the double quote need json encoding. Bytes above the ascii - // boundary needs utf8 encoding. - if !noEscapeTable[s[i]] { - // We encountered a character that needs to be encoded. Switch - // to complex version of the algorithm. - dst = appendStringComplex(dst, s, i) - return append(dst, '"') - } - } - // The string has no need for encoding and therefore is directly - // appended to the byte slice. - dst = append(dst, s...) - // End with a double quote - return append(dst, '"') -} - -// AppendStringers encodes the provided Stringer list to json and -// appends the encoded Stringer list to the input byte slice. -func (e Encoder) AppendStringers(dst []byte, vals []fmt.Stringer) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = e.AppendStringer(dst, vals[0]) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = e.AppendStringer(append(dst, ','), val) - } - } - return append(dst, ']') -} - -// AppendStringer encodes the input Stringer to json and appends the -// encoded Stringer value to the input byte slice. -func (e Encoder) AppendStringer(dst []byte, val fmt.Stringer) []byte { - if val == nil { - return e.AppendInterface(dst, nil) - } - return e.AppendString(dst, val.String()) -} - -//// appendStringComplex is used by appendString to take over an in -// progress JSON string encoding that encountered a character that needs -// to be encoded. -func appendStringComplex(dst []byte, s string, i int) []byte { - start := 0 - for i < len(s) { - b := s[i] - if b >= utf8.RuneSelf { - r, size := utf8.DecodeRuneInString(s[i:]) - if r == utf8.RuneError && size == 1 { - // In case of error, first append previous simple characters to - // the byte slice if any and append a replacement character code - // in place of the invalid sequence. - if start < i { - dst = append(dst, s[start:i]...) - } - dst = append(dst, `\ufffd`...) - i += size - start = i - continue - } - i += size - continue - } - if noEscapeTable[b] { - i++ - continue - } - // We encountered a character that needs to be encoded. - // Let's append the previous simple characters to the byte slice - // and switch our operation to read and encode the remainder - // characters byte-by-byte. - if start < i { - dst = append(dst, s[start:i]...) - } - switch b { - case '"', '\\': - dst = append(dst, '\\', b) - case '\b': - dst = append(dst, '\\', 'b') - case '\f': - dst = append(dst, '\\', 'f') - case '\n': - dst = append(dst, '\\', 'n') - case '\r': - dst = append(dst, '\\', 'r') - case '\t': - dst = append(dst, '\\', 't') - default: - dst = append(dst, '\\', 'u', '0', '0', hex[b>>4], hex[b&0xF]) - } - i++ - start = i - } - if start < len(s) { - dst = append(dst, s[start:]...) - } - return dst -} diff --git a/vendor/github.com/rs/zerolog/internal/json/time.go b/vendor/github.com/rs/zerolog/internal/json/time.go deleted file mode 100644 index 08cbbd9..0000000 --- a/vendor/github.com/rs/zerolog/internal/json/time.go +++ /dev/null @@ -1,113 +0,0 @@ -package json - -import ( - "strconv" - "time" -) - -const ( - // Import from zerolog/global.go - timeFormatUnix = "" - timeFormatUnixMs = "UNIXMS" - timeFormatUnixMicro = "UNIXMICRO" - timeFormatUnixNano = "UNIXNANO" -) - -// AppendTime formats the input time with the given format -// and appends the encoded string to the input byte slice. -func (e Encoder) AppendTime(dst []byte, t time.Time, format string) []byte { - switch format { - case timeFormatUnix: - return e.AppendInt64(dst, t.Unix()) - case timeFormatUnixMs: - return e.AppendInt64(dst, t.UnixNano()/1000000) - case timeFormatUnixMicro: - return e.AppendInt64(dst, t.UnixNano()/1000) - case timeFormatUnixNano: - return e.AppendInt64(dst, t.UnixNano()) - } - return append(t.AppendFormat(append(dst, '"'), format), '"') -} - -// AppendTimes converts the input times with the given format -// and appends the encoded string list to the input byte slice. -func (Encoder) AppendTimes(dst []byte, vals []time.Time, format string) []byte { - switch format { - case timeFormatUnix: - return appendUnixTimes(dst, vals) - case timeFormatUnixMs: - return appendUnixNanoTimes(dst, vals, 1000000) - case timeFormatUnixMicro: - return appendUnixNanoTimes(dst, vals, 1000) - case timeFormatUnixNano: - return appendUnixNanoTimes(dst, vals, 1) - } - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = append(vals[0].AppendFormat(append(dst, '"'), format), '"') - if len(vals) > 1 { - for _, t := range vals[1:] { - dst = append(t.AppendFormat(append(dst, ',', '"'), format), '"') - } - } - dst = append(dst, ']') - return dst -} - -func appendUnixTimes(dst []byte, vals []time.Time) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = strconv.AppendInt(dst, vals[0].Unix(), 10) - if len(vals) > 1 { - for _, t := range vals[1:] { - dst = strconv.AppendInt(append(dst, ','), t.Unix(), 10) - } - } - dst = append(dst, ']') - return dst -} - -func appendUnixNanoTimes(dst []byte, vals []time.Time, div int64) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = strconv.AppendInt(dst, vals[0].UnixNano()/div, 10) - if len(vals) > 1 { - for _, t := range vals[1:] { - dst = strconv.AppendInt(append(dst, ','), t.UnixNano()/div, 10) - } - } - dst = append(dst, ']') - return dst -} - -// AppendDuration formats the input duration with the given unit & format -// and appends the encoded string to the input byte slice. -func (e Encoder) AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool, precision int) []byte { - if useInt { - return strconv.AppendInt(dst, int64(d/unit), 10) - } - return e.AppendFloat64(dst, float64(d)/float64(unit), precision) -} - -// AppendDurations formats the input durations with the given unit & format -// and appends the encoded string list to the input byte slice. -func (e Encoder) AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool, precision int) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = e.AppendDuration(dst, vals[0], unit, useInt, precision) - if len(vals) > 1 { - for _, d := range vals[1:] { - dst = e.AppendDuration(append(dst, ','), d, unit, useInt, precision) - } - } - dst = append(dst, ']') - return dst -} diff --git a/vendor/github.com/rs/zerolog/internal/json/types.go b/vendor/github.com/rs/zerolog/internal/json/types.go deleted file mode 100644 index 7930491..0000000 --- a/vendor/github.com/rs/zerolog/internal/json/types.go +++ /dev/null @@ -1,435 +0,0 @@ -package json - -import ( - "fmt" - "math" - "net" - "reflect" - "strconv" -) - -// AppendNil inserts a 'Nil' object into the dst byte array. -func (Encoder) AppendNil(dst []byte) []byte { - return append(dst, "null"...) -} - -// AppendBeginMarker inserts a map start into the dst byte array. -func (Encoder) AppendBeginMarker(dst []byte) []byte { - return append(dst, '{') -} - -// AppendEndMarker inserts a map end into the dst byte array. -func (Encoder) AppendEndMarker(dst []byte) []byte { - return append(dst, '}') -} - -// AppendLineBreak appends a line break. -func (Encoder) AppendLineBreak(dst []byte) []byte { - return append(dst, '\n') -} - -// AppendArrayStart adds markers to indicate the start of an array. -func (Encoder) AppendArrayStart(dst []byte) []byte { - return append(dst, '[') -} - -// AppendArrayEnd adds markers to indicate the end of an array. -func (Encoder) AppendArrayEnd(dst []byte) []byte { - return append(dst, ']') -} - -// AppendArrayDelim adds markers to indicate end of a particular array element. -func (Encoder) AppendArrayDelim(dst []byte) []byte { - if len(dst) > 0 { - return append(dst, ',') - } - return dst -} - -// AppendBool converts the input bool to a string and -// appends the encoded string to the input byte slice. -func (Encoder) AppendBool(dst []byte, val bool) []byte { - return strconv.AppendBool(dst, val) -} - -// AppendBools encodes the input bools to json and -// appends the encoded string list to the input byte slice. -func (Encoder) AppendBools(dst []byte, vals []bool) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = strconv.AppendBool(dst, vals[0]) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = strconv.AppendBool(append(dst, ','), val) - } - } - dst = append(dst, ']') - return dst -} - -// AppendInt converts the input int to a string and -// appends the encoded string to the input byte slice. -func (Encoder) AppendInt(dst []byte, val int) []byte { - return strconv.AppendInt(dst, int64(val), 10) -} - -// AppendInts encodes the input ints to json and -// appends the encoded string list to the input byte slice. -func (Encoder) AppendInts(dst []byte, vals []int) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = strconv.AppendInt(dst, int64(vals[0]), 10) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = strconv.AppendInt(append(dst, ','), int64(val), 10) - } - } - dst = append(dst, ']') - return dst -} - -// AppendInt8 converts the input []int8 to a string and -// appends the encoded string to the input byte slice. -func (Encoder) AppendInt8(dst []byte, val int8) []byte { - return strconv.AppendInt(dst, int64(val), 10) -} - -// AppendInts8 encodes the input int8s to json and -// appends the encoded string list to the input byte slice. -func (Encoder) AppendInts8(dst []byte, vals []int8) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = strconv.AppendInt(dst, int64(vals[0]), 10) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = strconv.AppendInt(append(dst, ','), int64(val), 10) - } - } - dst = append(dst, ']') - return dst -} - -// AppendInt16 converts the input int16 to a string and -// appends the encoded string to the input byte slice. -func (Encoder) AppendInt16(dst []byte, val int16) []byte { - return strconv.AppendInt(dst, int64(val), 10) -} - -// AppendInts16 encodes the input int16s to json and -// appends the encoded string list to the input byte slice. -func (Encoder) AppendInts16(dst []byte, vals []int16) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = strconv.AppendInt(dst, int64(vals[0]), 10) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = strconv.AppendInt(append(dst, ','), int64(val), 10) - } - } - dst = append(dst, ']') - return dst -} - -// AppendInt32 converts the input int32 to a string and -// appends the encoded string to the input byte slice. -func (Encoder) AppendInt32(dst []byte, val int32) []byte { - return strconv.AppendInt(dst, int64(val), 10) -} - -// AppendInts32 encodes the input int32s to json and -// appends the encoded string list to the input byte slice. -func (Encoder) AppendInts32(dst []byte, vals []int32) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = strconv.AppendInt(dst, int64(vals[0]), 10) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = strconv.AppendInt(append(dst, ','), int64(val), 10) - } - } - dst = append(dst, ']') - return dst -} - -// AppendInt64 converts the input int64 to a string and -// appends the encoded string to the input byte slice. -func (Encoder) AppendInt64(dst []byte, val int64) []byte { - return strconv.AppendInt(dst, val, 10) -} - -// AppendInts64 encodes the input int64s to json and -// appends the encoded string list to the input byte slice. -func (Encoder) AppendInts64(dst []byte, vals []int64) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = strconv.AppendInt(dst, vals[0], 10) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = strconv.AppendInt(append(dst, ','), val, 10) - } - } - dst = append(dst, ']') - return dst -} - -// AppendUint converts the input uint to a string and -// appends the encoded string to the input byte slice. -func (Encoder) AppendUint(dst []byte, val uint) []byte { - return strconv.AppendUint(dst, uint64(val), 10) -} - -// AppendUints encodes the input uints to json and -// appends the encoded string list to the input byte slice. -func (Encoder) AppendUints(dst []byte, vals []uint) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = strconv.AppendUint(dst, uint64(vals[0]), 10) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = strconv.AppendUint(append(dst, ','), uint64(val), 10) - } - } - dst = append(dst, ']') - return dst -} - -// AppendUint8 converts the input uint8 to a string and -// appends the encoded string to the input byte slice. -func (Encoder) AppendUint8(dst []byte, val uint8) []byte { - return strconv.AppendUint(dst, uint64(val), 10) -} - -// AppendUints8 encodes the input uint8s to json and -// appends the encoded string list to the input byte slice. -func (Encoder) AppendUints8(dst []byte, vals []uint8) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = strconv.AppendUint(dst, uint64(vals[0]), 10) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = strconv.AppendUint(append(dst, ','), uint64(val), 10) - } - } - dst = append(dst, ']') - return dst -} - -// AppendUint16 converts the input uint16 to a string and -// appends the encoded string to the input byte slice. -func (Encoder) AppendUint16(dst []byte, val uint16) []byte { - return strconv.AppendUint(dst, uint64(val), 10) -} - -// AppendUints16 encodes the input uint16s to json and -// appends the encoded string list to the input byte slice. -func (Encoder) AppendUints16(dst []byte, vals []uint16) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = strconv.AppendUint(dst, uint64(vals[0]), 10) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = strconv.AppendUint(append(dst, ','), uint64(val), 10) - } - } - dst = append(dst, ']') - return dst -} - -// AppendUint32 converts the input uint32 to a string and -// appends the encoded string to the input byte slice. -func (Encoder) AppendUint32(dst []byte, val uint32) []byte { - return strconv.AppendUint(dst, uint64(val), 10) -} - -// AppendUints32 encodes the input uint32s to json and -// appends the encoded string list to the input byte slice. -func (Encoder) AppendUints32(dst []byte, vals []uint32) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = strconv.AppendUint(dst, uint64(vals[0]), 10) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = strconv.AppendUint(append(dst, ','), uint64(val), 10) - } - } - dst = append(dst, ']') - return dst -} - -// AppendUint64 converts the input uint64 to a string and -// appends the encoded string to the input byte slice. -func (Encoder) AppendUint64(dst []byte, val uint64) []byte { - return strconv.AppendUint(dst, val, 10) -} - -// AppendUints64 encodes the input uint64s to json and -// appends the encoded string list to the input byte slice. -func (Encoder) AppendUints64(dst []byte, vals []uint64) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = strconv.AppendUint(dst, vals[0], 10) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = strconv.AppendUint(append(dst, ','), val, 10) - } - } - dst = append(dst, ']') - return dst -} - -func appendFloat(dst []byte, val float64, bitSize, precision int) []byte { - // JSON does not permit NaN or Infinity. A typical JSON encoder would fail - // with an error, but a logging library wants the data to get through so we - // make a tradeoff and store those types as string. - switch { - case math.IsNaN(val): - return append(dst, `"NaN"`...) - case math.IsInf(val, 1): - return append(dst, `"+Inf"`...) - case math.IsInf(val, -1): - return append(dst, `"-Inf"`...) - } - // convert as if by es6 number to string conversion - // see also https://cs.opensource.google/go/go/+/refs/tags/go1.20.3:src/encoding/json/encode.go;l=573 - strFmt := byte('f') - // If precision is set to a value other than -1, we always just format the float using that precision. - if precision == -1 { - // Use float32 comparisons for underlying float32 value to get precise cutoffs right. - if abs := math.Abs(val); abs != 0 { - if bitSize == 64 && (abs < 1e-6 || abs >= 1e21) || bitSize == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) { - strFmt = 'e' - } - } - } - dst = strconv.AppendFloat(dst, val, strFmt, precision, bitSize) - if strFmt == 'e' { - // Clean up e-09 to e-9 - n := len(dst) - if n >= 4 && dst[n-4] == 'e' && dst[n-3] == '-' && dst[n-2] == '0' { - dst[n-2] = dst[n-1] - dst = dst[:n-1] - } - } - return dst -} - -// AppendFloat32 converts the input float32 to a string and -// appends the encoded string to the input byte slice. -func (Encoder) AppendFloat32(dst []byte, val float32, precision int) []byte { - return appendFloat(dst, float64(val), 32, precision) -} - -// AppendFloats32 encodes the input float32s to json and -// appends the encoded string list to the input byte slice. -func (Encoder) AppendFloats32(dst []byte, vals []float32, precision int) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = appendFloat(dst, float64(vals[0]), 32, precision) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = appendFloat(append(dst, ','), float64(val), 32, precision) - } - } - dst = append(dst, ']') - return dst -} - -// AppendFloat64 converts the input float64 to a string and -// appends the encoded string to the input byte slice. -func (Encoder) AppendFloat64(dst []byte, val float64, precision int) []byte { - return appendFloat(dst, val, 64, precision) -} - -// AppendFloats64 encodes the input float64s to json and -// appends the encoded string list to the input byte slice. -func (Encoder) AppendFloats64(dst []byte, vals []float64, precision int) []byte { - if len(vals) == 0 { - return append(dst, '[', ']') - } - dst = append(dst, '[') - dst = appendFloat(dst, vals[0], 64, precision) - if len(vals) > 1 { - for _, val := range vals[1:] { - dst = appendFloat(append(dst, ','), val, 64, precision) - } - } - dst = append(dst, ']') - return dst -} - -// AppendInterface marshals the input interface to a string and -// appends the encoded string to the input byte slice. -func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte { - marshaled, err := JSONMarshalFunc(i) - if err != nil { - return e.AppendString(dst, fmt.Sprintf("marshaling error: %v", err)) - } - return append(dst, marshaled...) -} - -// AppendType appends the parameter type (as a string) to the input byte slice. -func (e Encoder) AppendType(dst []byte, i interface{}) []byte { - if i == nil { - return e.AppendString(dst, "") - } - return e.AppendString(dst, reflect.TypeOf(i).String()) -} - -// AppendObjectData takes in an object that is already in a byte array -// and adds it to the dst. -func (Encoder) AppendObjectData(dst []byte, o []byte) []byte { - // Three conditions apply here: - // 1. new content starts with '{' - which should be dropped OR - // 2. new content starts with '{' - which should be replaced with ',' - // to separate with existing content OR - // 3. existing content has already other fields - if o[0] == '{' { - if len(dst) > 1 { - dst = append(dst, ',') - } - o = o[1:] - } else if len(dst) > 1 { - dst = append(dst, ',') - } - return append(dst, o...) -} - -// AppendIPAddr adds IPv4 or IPv6 address to dst. -func (e Encoder) AppendIPAddr(dst []byte, ip net.IP) []byte { - return e.AppendString(dst, ip.String()) -} - -// AppendIPPrefix adds IPv4 or IPv6 Prefix (address & mask) to dst. -func (e Encoder) AppendIPPrefix(dst []byte, pfx net.IPNet) []byte { - return e.AppendString(dst, pfx.String()) - -} - -// AppendMACAddr adds MAC address to dst. -func (e Encoder) AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte { - return e.AppendString(dst, ha.String()) -} diff --git a/vendor/github.com/rs/zerolog/log.go b/vendor/github.com/rs/zerolog/log.go deleted file mode 100644 index 6c1d4ea..0000000 --- a/vendor/github.com/rs/zerolog/log.go +++ /dev/null @@ -1,518 +0,0 @@ -// Package zerolog provides a lightweight logging library dedicated to JSON logging. -// -// A global Logger can be use for simple logging: -// -// import "github.com/rs/zerolog/log" -// -// log.Info().Msg("hello world") -// // Output: {"time":1494567715,"level":"info","message":"hello world"} -// -// NOTE: To import the global logger, import the "log" subpackage "github.com/rs/zerolog/log". -// -// Fields can be added to log messages: -// -// log.Info().Str("foo", "bar").Msg("hello world") -// // Output: {"time":1494567715,"level":"info","message":"hello world","foo":"bar"} -// -// Create logger instance to manage different outputs: -// -// logger := zerolog.New(os.Stderr).With().Timestamp().Logger() -// logger.Info(). -// Str("foo", "bar"). -// Msg("hello world") -// // Output: {"time":1494567715,"level":"info","message":"hello world","foo":"bar"} -// -// Sub-loggers let you chain loggers with additional context: -// -// sublogger := log.With().Str("component", "foo").Logger() -// sublogger.Info().Msg("hello world") -// // Output: {"time":1494567715,"level":"info","message":"hello world","component":"foo"} -// -// Level logging -// -// zerolog.SetGlobalLevel(zerolog.InfoLevel) -// -// log.Debug().Msg("filtered out message") -// log.Info().Msg("routed message") -// -// if e := log.Debug(); e.Enabled() { -// // Compute log output only if enabled. -// value := compute() -// e.Str("foo": value).Msg("some debug message") -// } -// // Output: {"level":"info","time":1494567715,"routed message"} -// -// Customize automatic field names: -// -// log.TimestampFieldName = "t" -// log.LevelFieldName = "p" -// log.MessageFieldName = "m" -// -// log.Info().Msg("hello world") -// // Output: {"t":1494567715,"p":"info","m":"hello world"} -// -// Log with no level and message: -// -// log.Log().Str("foo","bar").Msg("") -// // Output: {"time":1494567715,"foo":"bar"} -// -// Add contextual fields to global Logger: -// -// log.Logger = log.With().Str("foo", "bar").Logger() -// -// Sample logs: -// -// sampled := log.Sample(&zerolog.BasicSampler{N: 10}) -// sampled.Info().Msg("will be logged every 10 messages") -// -// Log with contextual hooks: -// -// // Create the hook: -// type SeverityHook struct{} -// -// func (h SeverityHook) Run(e *zerolog.Event, level zerolog.Level, msg string) { -// if level != zerolog.NoLevel { -// e.Str("severity", level.String()) -// } -// } -// -// // And use it: -// var h SeverityHook -// log := zerolog.New(os.Stdout).Hook(h) -// log.Warn().Msg("") -// // Output: {"level":"warn","severity":"warn"} -// -// # Caveats -// -// Field duplication: -// -// There is no fields deduplication out-of-the-box. -// Using the same key multiple times creates new key in final JSON each time. -// -// logger := zerolog.New(os.Stderr).With().Timestamp().Logger() -// logger.Info(). -// Timestamp(). -// Msg("dup") -// // Output: {"level":"info","time":1494567715,"time":1494567715,"message":"dup"} -// -// In this case, many consumers will take the last value, -// but this is not guaranteed; check yours if in doubt. -// -// Concurrency safety: -// -// Be careful when calling UpdateContext. It is not concurrency safe. Use the With method to create a child logger: -// -// func handler(w http.ResponseWriter, r *http.Request) { -// // Create a child logger for concurrency safety -// logger := log.Logger.With().Logger() -// -// // Add context fields, for example User-Agent from HTTP headers -// logger.UpdateContext(func(c zerolog.Context) zerolog.Context { -// ... -// }) -// } -package zerolog - -import ( - "context" - "errors" - "fmt" - "io" - "os" - "strconv" - "strings" -) - -// Level defines log levels. -type Level int8 - -const ( - // DebugLevel defines debug log level. - DebugLevel Level = iota - // InfoLevel defines info log level. - InfoLevel - // WarnLevel defines warn log level. - WarnLevel - // ErrorLevel defines error log level. - ErrorLevel - // FatalLevel defines fatal log level. - FatalLevel - // PanicLevel defines panic log level. - PanicLevel - // NoLevel defines an absent log level. - NoLevel - // Disabled disables the logger. - Disabled - - // TraceLevel defines trace log level. - TraceLevel Level = -1 - // Values less than TraceLevel are handled as numbers. -) - -func (l Level) String() string { - switch l { - case TraceLevel: - return LevelTraceValue - case DebugLevel: - return LevelDebugValue - case InfoLevel: - return LevelInfoValue - case WarnLevel: - return LevelWarnValue - case ErrorLevel: - return LevelErrorValue - case FatalLevel: - return LevelFatalValue - case PanicLevel: - return LevelPanicValue - case Disabled: - return "disabled" - case NoLevel: - return "" - } - return strconv.Itoa(int(l)) -} - -// ParseLevel converts a level string into a zerolog Level value. -// returns an error if the input string does not match known values. -func ParseLevel(levelStr string) (Level, error) { - switch { - case strings.EqualFold(levelStr, LevelFieldMarshalFunc(TraceLevel)): - return TraceLevel, nil - case strings.EqualFold(levelStr, LevelFieldMarshalFunc(DebugLevel)): - return DebugLevel, nil - case strings.EqualFold(levelStr, LevelFieldMarshalFunc(InfoLevel)): - return InfoLevel, nil - case strings.EqualFold(levelStr, LevelFieldMarshalFunc(WarnLevel)): - return WarnLevel, nil - case strings.EqualFold(levelStr, LevelFieldMarshalFunc(ErrorLevel)): - return ErrorLevel, nil - case strings.EqualFold(levelStr, LevelFieldMarshalFunc(FatalLevel)): - return FatalLevel, nil - case strings.EqualFold(levelStr, LevelFieldMarshalFunc(PanicLevel)): - return PanicLevel, nil - case strings.EqualFold(levelStr, LevelFieldMarshalFunc(Disabled)): - return Disabled, nil - case strings.EqualFold(levelStr, LevelFieldMarshalFunc(NoLevel)): - return NoLevel, nil - } - i, err := strconv.Atoi(levelStr) - if err != nil { - return NoLevel, fmt.Errorf("Unknown Level String: '%s', defaulting to NoLevel", levelStr) - } - if i > 127 || i < -128 { - return NoLevel, fmt.Errorf("Out-Of-Bounds Level: '%d', defaulting to NoLevel", i) - } - return Level(i), nil -} - -// UnmarshalText implements encoding.TextUnmarshaler to allow for easy reading from toml/yaml/json formats -func (l *Level) UnmarshalText(text []byte) error { - if l == nil { - return errors.New("can't unmarshal a nil *Level") - } - var err error - *l, err = ParseLevel(string(text)) - return err -} - -// MarshalText implements encoding.TextMarshaler to allow for easy writing into toml/yaml/json formats -func (l Level) MarshalText() ([]byte, error) { - return []byte(LevelFieldMarshalFunc(l)), nil -} - -// A Logger represents an active logging object that generates lines -// of JSON output to an io.Writer. Each logging operation makes a single -// call to the Writer's Write method. There is no guarantee on access -// serialization to the Writer. If your Writer is not thread safe, -// you may consider a sync wrapper. -type Logger struct { - w LevelWriter - level Level - sampler Sampler - context []byte - hooks []Hook - stack bool - ctx context.Context -} - -// New creates a root logger with given output writer. If the output writer implements -// the LevelWriter interface, the WriteLevel method will be called instead of the Write -// one. -// -// Each logging operation makes a single call to the Writer's Write method. There is no -// guarantee on access serialization to the Writer. If your Writer is not thread safe, -// you may consider using sync wrapper. -func New(w io.Writer) Logger { - if w == nil { - w = io.Discard - } - lw, ok := w.(LevelWriter) - if !ok { - lw = LevelWriterAdapter{w} - } - return Logger{w: lw, level: TraceLevel} -} - -// Nop returns a disabled logger for which all operation are no-op. -func Nop() Logger { - return New(nil).Level(Disabled) -} - -// Output duplicates the current logger and sets w as its output. -func (l Logger) Output(w io.Writer) Logger { - l2 := New(w) - l2.level = l.level - l2.sampler = l.sampler - l2.stack = l.stack - if len(l.hooks) > 0 { - l2.hooks = append(l2.hooks, l.hooks...) - } - if l.context != nil { - l2.context = make([]byte, len(l.context), cap(l.context)) - copy(l2.context, l.context) - } - return l2 -} - -// With creates a child logger with the field added to its context. -func (l Logger) With() Context { - context := l.context - l.context = make([]byte, 0, 500) - if context != nil { - l.context = append(l.context, context...) - } else { - // This is needed for AppendKey to not check len of input - // thus making it inlinable - l.context = enc.AppendBeginMarker(l.context) - } - return Context{l} -} - -// UpdateContext updates the internal logger's context. -// -// Caution: This method is not concurrency safe. -// Use the With method to create a child logger before modifying the context from concurrent goroutines. -func (l *Logger) UpdateContext(update func(c Context) Context) { - if l == disabledLogger { - return - } - if cap(l.context) == 0 { - l.context = make([]byte, 0, 500) - } - if len(l.context) == 0 { - l.context = enc.AppendBeginMarker(l.context) - } - c := update(Context{*l}) - l.context = c.l.context -} - -// Level creates a child logger with the minimum accepted level set to level. -func (l Logger) Level(lvl Level) Logger { - l.level = lvl - return l -} - -// GetLevel returns the current Level of l. -func (l Logger) GetLevel() Level { - return l.level -} - -// Sample returns a logger with the s sampler. -func (l Logger) Sample(s Sampler) Logger { - l.sampler = s - return l -} - -// Hook returns a logger with the h Hook. -func (l Logger) Hook(hooks ...Hook) Logger { - if len(hooks) == 0 { - return l - } - newHooks := make([]Hook, len(l.hooks), len(l.hooks)+len(hooks)) - copy(newHooks, l.hooks) - l.hooks = append(newHooks, hooks...) - return l -} - -// Trace starts a new message with trace level. -// -// You must call Msg on the returned event in order to send the event. -func (l *Logger) Trace() *Event { - return l.newEvent(TraceLevel, nil) -} - -// Debug starts a new message with debug level. -// -// You must call Msg on the returned event in order to send the event. -func (l *Logger) Debug() *Event { - return l.newEvent(DebugLevel, nil) -} - -// Info starts a new message with info level. -// -// You must call Msg on the returned event in order to send the event. -func (l *Logger) Info() *Event { - return l.newEvent(InfoLevel, nil) -} - -// Warn starts a new message with warn level. -// -// You must call Msg on the returned event in order to send the event. -func (l *Logger) Warn() *Event { - return l.newEvent(WarnLevel, nil) -} - -// Error starts a new message with error level. -// -// You must call Msg on the returned event in order to send the event. -func (l *Logger) Error() *Event { - return l.newEvent(ErrorLevel, nil) -} - -// Err starts a new message with error level with err as a field if not nil or -// with info level if err is nil. -// -// You must call Msg on the returned event in order to send the event. -func (l *Logger) Err(err error) *Event { - if err != nil { - return l.Error().Err(err) - } - - return l.Info() -} - -// Fatal starts a new message with fatal level. The os.Exit(1) function -// is called by the Msg method, which terminates the program immediately. -// -// You must call Msg on the returned event in order to send the event. -func (l *Logger) Fatal() *Event { - return l.newEvent(FatalLevel, func(msg string) { - if closer, ok := l.w.(io.Closer); ok { - // Close the writer to flush any buffered message. Otherwise the message - // will be lost as os.Exit() terminates the program immediately. - closer.Close() - } - os.Exit(1) - }) -} - -// Panic starts a new message with panic level. The panic() function -// is called by the Msg method, which stops the ordinary flow of a goroutine. -// -// You must call Msg on the returned event in order to send the event. -func (l *Logger) Panic() *Event { - return l.newEvent(PanicLevel, func(msg string) { panic(msg) }) -} - -// WithLevel starts a new message with level. Unlike Fatal and Panic -// methods, WithLevel does not terminate the program or stop the ordinary -// flow of a goroutine when used with their respective levels. -// -// You must call Msg on the returned event in order to send the event. -func (l *Logger) WithLevel(level Level) *Event { - switch level { - case TraceLevel: - return l.Trace() - case DebugLevel: - return l.Debug() - case InfoLevel: - return l.Info() - case WarnLevel: - return l.Warn() - case ErrorLevel: - return l.Error() - case FatalLevel: - return l.newEvent(FatalLevel, nil) - case PanicLevel: - return l.newEvent(PanicLevel, nil) - case NoLevel: - return l.Log() - case Disabled: - return nil - default: - return l.newEvent(level, nil) - } -} - -// Log starts a new message with no level. Setting GlobalLevel to Disabled -// will still disable events produced by this method. -// -// You must call Msg on the returned event in order to send the event. -func (l *Logger) Log() *Event { - return l.newEvent(NoLevel, nil) -} - -// Print sends a log event using debug level and no extra field. -// Arguments are handled in the manner of fmt.Print. -func (l *Logger) Print(v ...interface{}) { - if e := l.Debug(); e.Enabled() { - e.CallerSkipFrame(1).Msg(fmt.Sprint(v...)) - } -} - -// Printf sends a log event using debug level and no extra field. -// Arguments are handled in the manner of fmt.Printf. -func (l *Logger) Printf(format string, v ...interface{}) { - if e := l.Debug(); e.Enabled() { - e.CallerSkipFrame(1).Msg(fmt.Sprintf(format, v...)) - } -} - -// Println sends a log event using debug level and no extra field. -// Arguments are handled in the manner of fmt.Println. -func (l *Logger) Println(v ...interface{}) { - if e := l.Debug(); e.Enabled() { - e.CallerSkipFrame(1).Msg(fmt.Sprintln(v...)) - } -} - -// Write implements the io.Writer interface. This is useful to set as a writer -// for the standard library log. -func (l Logger) Write(p []byte) (n int, err error) { - n = len(p) - if n > 0 && p[n-1] == '\n' { - // Trim CR added by stdlog. - p = p[0 : n-1] - } - l.Log().CallerSkipFrame(1).Msg(string(p)) - return -} - -func (l *Logger) newEvent(level Level, done func(string)) *Event { - enabled := l.should(level) - if !enabled { - if done != nil { - done("") - } - return nil - } - e := newEvent(l.w, level) - e.done = done - e.ch = l.hooks - e.ctx = l.ctx - if level != NoLevel && LevelFieldName != "" { - e.Str(LevelFieldName, LevelFieldMarshalFunc(level)) - } - if l.context != nil && len(l.context) > 1 { - e.buf = enc.AppendObjectData(e.buf, l.context) - } - if l.stack { - e.Stack() - } - return e -} - -// should returns true if the log event should be logged. -func (l *Logger) should(lvl Level) bool { - if l.w == nil { - return false - } - if lvl < l.level || lvl < GlobalLevel() { - return false - } - if l.sampler != nil && !samplingDisabled() { - return l.sampler.Sample(lvl) - } - return true -} diff --git a/vendor/github.com/rs/zerolog/log/log.go b/vendor/github.com/rs/zerolog/log/log.go deleted file mode 100644 index a96ec50..0000000 --- a/vendor/github.com/rs/zerolog/log/log.go +++ /dev/null @@ -1,131 +0,0 @@ -// Package log provides a global logger for zerolog. -package log - -import ( - "context" - "fmt" - "io" - "os" - - "github.com/rs/zerolog" -) - -// Logger is the global logger. -var Logger = zerolog.New(os.Stderr).With().Timestamp().Logger() - -// Output duplicates the global logger and sets w as its output. -func Output(w io.Writer) zerolog.Logger { - return Logger.Output(w) -} - -// With creates a child logger with the field added to its context. -func With() zerolog.Context { - return Logger.With() -} - -// Level creates a child logger with the minimum accepted level set to level. -func Level(level zerolog.Level) zerolog.Logger { - return Logger.Level(level) -} - -// Sample returns a logger with the s sampler. -func Sample(s zerolog.Sampler) zerolog.Logger { - return Logger.Sample(s) -} - -// Hook returns a logger with the h Hook. -func Hook(h zerolog.Hook) zerolog.Logger { - return Logger.Hook(h) -} - -// Err starts a new message with error level with err as a field if not nil or -// with info level if err is nil. -// -// You must call Msg on the returned event in order to send the event. -func Err(err error) *zerolog.Event { - return Logger.Err(err) -} - -// Trace starts a new message with trace level. -// -// You must call Msg on the returned event in order to send the event. -func Trace() *zerolog.Event { - return Logger.Trace() -} - -// Debug starts a new message with debug level. -// -// You must call Msg on the returned event in order to send the event. -func Debug() *zerolog.Event { - return Logger.Debug() -} - -// Info starts a new message with info level. -// -// You must call Msg on the returned event in order to send the event. -func Info() *zerolog.Event { - return Logger.Info() -} - -// Warn starts a new message with warn level. -// -// You must call Msg on the returned event in order to send the event. -func Warn() *zerolog.Event { - return Logger.Warn() -} - -// Error starts a new message with error level. -// -// You must call Msg on the returned event in order to send the event. -func Error() *zerolog.Event { - return Logger.Error() -} - -// Fatal starts a new message with fatal level. The os.Exit(1) function -// is called by the Msg method. -// -// You must call Msg on the returned event in order to send the event. -func Fatal() *zerolog.Event { - return Logger.Fatal() -} - -// Panic starts a new message with panic level. The message is also sent -// to the panic function. -// -// You must call Msg on the returned event in order to send the event. -func Panic() *zerolog.Event { - return Logger.Panic() -} - -// WithLevel starts a new message with level. -// -// You must call Msg on the returned event in order to send the event. -func WithLevel(level zerolog.Level) *zerolog.Event { - return Logger.WithLevel(level) -} - -// Log starts a new message with no level. Setting zerolog.GlobalLevel to -// zerolog.Disabled will still disable events produced by this method. -// -// You must call Msg on the returned event in order to send the event. -func Log() *zerolog.Event { - return Logger.Log() -} - -// Print sends a log event using debug level and no extra field. -// Arguments are handled in the manner of fmt.Print. -func Print(v ...interface{}) { - Logger.Debug().CallerSkipFrame(1).Msg(fmt.Sprint(v...)) -} - -// Printf sends a log event using debug level and no extra field. -// Arguments are handled in the manner of fmt.Printf. -func Printf(format string, v ...interface{}) { - Logger.Debug().CallerSkipFrame(1).Msgf(format, v...) -} - -// Ctx returns the Logger associated with the ctx. If no logger -// is associated, a disabled logger is returned. -func Ctx(ctx context.Context) *zerolog.Logger { - return zerolog.Ctx(ctx) -} diff --git a/vendor/github.com/rs/zerolog/not_go112.go b/vendor/github.com/rs/zerolog/not_go112.go deleted file mode 100644 index 4c43c9e..0000000 --- a/vendor/github.com/rs/zerolog/not_go112.go +++ /dev/null @@ -1,5 +0,0 @@ -// +build !go1.12 - -package zerolog - -const contextCallerSkipFrameCount = 3 diff --git a/vendor/github.com/rs/zerolog/pkgerrors/stacktrace.go b/vendor/github.com/rs/zerolog/pkgerrors/stacktrace.go deleted file mode 100644 index 2f62ffd..0000000 --- a/vendor/github.com/rs/zerolog/pkgerrors/stacktrace.go +++ /dev/null @@ -1,82 +0,0 @@ -package pkgerrors - -import ( - "github.com/pkg/errors" -) - -var ( - StackSourceFileName = "source" - StackSourceLineName = "line" - StackSourceFunctionName = "func" -) - -type state struct { - b []byte -} - -// Write implement fmt.Formatter interface. -func (s *state) Write(b []byte) (n int, err error) { - s.b = b - return len(b), nil -} - -// Width implement fmt.Formatter interface. -func (s *state) Width() (wid int, ok bool) { - return 0, false -} - -// Precision implement fmt.Formatter interface. -func (s *state) Precision() (prec int, ok bool) { - return 0, false -} - -// Flag implement fmt.Formatter interface. -func (s *state) Flag(c int) bool { - return false -} - -func frameField(f errors.Frame, s *state, c rune) string { - f.Format(s, c) - return string(s.b) -} - -// MarshalStack implements pkg/errors stack trace marshaling. -// -// zerolog.ErrorStackMarshaler = MarshalStack -func MarshalStack(err error) interface{} { - type stackTracer interface { - StackTrace() errors.StackTrace - } - var sterr stackTracer - var ok bool - for err != nil { - sterr, ok = err.(stackTracer) - if ok { - break - } - - u, ok := err.(interface { - Unwrap() error - }) - if !ok { - return nil - } - - err = u.Unwrap() - } - if sterr == nil { - return nil - } - - st := sterr.StackTrace() - s := &state{} - out := make([]map[string]string, 0, len(st)) - for _, frame := range st { - out = append(out, map[string]string{ - StackSourceFileName: frameField(frame, s, 's'), - StackSourceLineName: frameField(frame, s, 'd'), - StackSourceFunctionName: frameField(frame, s, 'n'), - }) - } - return out -} diff --git a/vendor/github.com/rs/zerolog/pretty.png b/vendor/github.com/rs/zerolog/pretty.png deleted file mode 100644 index 1449e45..0000000 Binary files a/vendor/github.com/rs/zerolog/pretty.png and /dev/null differ diff --git a/vendor/github.com/rs/zerolog/sampler.go b/vendor/github.com/rs/zerolog/sampler.go deleted file mode 100644 index 83ce2ed..0000000 --- a/vendor/github.com/rs/zerolog/sampler.go +++ /dev/null @@ -1,134 +0,0 @@ -package zerolog - -import ( - "math/rand" - "sync/atomic" - "time" -) - -var ( - // Often samples log every ~ 10 events. - Often = RandomSampler(10) - // Sometimes samples log every ~ 100 events. - Sometimes = RandomSampler(100) - // Rarely samples log every ~ 1000 events. - Rarely = RandomSampler(1000) -) - -// Sampler defines an interface to a log sampler. -type Sampler interface { - // Sample returns true if the event should be part of the sample, false if - // the event should be dropped. - Sample(lvl Level) bool -} - -// RandomSampler use a PRNG to randomly sample an event out of N events, -// regardless of their level. -type RandomSampler uint32 - -// Sample implements the Sampler interface. -func (s RandomSampler) Sample(lvl Level) bool { - if s <= 0 { - return false - } - if rand.Intn(int(s)) != 0 { - return false - } - return true -} - -// BasicSampler is a sampler that will send every Nth events, regardless of -// their level. -type BasicSampler struct { - N uint32 - counter uint32 -} - -// Sample implements the Sampler interface. -func (s *BasicSampler) Sample(lvl Level) bool { - n := s.N - if n == 1 { - return true - } - c := atomic.AddUint32(&s.counter, 1) - return c%n == 1 -} - -// BurstSampler lets Burst events pass per Period then pass the decision to -// NextSampler. If Sampler is not set, all subsequent events are rejected. -type BurstSampler struct { - // Burst is the maximum number of event per period allowed before calling - // NextSampler. - Burst uint32 - // Period defines the burst period. If 0, NextSampler is always called. - Period time.Duration - // NextSampler is the sampler used after the burst is reached. If nil, - // events are always rejected after the burst. - NextSampler Sampler - - counter uint32 - resetAt int64 -} - -// Sample implements the Sampler interface. -func (s *BurstSampler) Sample(lvl Level) bool { - if s.Burst > 0 && s.Period > 0 { - if s.inc() <= s.Burst { - return true - } - } - if s.NextSampler == nil { - return false - } - return s.NextSampler.Sample(lvl) -} - -func (s *BurstSampler) inc() uint32 { - now := TimestampFunc().UnixNano() - resetAt := atomic.LoadInt64(&s.resetAt) - var c uint32 - if now > resetAt { - c = 1 - atomic.StoreUint32(&s.counter, c) - newResetAt := now + s.Period.Nanoseconds() - reset := atomic.CompareAndSwapInt64(&s.resetAt, resetAt, newResetAt) - if !reset { - // Lost the race with another goroutine trying to reset. - c = atomic.AddUint32(&s.counter, 1) - } - } else { - c = atomic.AddUint32(&s.counter, 1) - } - return c -} - -// LevelSampler applies a different sampler for each level. -type LevelSampler struct { - TraceSampler, DebugSampler, InfoSampler, WarnSampler, ErrorSampler Sampler -} - -func (s LevelSampler) Sample(lvl Level) bool { - switch lvl { - case TraceLevel: - if s.TraceSampler != nil { - return s.TraceSampler.Sample(lvl) - } - case DebugLevel: - if s.DebugSampler != nil { - return s.DebugSampler.Sample(lvl) - } - case InfoLevel: - if s.InfoSampler != nil { - return s.InfoSampler.Sample(lvl) - } - case WarnLevel: - if s.WarnSampler != nil { - return s.WarnSampler.Sample(lvl) - } - case ErrorLevel: - if s.ErrorSampler != nil { - return s.ErrorSampler.Sample(lvl) - } - } - return true -} diff --git a/vendor/github.com/rs/zerolog/syslog.go b/vendor/github.com/rs/zerolog/syslog.go deleted file mode 100644 index a2b7285..0000000 --- a/vendor/github.com/rs/zerolog/syslog.go +++ /dev/null @@ -1,89 +0,0 @@ -// +build !windows -// +build !binary_log - -package zerolog - -import ( - "io" -) - -// See http://cee.mitre.org/language/1.0-beta1/clt.html#syslog -// or https://www.rsyslog.com/json-elasticsearch/ -const ceePrefix = "@cee:" - -// SyslogWriter is an interface matching a syslog.Writer struct. -type SyslogWriter interface { - io.Writer - Debug(m string) error - Info(m string) error - Warning(m string) error - Err(m string) error - Emerg(m string) error - Crit(m string) error -} - -type syslogWriter struct { - w SyslogWriter - prefix string -} - -// SyslogLevelWriter wraps a SyslogWriter and call the right syslog level -// method matching the zerolog level. -func SyslogLevelWriter(w SyslogWriter) LevelWriter { - return syslogWriter{w, ""} -} - -// SyslogCEEWriter wraps a SyslogWriter with a SyslogLevelWriter that adds a -// MITRE CEE prefix for JSON syslog entries, compatible with rsyslog -// and syslog-ng JSON logging support. -// See https://www.rsyslog.com/json-elasticsearch/ -func SyslogCEEWriter(w SyslogWriter) LevelWriter { - return syslogWriter{w, ceePrefix} -} - -func (sw syslogWriter) Write(p []byte) (n int, err error) { - var pn int - if sw.prefix != "" { - pn, err = sw.w.Write([]byte(sw.prefix)) - if err != nil { - return pn, err - } - } - n, err = sw.w.Write(p) - return pn + n, err -} - -// WriteLevel implements LevelWriter interface. -func (sw syslogWriter) WriteLevel(level Level, p []byte) (n int, err error) { - switch level { - case TraceLevel: - case DebugLevel: - err = sw.w.Debug(sw.prefix + string(p)) - case InfoLevel: - err = sw.w.Info(sw.prefix + string(p)) - case WarnLevel: - err = sw.w.Warning(sw.prefix + string(p)) - case ErrorLevel: - err = sw.w.Err(sw.prefix + string(p)) - case FatalLevel: - err = sw.w.Emerg(sw.prefix + string(p)) - case PanicLevel: - err = sw.w.Crit(sw.prefix + string(p)) - case NoLevel: - err = sw.w.Info(sw.prefix + string(p)) - default: - panic("invalid level") - } - // Any CEE prefix is not part of the message, so we don't include its length - n = len(p) - return -} - -// Call the underlying writer's Close method if it is an io.Closer. Otherwise -// does nothing. -func (sw syslogWriter) Close() error { - if c, ok := sw.w.(io.Closer); ok { - return c.Close() - } - return nil -} diff --git a/vendor/github.com/rs/zerolog/writer.go b/vendor/github.com/rs/zerolog/writer.go deleted file mode 100644 index 41b394d..0000000 --- a/vendor/github.com/rs/zerolog/writer.go +++ /dev/null @@ -1,346 +0,0 @@ -package zerolog - -import ( - "bytes" - "io" - "path" - "runtime" - "strconv" - "strings" - "sync" -) - -// LevelWriter defines as interface a writer may implement in order -// to receive level information with payload. -type LevelWriter interface { - io.Writer - WriteLevel(level Level, p []byte) (n int, err error) -} - -// LevelWriterAdapter adapts an io.Writer to support the LevelWriter interface. -type LevelWriterAdapter struct { - io.Writer -} - -// WriteLevel simply writes everything to the adapted writer, ignoring the level. -func (lw LevelWriterAdapter) WriteLevel(l Level, p []byte) (n int, err error) { - return lw.Write(p) -} - -// Call the underlying writer's Close method if it is an io.Closer. Otherwise -// does nothing. -func (lw LevelWriterAdapter) Close() error { - if closer, ok := lw.Writer.(io.Closer); ok { - return closer.Close() - } - return nil -} - -type syncWriter struct { - mu sync.Mutex - lw LevelWriter -} - -// SyncWriter wraps w so that each call to Write is synchronized with a mutex. -// This syncer can be used to wrap the call to writer's Write method if it is -// not thread safe. Note that you do not need this wrapper for os.File Write -// operations on POSIX and Windows systems as they are already thread-safe. -func SyncWriter(w io.Writer) io.Writer { - if lw, ok := w.(LevelWriter); ok { - return &syncWriter{lw: lw} - } - return &syncWriter{lw: LevelWriterAdapter{w}} -} - -// Write implements the io.Writer interface. -func (s *syncWriter) Write(p []byte) (n int, err error) { - s.mu.Lock() - defer s.mu.Unlock() - return s.lw.Write(p) -} - -// WriteLevel implements the LevelWriter interface. -func (s *syncWriter) WriteLevel(l Level, p []byte) (n int, err error) { - s.mu.Lock() - defer s.mu.Unlock() - return s.lw.WriteLevel(l, p) -} - -func (s *syncWriter) Close() error { - s.mu.Lock() - defer s.mu.Unlock() - if closer, ok := s.lw.(io.Closer); ok { - return closer.Close() - } - return nil -} - -type multiLevelWriter struct { - writers []LevelWriter -} - -func (t multiLevelWriter) Write(p []byte) (n int, err error) { - for _, w := range t.writers { - if _n, _err := w.Write(p); err == nil { - n = _n - if _err != nil { - err = _err - } else if _n != len(p) { - err = io.ErrShortWrite - } - } - } - return n, err -} - -func (t multiLevelWriter) WriteLevel(l Level, p []byte) (n int, err error) { - for _, w := range t.writers { - if _n, _err := w.WriteLevel(l, p); err == nil { - n = _n - if _err != nil { - err = _err - } else if _n != len(p) { - err = io.ErrShortWrite - } - } - } - return n, err -} - -// Calls close on all the underlying writers that are io.Closers. If any of the -// Close methods return an error, the remainder of the closers are not closed -// and the error is returned. -func (t multiLevelWriter) Close() error { - for _, w := range t.writers { - if closer, ok := w.(io.Closer); ok { - if err := closer.Close(); err != nil { - return err - } - } - } - return nil -} - -// MultiLevelWriter creates a writer that duplicates its writes to all the -// provided writers, similar to the Unix tee(1) command. If some writers -// implement LevelWriter, their WriteLevel method will be used instead of Write. -func MultiLevelWriter(writers ...io.Writer) LevelWriter { - lwriters := make([]LevelWriter, 0, len(writers)) - for _, w := range writers { - if lw, ok := w.(LevelWriter); ok { - lwriters = append(lwriters, lw) - } else { - lwriters = append(lwriters, LevelWriterAdapter{w}) - } - } - return multiLevelWriter{lwriters} -} - -// TestingLog is the logging interface of testing.TB. -type TestingLog interface { - Log(args ...interface{}) - Logf(format string, args ...interface{}) - Helper() -} - -// TestWriter is a writer that writes to testing.TB. -type TestWriter struct { - T TestingLog - - // Frame skips caller frames to capture the original file and line numbers. - Frame int -} - -// NewTestWriter creates a writer that logs to the testing.TB. -func NewTestWriter(t TestingLog) TestWriter { - return TestWriter{T: t} -} - -// Write to testing.TB. -func (t TestWriter) Write(p []byte) (n int, err error) { - t.T.Helper() - - n = len(p) - - // Strip trailing newline because t.Log always adds one. - p = bytes.TrimRight(p, "\n") - - // Try to correct the log file and line number to the caller. - if t.Frame > 0 { - _, origFile, origLine, _ := runtime.Caller(1) - _, frameFile, frameLine, ok := runtime.Caller(1 + t.Frame) - if ok { - erase := strings.Repeat("\b", len(path.Base(origFile))+len(strconv.Itoa(origLine))+3) - t.T.Logf("%s%s:%d: %s", erase, path.Base(frameFile), frameLine, p) - return n, err - } - } - t.T.Log(string(p)) - - return n, err -} - -// ConsoleTestWriter creates an option that correctly sets the file frame depth for testing.TB log. -func ConsoleTestWriter(t TestingLog) func(w *ConsoleWriter) { - return func(w *ConsoleWriter) { - w.Out = TestWriter{T: t, Frame: 6} - } -} - -// FilteredLevelWriter writes only logs at Level or above to Writer. -// -// It should be used only in combination with MultiLevelWriter when you -// want to write to multiple destinations at different levels. Otherwise -// you should just set the level on the logger and filter events early. -// When using MultiLevelWriter then you set the level on the logger to -// the lowest of the levels you use for writers. -type FilteredLevelWriter struct { - Writer LevelWriter - Level Level -} - -// Write writes to the underlying Writer. -func (w *FilteredLevelWriter) Write(p []byte) (int, error) { - return w.Writer.Write(p) -} - -// WriteLevel calls WriteLevel of the underlying Writer only if the level is equal -// or above the Level. -func (w *FilteredLevelWriter) WriteLevel(level Level, p []byte) (int, error) { - if level >= w.Level { - return w.Writer.WriteLevel(level, p) - } - return len(p), nil -} - -var triggerWriterPool = &sync.Pool{ - New: func() interface{} { - return bytes.NewBuffer(make([]byte, 0, 1024)) - }, -} - -// TriggerLevelWriter buffers log lines at the ConditionalLevel or below -// until a trigger level (or higher) line is emitted. Log lines with level -// higher than ConditionalLevel are always written out to the destination -// writer. If trigger never happens, buffered log lines are never written out. -// -// It can be used to configure "log level per request". -type TriggerLevelWriter struct { - // Destination writer. If LevelWriter is provided (usually), its WriteLevel is used - // instead of Write. - io.Writer - - // ConditionalLevel is the level (and below) at which lines are buffered until - // a trigger level (or higher) line is emitted. Usually this is set to DebugLevel. - ConditionalLevel Level - - // TriggerLevel is the lowest level that triggers the sending of the conditional - // level lines. Usually this is set to ErrorLevel. - TriggerLevel Level - - buf *bytes.Buffer - triggered bool - mu sync.Mutex -} - -func (w *TriggerLevelWriter) WriteLevel(l Level, p []byte) (n int, err error) { - w.mu.Lock() - defer w.mu.Unlock() - - // At first trigger level or above log line, we flush the buffer and change the - // trigger state to triggered. - if !w.triggered && l >= w.TriggerLevel { - err := w.trigger() - if err != nil { - return 0, err - } - } - - // Unless triggered, we buffer everything at and below ConditionalLevel. - if !w.triggered && l <= w.ConditionalLevel { - if w.buf == nil { - w.buf = triggerWriterPool.Get().(*bytes.Buffer) - } - - // We prefix each log line with a byte with the level. - // Hopefully we will never have a level value which equals a newline - // (which could interfere with reconstruction of log lines in the trigger method). - w.buf.WriteByte(byte(l)) - w.buf.Write(p) - return len(p), nil - } - - // Anything above ConditionalLevel is always passed through. - // Once triggered, everything is passed through. - if lw, ok := w.Writer.(LevelWriter); ok { - return lw.WriteLevel(l, p) - } - return w.Write(p) -} - -// trigger expects lock to be held. -func (w *TriggerLevelWriter) trigger() error { - if w.triggered { - return nil - } - w.triggered = true - - if w.buf == nil { - return nil - } - - p := w.buf.Bytes() - for len(p) > 0 { - // We do not use bufio.Scanner here because we already have full buffer - // in the memory and we do not want extra copying from the buffer to - // scanner's token slice, nor we want to hit scanner's token size limit, - // and we also want to preserve newlines. - i := bytes.IndexByte(p, '\n') - line := p[0 : i+1] - p = p[i+1:] - // We prefixed each log line with a byte with the level. - level := Level(line[0]) - line = line[1:] - var err error - if lw, ok := w.Writer.(LevelWriter); ok { - _, err = lw.WriteLevel(level, line) - } else { - _, err = w.Write(line) - } - if err != nil { - return err - } - } - - return nil -} - -// Trigger forces flushing the buffer and change the trigger state to -// triggered, if the writer has not already been triggered before. -func (w *TriggerLevelWriter) Trigger() error { - w.mu.Lock() - defer w.mu.Unlock() - - return w.trigger() -} - -// Close closes the writer and returns the buffer to the pool. -func (w *TriggerLevelWriter) Close() error { - w.mu.Lock() - defer w.mu.Unlock() - - if w.buf == nil { - return nil - } - - // We return the buffer only if it has not grown above the limit. - // This prevents accumulation of large buffers in the pool just - // because occasionally a large buffer might be needed. - if w.buf.Cap() <= TriggerLevelWriterBufferReuseLimit { - w.buf.Reset() - triggerWriterPool.Put(w.buf) - } - w.buf = nil - - return nil -} diff --git a/vendor/golang.org/x/sys/unix/README.md b/vendor/golang.org/x/sys/unix/README.md index 7d3c060..6e08a76 100644 --- a/vendor/golang.org/x/sys/unix/README.md +++ b/vendor/golang.org/x/sys/unix/README.md @@ -156,7 +156,7 @@ from the generated architecture-specific files listed below, and merge these into a common file for each OS. The merge is performed in the following steps: -1. Construct the set of common code that is idential in all architecture-specific files. +1. Construct the set of common code that is identical in all architecture-specific files. 2. Write this common code to the merged file. 3. Remove the common code from all architecture-specific files. diff --git a/vendor/golang.org/x/sys/unix/mkall.sh b/vendor/golang.org/x/sys/unix/mkall.sh index e6f31d3..9191ca2 100644 --- a/vendor/golang.org/x/sys/unix/mkall.sh +++ b/vendor/golang.org/x/sys/unix/mkall.sh @@ -22,228 +22,229 @@ run="sh" cmd="" case "$1" in --syscalls) - for i in zsyscall*go - do - # Run the command line that appears in the first line - # of the generated file to regenerate it. - sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i - rm _$i - done - exit 0 - ;; --n) - run="cat" - cmd="echo" - shift + -syscalls) + for i in zsyscall*go; do + # Run the command line that appears in the first line + # of the generated file to regenerate it. + sed 1q $i | sed 's;^// ;;' | sh >_$i && gofmt <_$i >$i + rm _$i + done + exit 0 + ;; + -n) + run="cat" + cmd="echo" + shift + ;; esac case "$#" in -0) - ;; -*) - echo 'usage: mkall.sh [-n]' 1>&2 - exit 2 + 0) ;; + *) + echo 'usage: mkall.sh [-n]' 1>&2 + exit 2 + ;; esac -if [[ "$GOOS" = "linux" ]]; then - # Use the Docker-based build system - # Files generated through docker (use $cmd so you can Ctl-C the build or run) - $cmd docker build --tag generate:$GOOS $GOOS - $cmd docker run --interactive --tty --volume $(cd -- "$(dirname -- "$0")/.." && pwd):/build generate:$GOOS - exit +if [[ $GOOS == "linux" ]]; then + # Use the Docker-based build system + # Files generated through docker (use $cmd so you can Ctl-C the build or run) + $cmd docker build --tag generate:$GOOS $GOOS + $cmd docker run --interactive --tty --volume $(cd -- "$(dirname -- "$0")/.." && pwd):/build generate:$GOOS + exit fi GOOSARCH_in=syscall_$GOOSARCH.go case "$GOOSARCH" in -_* | *_ | _) - echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2 - exit 1 - ;; -aix_ppc) - mkerrors="$mkerrors -maix32" - mksyscall="go run mksyscall_aix_ppc.go -aix" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -aix_ppc64) - mkerrors="$mkerrors -maix64" - mksyscall="go run mksyscall_aix_ppc64.go -aix" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -darwin_amd64) - mkerrors="$mkerrors -m64" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - mkasm="go run mkasm.go" - ;; -darwin_arm64) - mkerrors="$mkerrors -m64" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - mkasm="go run mkasm.go" - ;; -dragonfly_amd64) - mkerrors="$mkerrors -m64" - mksyscall="go run mksyscall.go -dragonfly" - mksysnum="go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -freebsd_386) - mkerrors="$mkerrors -m32" - mksyscall="go run mksyscall.go -l32" - mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -freebsd_amd64) - mkerrors="$mkerrors -m64" - mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -freebsd_arm) - mkerrors="$mkerrors" - mksyscall="go run mksyscall.go -l32 -arm" - mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'" - # Let the type of C char be signed for making the bare syscall - # API consistent across platforms. - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -freebsd_arm64) - mkerrors="$mkerrors -m64" - mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'" - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -freebsd_riscv64) - mkerrors="$mkerrors -m64" - mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'" - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -netbsd_386) - mkerrors="$mkerrors -m32" - mksyscall="go run mksyscall.go -l32 -netbsd" - mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -netbsd_amd64) - mkerrors="$mkerrors -m64" - mksyscall="go run mksyscall.go -netbsd" - mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -netbsd_arm) - mkerrors="$mkerrors" - mksyscall="go run mksyscall.go -l32 -netbsd -arm" - mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'" - # Let the type of C char be signed for making the bare syscall - # API consistent across platforms. - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -netbsd_arm64) - mkerrors="$mkerrors -m64" - mksyscall="go run mksyscall.go -netbsd" - mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -openbsd_386) - mkasm="go run mkasm.go" - mkerrors="$mkerrors -m32" - mksyscall="go run mksyscall.go -l32 -openbsd -libc" - mksysctl="go run mksysctl_openbsd.go" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -openbsd_amd64) - mkasm="go run mkasm.go" - mkerrors="$mkerrors -m64" - mksyscall="go run mksyscall.go -openbsd -libc" - mksysctl="go run mksysctl_openbsd.go" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -openbsd_arm) - mkasm="go run mkasm.go" - mkerrors="$mkerrors" - mksyscall="go run mksyscall.go -l32 -openbsd -arm -libc" - mksysctl="go run mksysctl_openbsd.go" - # Let the type of C char be signed for making the bare syscall - # API consistent across platforms. - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -openbsd_arm64) - mkasm="go run mkasm.go" - mkerrors="$mkerrors -m64" - mksyscall="go run mksyscall.go -openbsd -libc" - mksysctl="go run mksysctl_openbsd.go" - # Let the type of C char be signed for making the bare syscall - # API consistent across platforms. - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -openbsd_mips64) - mkasm="go run mkasm.go" - mkerrors="$mkerrors -m64" - mksyscall="go run mksyscall.go -openbsd -libc" - mksysctl="go run mksysctl_openbsd.go" - # Let the type of C char be signed for making the bare syscall - # API consistent across platforms. - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -openbsd_ppc64) - mkasm="go run mkasm.go" - mkerrors="$mkerrors -m64" - mksyscall="go run mksyscall.go -openbsd -libc" - mksysctl="go run mksysctl_openbsd.go" - # Let the type of C char be signed for making the bare syscall - # API consistent across platforms. - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -openbsd_riscv64) - mkasm="go run mkasm.go" - mkerrors="$mkerrors -m64" - mksyscall="go run mksyscall.go -openbsd -libc" - mksysctl="go run mksysctl_openbsd.go" - # Let the type of C char be signed for making the bare syscall - # API consistent across platforms. - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -solaris_amd64) - mksyscall="go run mksyscall_solaris.go" - mkerrors="$mkerrors -m64" - mksysnum= - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -illumos_amd64) - mksyscall="go run mksyscall_solaris.go" - mkerrors= - mksysnum= - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -*) - echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2 - exit 1 - ;; + _* | *_ | _) + echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2 + exit 1 + ;; + aix_ppc) + mkerrors="$mkerrors -maix32" + mksyscall="go run mksyscall_aix_ppc.go -aix" + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + ;; + aix_ppc64) + mkerrors="$mkerrors -maix64" + mksyscall="go run mksyscall_aix_ppc64.go -aix" + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + ;; + darwin_amd64) + mkerrors="$mkerrors -m64" + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + mkasm="go run mkasm.go" + ;; + darwin_arm64) + mkerrors="$mkerrors -m64" + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + mkasm="go run mkasm.go" + ;; + dragonfly_amd64) + mkerrors="$mkerrors -m64" + mksyscall="go run mksyscall.go -dragonfly" + mksysnum="go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'" + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + ;; + freebsd_386) + mkerrors="$mkerrors -m32" + mksyscall="go run mksyscall.go -l32" + mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'" + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + ;; + freebsd_amd64) + mkerrors="$mkerrors -m64" + mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'" + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + ;; + freebsd_arm) + mkerrors="$mkerrors" + mksyscall="go run mksyscall.go -l32 -arm" + mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'" + # Let the type of C char be signed for making the bare syscall + # API consistent across platforms. + mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" + ;; + freebsd_arm64) + mkerrors="$mkerrors -m64" + mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'" + mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" + ;; + freebsd_riscv64) + mkerrors="$mkerrors -m64" + mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'" + mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" + ;; + netbsd_386) + mkerrors="$mkerrors -m32" + mksyscall="go run mksyscall.go -l32 -netbsd" + mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'" + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + ;; + netbsd_amd64) + mkerrors="$mkerrors -m64" + mksyscall="go run mksyscall.go -netbsd" + mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'" + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + ;; + netbsd_arm) + mkerrors="$mkerrors" + mksyscall="go run mksyscall.go -l32 -netbsd -arm" + mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'" + # Let the type of C char be signed for making the bare syscall + # API consistent across platforms. + mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" + ;; + netbsd_arm64) + mkerrors="$mkerrors -m64" + mksyscall="go run mksyscall.go -netbsd" + mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'" + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + ;; + openbsd_386) + mkasm="go run mkasm.go" + mkerrors="$mkerrors -m32" + mksyscall="go run mksyscall.go -l32 -openbsd -libc" + mksysctl="go run mksysctl_openbsd.go" + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + ;; + openbsd_amd64) + mkasm="go run mkasm.go" + mkerrors="$mkerrors -m64" + mksyscall="go run mksyscall.go -openbsd -libc" + mksysctl="go run mksysctl_openbsd.go" + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + ;; + openbsd_arm) + mkasm="go run mkasm.go" + mkerrors="$mkerrors" + mksyscall="go run mksyscall.go -l32 -openbsd -arm -libc" + mksysctl="go run mksysctl_openbsd.go" + # Let the type of C char be signed for making the bare syscall + # API consistent across platforms. + mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" + ;; + openbsd_arm64) + mkasm="go run mkasm.go" + mkerrors="$mkerrors -m64" + mksyscall="go run mksyscall.go -openbsd -libc" + mksysctl="go run mksysctl_openbsd.go" + # Let the type of C char be signed for making the bare syscall + # API consistent across platforms. + mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" + ;; + openbsd_mips64) + mkasm="go run mkasm.go" + mkerrors="$mkerrors -m64" + mksyscall="go run mksyscall.go -openbsd -libc" + mksysctl="go run mksysctl_openbsd.go" + # Let the type of C char be signed for making the bare syscall + # API consistent across platforms. + mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" + ;; + openbsd_ppc64) + mkasm="go run mkasm.go" + mkerrors="$mkerrors -m64" + mksyscall="go run mksyscall.go -openbsd -libc" + mksysctl="go run mksysctl_openbsd.go" + # Let the type of C char be signed for making the bare syscall + # API consistent across platforms. + mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" + ;; + openbsd_riscv64) + mkasm="go run mkasm.go" + mkerrors="$mkerrors -m64" + mksyscall="go run mksyscall.go -openbsd -libc" + mksysctl="go run mksysctl_openbsd.go" + # Let the type of C char be signed for making the bare syscall + # API consistent across platforms. + mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" + ;; + solaris_amd64) + mksyscall="go run mksyscall_solaris.go" + mkerrors="$mkerrors -m64" + mksysnum= + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + ;; + illumos_amd64) + mksyscall="go run mksyscall_solaris.go" + mkerrors= + mksysnum= + mktypes="GOARCH=$GOARCH go tool cgo -godefs" + ;; + *) + echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2 + exit 1 + ;; esac ( - if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi - case "$GOOS" in - *) - syscall_goos="syscall_$GOOS.go" - case "$GOOS" in - darwin | dragonfly | freebsd | netbsd | openbsd) - syscall_goos="syscall_bsd.go $syscall_goos" - ;; - esac - if [ -n "$mksyscall" ]; then - if [ "$GOOSARCH" == "aix_ppc64" ]; then - # aix/ppc64 script generates files instead of writing to stdin. - echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_"$GOOSARCH"_gccgo.go && gofmt -w zsyscall_"$GOOSARCH"_gc.go " ; - elif [ "$GOOS" == "illumos" ]; then - # illumos code generation requires a --illumos switch - echo "$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go"; - # illumos implies solaris, so solaris code generation is also required - echo "$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go"; - else - echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; - fi - fi - esac - if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi - if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi - if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go"; fi - if [ -n "$mkasm" ]; then echo "$mkasm $GOOS $GOARCH"; fi + if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi + case "$GOOS" in + *) + syscall_goos="syscall_$GOOS.go" + case "$GOOS" in + darwin | dragonfly | freebsd | netbsd | openbsd) + syscall_goos="syscall_bsd.go $syscall_goos" + ;; + esac + if [ -n "$mksyscall" ]; then + if [ "$GOOSARCH" == "aix_ppc64" ]; then + # aix/ppc64 script generates files instead of writing to stdin. + echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_"$GOOSARCH"_gccgo.go && gofmt -w zsyscall_"$GOOSARCH"_gc.go " + elif [ "$GOOS" == "illumos" ]; then + # illumos code generation requires a --illumos switch + echo "$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go" + # illumos implies solaris, so solaris code generation is also required + echo "$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go" + else + echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go" + fi + fi + ;; + esac + if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi + if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi + if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go"; fi + if [ -n "$mkasm" ]; then echo "$mkasm $GOOS $GOARCH"; fi ) | $run diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index e14b766..240a383 100644 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -12,26 +12,26 @@ export LC_ALL=C export LC_CTYPE=C if test -z "$GOARCH" -o -z "$GOOS"; then - echo 1>&2 "GOARCH or GOOS not defined in environment" - exit 1 + echo 1>&2 "GOARCH or GOOS not defined in environment" + exit 1 fi # Check that we are using the new build system if we should -if [[ "$GOOS" = "linux" ]] && [[ "$GOLANG_SYS_BUILD" != "docker" ]]; then - echo 1>&2 "In the Docker based build system, mkerrors should not be called directly." - echo 1>&2 "See README.md" - exit 1 +if [[ $GOOS == "linux" ]] && [[ $GOLANG_SYS_BUILD != "docker" ]]; then + echo 1>&2 "In the Docker based build system, mkerrors should not be called directly." + echo 1>&2 "See README.md" + exit 1 fi -if [[ "$GOOS" = "aix" ]]; then - CC=${CC:-gcc} +if [[ $GOOS == "aix" ]]; then + CC=${CC:-gcc} else - CC=${CC:-cc} + CC=${CC:-cc} fi -if [[ "$GOOS" = "solaris" ]]; then - # Assumes GNU versions of utilities in PATH. - export PATH=/usr/gnu/bin:$PATH +if [[ $GOOS == "solaris" ]]; then + # Assumes GNU versions of utilities in PATH. + export PATH=/usr/gnu/bin:$PATH fi uname=$(uname) @@ -434,7 +434,6 @@ includes_SunOS=' #include ' - includes=' #include #include @@ -455,21 +454,21 @@ ccflags="$@" # Write go tool cgo -godefs input. ( - echo package unix - echo - echo '/*' - indirect="includes_$(uname)" - echo "${!indirect} $includes" - echo '*/' - echo 'import "C"' - echo 'import "syscall"' - echo - echo 'const (' - - # The gcc command line prints all the #defines - # it encounters while processing the input - echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags | - awk ' + echo package unix + echo + echo '/*' + indirect="includes_$(uname)" + echo "${!indirect} $includes" + echo '*/' + echo 'import "C"' + echo 'import "syscall"' + echo + echo 'const (' + + # The gcc command line prints all the #defines + # it encounters while processing the input + echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags | + awk ' $1 != "#define" || $2 ~ /\(/ || $3 == "" {next} $2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next} # 386 registers @@ -642,32 +641,32 @@ ccflags="$@" {next} ' | sort - echo ')' + echo ')' ) >_const.go # Pull out the error names for later. errors=$( - echo '#include ' | $CC -x c - -E -dM $ccflags | - awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' | - sort + echo '#include ' | $CC -x c - -E -dM $ccflags | + awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' | + sort ) # Pull out the signal names for later. signals=$( - echo '#include ' | $CC -x c - -E -dM $ccflags | - awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' | - grep -v 'SIGSTKSIZE\|SIGSTKSZ\|SIGRT\|SIGMAX64' | - sort + echo '#include ' | $CC -x c - -E -dM $ccflags | + awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' | + grep -E -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' | + sort ) # Again, writing regexps to a file. echo '#include ' | $CC -x c - -E -dM $ccflags | - awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' | - sort >_error.grep + awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' | + sort >_error.grep echo '#include ' | $CC -x c - -E -dM $ccflags | - awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' | - grep -v 'SIGSTKSIZE\|SIGSTKSZ\|SIGRT\|SIGMAX64' | - sort >_signal.grep + awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' | + grep -E -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' | + sort >_signal.grep echo '// mkerrors.sh' "$@" echo '// Code generated by the command above; see README.md. DO NOT EDIT.' @@ -690,7 +689,7 @@ echo ')' # Run C program to print error and syscall strings. ( - echo -E " + echo -E " #include #include #include @@ -709,23 +708,21 @@ struct tuple { struct tuple errors[] = { " - for i in $errors - do - echo -E ' {'$i', "'$i'" },' - done + for i in $errors; do + echo -E ' {'$i', "'$i'" },' + done - echo -E " + echo -E " }; struct tuple signals[] = { " - for i in $signals - do - echo -E ' {'$i', "'$i'" },' - done + for i in $signals; do + echo -E ' {'$i', "'$i'" },' + done - # Use -E because on some systems bash builtin interprets \n itself. - echo -E ' + # Use -E because on some systems bash builtin interprets \n itself. + echo -E ' }; static int diff --git a/vendor/golang.org/x/sys/unix/syscall_aix.go b/vendor/golang.org/x/sys/unix/syscall_aix.go index 67ce6ce..6f15ba1 100644 --- a/vendor/golang.org/x/sys/unix/syscall_aix.go +++ b/vendor/golang.org/x/sys/unix/syscall_aix.go @@ -360,7 +360,7 @@ func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, var status _C_int var r Pid_t err = ERESTART - // AIX wait4 may return with ERESTART errno, while the processus is still + // AIX wait4 may return with ERESTART errno, while the process is still // active. for err == ERESTART { r, err = wait4(Pid_t(pid), &status, options, rusage) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index 3f1d3d4..f08abd4 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -1295,6 +1295,48 @@ func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) { return &value, err } +// GetsockoptTCPCCVegasInfo returns algorithm specific congestion control information for a socket using the "vegas" +// algorithm. +// +// The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option: +// +// algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION) +func GetsockoptTCPCCVegasInfo(fd, level, opt int) (*TCPVegasInfo, error) { + var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment + vallen := _Socklen(SizeofTCPCCInfo) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) + out := (*TCPVegasInfo)(unsafe.Pointer(&value[0])) + return out, err +} + +// GetsockoptTCPCCDCTCPInfo returns algorithm specific congestion control information for a socket using the "dctp" +// algorithm. +// +// The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option: +// +// algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION) +func GetsockoptTCPCCDCTCPInfo(fd, level, opt int) (*TCPDCTCPInfo, error) { + var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment + vallen := _Socklen(SizeofTCPCCInfo) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) + out := (*TCPDCTCPInfo)(unsafe.Pointer(&value[0])) + return out, err +} + +// GetsockoptTCPCCBBRInfo returns algorithm specific congestion control information for a socket using the "bbr" +// algorithm. +// +// The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option: +// +// algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION) +func GetsockoptTCPCCBBRInfo(fd, level, opt int) (*TCPBBRInfo, error) { + var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment + vallen := _Socklen(SizeofTCPCCInfo) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) + out := (*TCPBBRInfo)(unsafe.Pointer(&value[0])) + return out, err +} + // GetsockoptString returns the string value of the socket option opt for the // socket associated with fd at the given socket level. func GetsockoptString(fd, level, opt int) (string, error) { @@ -1959,7 +2001,26 @@ func Getpgrp() (pid int) { //sysnb Getpid() (pid int) //sysnb Getppid() (ppid int) //sys Getpriority(which int, who int) (prio int, err error) -//sys Getrandom(buf []byte, flags int) (n int, err error) + +func Getrandom(buf []byte, flags int) (n int, err error) { + vdsoRet, supported := vgetrandom(buf, uint32(flags)) + if supported { + if vdsoRet < 0 { + return 0, errnoErr(syscall.Errno(-vdsoRet)) + } + return vdsoRet, nil + } + var p *byte + if len(buf) > 0 { + p = &buf[0] + } + r, _, e := Syscall(SYS_GETRANDOM, uintptr(unsafe.Pointer(p)), uintptr(len(buf)), uintptr(flags)) + if e != 0 { + return 0, errnoErr(e) + } + return int(r), nil +} + //sysnb Getrusage(who int, rusage *Rusage) (err error) //sysnb Getsid(pid int) (sid int, err error) //sysnb Gettid() (tid int) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go index cf2ee6c..745e5c7 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go @@ -182,3 +182,5 @@ func KexecFileLoad(kernelFd int, initrdFd int, cmdline string, flags int) error } return kexecFileLoad(kernelFd, initrdFd, cmdlineLen, cmdline, flags) } + +const SYS_FSTATAT = SYS_NEWFSTATAT diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go b/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go index 3d0e984..dd2262a 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go @@ -214,3 +214,5 @@ func KexecFileLoad(kernelFd int, initrdFd int, cmdline string, flags int) error } return kexecFileLoad(kernelFd, initrdFd, cmdlineLen, cmdline, flags) } + +const SYS_FSTATAT = SYS_NEWFSTATAT diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go b/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go index 6f5a288..8cf3670 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go @@ -187,3 +187,5 @@ func RISCVHWProbe(pairs []RISCVHWProbePairs, set *CPUSet, flags uint) (err error } return riscvHWProbe(pairs, setSize, set, flags) } + +const SYS_FSTATAT = SYS_NEWFSTATAT diff --git a/vendor/golang.org/x/sys/unix/vgetrandom_linux.go b/vendor/golang.org/x/sys/unix/vgetrandom_linux.go new file mode 100644 index 0000000..07ac8e0 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/vgetrandom_linux.go @@ -0,0 +1,13 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build linux && go1.24 + +package unix + +import _ "unsafe" + +//go:linkname vgetrandom runtime.vgetrandom +//go:noescape +func vgetrandom(p []byte, flags uint32) (ret int, supported bool) diff --git a/vendor/golang.org/x/sys/unix/vgetrandom_unsupported.go b/vendor/golang.org/x/sys/unix/vgetrandom_unsupported.go new file mode 100644 index 0000000..297e97b --- /dev/null +++ b/vendor/golang.org/x/sys/unix/vgetrandom_unsupported.go @@ -0,0 +1,11 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !linux || !go1.24 + +package unix + +func vgetrandom(p []byte, flags uint32) (ret int, supported bool) { + return -1, false +} diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux.go b/vendor/golang.org/x/sys/unix/zerrors_linux.go index 01a70b2..de3b462 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -495,6 +495,7 @@ const ( BPF_F_TEST_REG_INVARIANTS = 0x80 BPF_F_TEST_RND_HI32 = 0x4 BPF_F_TEST_RUN_ON_CPU = 0x1 + BPF_F_TEST_SKB_CHECKSUM_COMPLETE = 0x4 BPF_F_TEST_STATE_FREQ = 0x8 BPF_F_TEST_XDP_LIVE_FRAMES = 0x2 BPF_F_XDP_DEV_BOUND_ONLY = 0x40 @@ -1922,6 +1923,7 @@ const ( MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MNT_ID_REQ_SIZE_VER0 = 0x18 + MNT_ID_REQ_SIZE_VER1 = 0x20 MODULE_INIT_COMPRESSED_FILE = 0x4 MODULE_INIT_IGNORE_MODVERSIONS = 0x1 MODULE_INIT_IGNORE_VERMAGIC = 0x2 @@ -2187,7 +2189,7 @@ const ( NFT_REG_SIZE = 0x10 NFT_REJECT_ICMPX_MAX = 0x3 NFT_RT_MAX = 0x4 - NFT_SECMARK_CTX_MAXLEN = 0x100 + NFT_SECMARK_CTX_MAXLEN = 0x1000 NFT_SET_MAXNAMELEN = 0x100 NFT_SOCKET_MAX = 0x3 NFT_TABLE_F_MASK = 0x7 @@ -2356,9 +2358,11 @@ const ( PERF_MEM_LVLNUM_IO = 0xa PERF_MEM_LVLNUM_L1 = 0x1 PERF_MEM_LVLNUM_L2 = 0x2 + PERF_MEM_LVLNUM_L2_MHB = 0x5 PERF_MEM_LVLNUM_L3 = 0x3 PERF_MEM_LVLNUM_L4 = 0x4 PERF_MEM_LVLNUM_LFB = 0xc + PERF_MEM_LVLNUM_MSC = 0x6 PERF_MEM_LVLNUM_NA = 0xf PERF_MEM_LVLNUM_PMEM = 0xe PERF_MEM_LVLNUM_RAM = 0xd @@ -2431,6 +2435,7 @@ const ( PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 + PROCFS_IOCTL_MAGIC = 'f' PROC_SUPER_MAGIC = 0x9fa0 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 @@ -2933,11 +2938,12 @@ const ( RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 RWF_APPEND = 0x10 + RWF_ATOMIC = 0x40 RWF_DSYNC = 0x2 RWF_HIPRI = 0x1 RWF_NOAPPEND = 0x20 RWF_NOWAIT = 0x8 - RWF_SUPPORTED = 0x3f + RWF_SUPPORTED = 0x7f RWF_SYNC = 0x4 RWF_WRITE_LIFE_NOT_SET = 0x0 SCHED_BATCH = 0x3 @@ -3210,6 +3216,7 @@ const ( STATX_ATTR_MOUNT_ROOT = 0x2000 STATX_ATTR_NODUMP = 0x40 STATX_ATTR_VERITY = 0x100000 + STATX_ATTR_WRITE_ATOMIC = 0x400000 STATX_BASIC_STATS = 0x7ff STATX_BLOCKS = 0x400 STATX_BTIME = 0x800 @@ -3226,6 +3233,7 @@ const ( STATX_SUBVOL = 0x8000 STATX_TYPE = 0x1 STATX_UID = 0x8 + STATX_WRITE_ATOMIC = 0x10000 STATX__RESERVED = 0x80000000 SYNC_FILE_RANGE_WAIT_AFTER = 0x4 SYNC_FILE_RANGE_WAIT_BEFORE = 0x1 @@ -3624,6 +3632,7 @@ const ( XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000 XDP_UMEM_PGOFF_FILL_RING = 0x100000000 XDP_UMEM_REG = 0x4 + XDP_UMEM_TX_METADATA_LEN = 0x4 XDP_UMEM_TX_SW_CSUM = 0x2 XDP_UMEM_UNALIGNED_CHUNK_FLAG = 0x1 XDP_USE_NEED_WAKEUP = 0x8 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index 684a516..8aa6d77 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -153,9 +153,14 @@ const ( NFDBITS = 0x20 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index 61d74b5..da428f4 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -153,9 +153,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index a28c9e3..bf45bfe 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -150,9 +150,14 @@ const ( NFDBITS = 0x20 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index ab5d1fe..71c6716 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -154,9 +154,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go index c523090..9476628 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go @@ -154,9 +154,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go index 01e6ea7..b9e85f3 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -150,9 +150,14 @@ const ( NFDBITS = 0x20 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x2 ONLCR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go index 7aa610b..a48b68a 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -150,9 +150,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x2 ONLCR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go index 92af771..ea00e85 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -150,9 +150,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x2 ONLCR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go index b27ef5e..91c6468 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -150,9 +150,14 @@ const ( NFDBITS = 0x20 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x2 ONLCR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go index 237a2ce..8cbf38d 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go @@ -152,9 +152,14 @@ const ( NL3 = 0x300 NLDLY = 0x300 NOFLSH = 0x80000000 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x4 ONLCR = 0x2 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index 4a5c555..a2df734 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -152,9 +152,14 @@ const ( NL3 = 0x300 NLDLY = 0x300 NOFLSH = 0x80000000 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x4 ONLCR = 0x2 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index a02fb49..2479137 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -152,9 +152,14 @@ const ( NL3 = 0x300 NLDLY = 0x300 NOFLSH = 0x80000000 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x4 ONLCR = 0x2 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go index e26a7c6..d265f14 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go @@ -150,9 +150,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index c48f7c2..3f2d644 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -150,9 +150,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x8008b705 NS_GET_NSTYPE = 0xb703 NS_GET_OWNER_UID = 0xb704 NS_GET_PARENT = 0xb702 + NS_GET_PID_FROM_PIDNS = 0x8004b706 + NS_GET_PID_IN_PIDNS = 0x8004b708 + NS_GET_TGID_FROM_PIDNS = 0x8004b707 + NS_GET_TGID_IN_PIDNS = 0x8004b709 NS_GET_USERNS = 0xb701 OLCUC = 0x2 ONLCR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go index ad4b9aa..5d8b727 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go @@ -155,9 +155,14 @@ const ( NFDBITS = 0x40 NLDLY = 0x100 NOFLSH = 0x80 + NS_GET_MNTNS_ID = 0x4008b705 NS_GET_NSTYPE = 0x2000b703 NS_GET_OWNER_UID = 0x2000b704 NS_GET_PARENT = 0x2000b702 + NS_GET_PID_FROM_PIDNS = 0x4004b706 + NS_GET_PID_IN_PIDNS = 0x4004b708 + NS_GET_TGID_FROM_PIDNS = 0x4004b707 + NS_GET_TGID_IN_PIDNS = 0x4004b709 NS_GET_USERNS = 0x2000b701 OLCUC = 0x2 ONLCR = 0x4 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux.go b/vendor/golang.org/x/sys/unix/zsyscall_linux.go index 1bc1a5a..af30da5 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux.go @@ -971,23 +971,6 @@ func Getpriority(which int, who int) (prio int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getrandom(buf []byte, flags int) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go index d3e38f6..f485dbf 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go @@ -341,6 +341,7 @@ const ( SYS_STATX = 332 SYS_IO_PGETEVENTS = 333 SYS_RSEQ = 334 + SYS_URETPROBE = 335 SYS_PIDFD_SEND_SIGNAL = 424 SYS_IO_URING_SETUP = 425 SYS_IO_URING_ENTER = 426 diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go index 6c778c2..1893e2f 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go @@ -85,7 +85,7 @@ const ( SYS_SPLICE = 76 SYS_TEE = 77 SYS_READLINKAT = 78 - SYS_FSTATAT = 79 + SYS_NEWFSTATAT = 79 SYS_FSTAT = 80 SYS_SYNC = 81 SYS_FSYNC = 82 diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go index 37281cf..16a4017 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go @@ -84,6 +84,8 @@ const ( SYS_SPLICE = 76 SYS_TEE = 77 SYS_READLINKAT = 78 + SYS_NEWFSTATAT = 79 + SYS_FSTAT = 80 SYS_SYNC = 81 SYS_FSYNC = 82 SYS_FDATASYNC = 83 diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go index 9889f6a..a5459e7 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go @@ -84,7 +84,7 @@ const ( SYS_SPLICE = 76 SYS_TEE = 77 SYS_READLINKAT = 78 - SYS_FSTATAT = 79 + SYS_NEWFSTATAT = 79 SYS_FSTAT = 80 SYS_SYNC = 81 SYS_FSYNC = 82 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux.go b/vendor/golang.org/x/sys/unix/ztypes_linux.go index 9f2550d..3a69e45 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -87,31 +87,35 @@ type StatxTimestamp struct { } type Statx_t struct { - Mask uint32 - Blksize uint32 - Attributes uint64 - Nlink uint32 - Uid uint32 - Gid uint32 - Mode uint16 - _ [1]uint16 - Ino uint64 - Size uint64 - Blocks uint64 - Attributes_mask uint64 - Atime StatxTimestamp - Btime StatxTimestamp - Ctime StatxTimestamp - Mtime StatxTimestamp - Rdev_major uint32 - Rdev_minor uint32 - Dev_major uint32 - Dev_minor uint32 - Mnt_id uint64 - Dio_mem_align uint32 - Dio_offset_align uint32 - Subvol uint64 - _ [11]uint64 + Mask uint32 + Blksize uint32 + Attributes uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Mode uint16 + _ [1]uint16 + Ino uint64 + Size uint64 + Blocks uint64 + Attributes_mask uint64 + Atime StatxTimestamp + Btime StatxTimestamp + Ctime StatxTimestamp + Mtime StatxTimestamp + Rdev_major uint32 + Rdev_minor uint32 + Dev_major uint32 + Dev_minor uint32 + Mnt_id uint64 + Dio_mem_align uint32 + Dio_offset_align uint32 + Subvol uint64 + Atomic_write_unit_min uint32 + Atomic_write_unit_max uint32 + Atomic_write_segments_max uint32 + _ [1]uint32 + _ [9]uint64 } type Fsid struct { @@ -516,6 +520,29 @@ type TCPInfo struct { Total_rto_time uint32 } +type TCPVegasInfo struct { + Enabled uint32 + Rttcnt uint32 + Rtt uint32 + Minrtt uint32 +} + +type TCPDCTCPInfo struct { + Enabled uint16 + Ce_state uint16 + Alpha uint32 + Ab_ecn uint32 + Ab_tot uint32 +} + +type TCPBBRInfo struct { + Bw_lo uint32 + Bw_hi uint32 + Min_rtt uint32 + Pacing_gain uint32 + Cwnd_gain uint32 +} + type CanFilter struct { Id uint32 Mask uint32 @@ -557,6 +584,7 @@ const ( SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0xf8 + SizeofTCPCCInfo = 0x14 SizeofCanFilter = 0x8 SizeofTCPRepairOpt = 0x8 ) @@ -3766,7 +3794,7 @@ const ( ETHTOOL_MSG_PSE_GET = 0x24 ETHTOOL_MSG_PSE_SET = 0x25 ETHTOOL_MSG_RSS_GET = 0x26 - ETHTOOL_MSG_USER_MAX = 0x2b + ETHTOOL_MSG_USER_MAX = 0x2c ETHTOOL_MSG_KERNEL_NONE = 0x0 ETHTOOL_MSG_STRSET_GET_REPLY = 0x1 ETHTOOL_MSG_LINKINFO_GET_REPLY = 0x2 @@ -3806,7 +3834,7 @@ const ( ETHTOOL_MSG_MODULE_NTF = 0x24 ETHTOOL_MSG_PSE_GET_REPLY = 0x25 ETHTOOL_MSG_RSS_GET_REPLY = 0x26 - ETHTOOL_MSG_KERNEL_MAX = 0x2b + ETHTOOL_MSG_KERNEL_MAX = 0x2c ETHTOOL_FLAG_COMPACT_BITSETS = 0x1 ETHTOOL_FLAG_OMIT_REPLY = 0x2 ETHTOOL_FLAG_STATS = 0x4 @@ -3951,7 +3979,7 @@ const ( ETHTOOL_A_COALESCE_RATE_SAMPLE_INTERVAL = 0x17 ETHTOOL_A_COALESCE_USE_CQE_MODE_TX = 0x18 ETHTOOL_A_COALESCE_USE_CQE_MODE_RX = 0x19 - ETHTOOL_A_COALESCE_MAX = 0x1c + ETHTOOL_A_COALESCE_MAX = 0x1e ETHTOOL_A_PAUSE_UNSPEC = 0x0 ETHTOOL_A_PAUSE_HEADER = 0x1 ETHTOOL_A_PAUSE_AUTONEG = 0x2 @@ -4609,7 +4637,7 @@ const ( NL80211_ATTR_MAC_HINT = 0xc8 NL80211_ATTR_MAC_MASK = 0xd7 NL80211_ATTR_MAX_AP_ASSOC_STA = 0xca - NL80211_ATTR_MAX = 0x14a + NL80211_ATTR_MAX = 0x14c NL80211_ATTR_MAX_CRIT_PROT_DURATION = 0xb4 NL80211_ATTR_MAX_CSA_COUNTERS = 0xce NL80211_ATTR_MAX_MATCH_SETS = 0x85 @@ -5213,7 +5241,7 @@ const ( NL80211_FREQUENCY_ATTR_GO_CONCURRENT = 0xf NL80211_FREQUENCY_ATTR_INDOOR_ONLY = 0xe NL80211_FREQUENCY_ATTR_IR_CONCURRENT = 0xf - NL80211_FREQUENCY_ATTR_MAX = 0x20 + NL80211_FREQUENCY_ATTR_MAX = 0x21 NL80211_FREQUENCY_ATTR_MAX_TX_POWER = 0x6 NL80211_FREQUENCY_ATTR_NO_10MHZ = 0x11 NL80211_FREQUENCY_ATTR_NO_160MHZ = 0xc diff --git a/vendor/golang.org/x/sys/windows/dll_windows.go b/vendor/golang.org/x/sys/windows/dll_windows.go index 115341f..4e613cf 100644 --- a/vendor/golang.org/x/sys/windows/dll_windows.go +++ b/vendor/golang.org/x/sys/windows/dll_windows.go @@ -65,7 +65,7 @@ func LoadDLL(name string) (dll *DLL, err error) { return d, nil } -// MustLoadDLL is like LoadDLL but panics if load operation failes. +// MustLoadDLL is like LoadDLL but panics if load operation fails. func MustLoadDLL(name string) *DLL { d, e := LoadDLL(name) if e != nil { diff --git a/vendor/golang.org/x/sys/windows/mkerrors.bash b/vendor/golang.org/x/sys/windows/mkerrors.bash index 58e0188..0fc9c54 100644 --- a/vendor/golang.org/x/sys/windows/mkerrors.bash +++ b/vendor/golang.org/x/sys/windows/mkerrors.bash @@ -8,63 +8,69 @@ set -e shopt -s nullglob winerror="$(printf '%s\n' "/mnt/c/Program Files (x86)/Windows Kits/"/*/Include/*/shared/winerror.h | sort -Vr | head -n 1)" -[[ -n $winerror ]] || { echo "Unable to find winerror.h" >&2; exit 1; } +[[ -n $winerror ]] || { + echo "Unable to find winerror.h" >&2 + exit 1 +} ntstatus="$(printf '%s\n' "/mnt/c/Program Files (x86)/Windows Kits/"/*/Include/*/shared/ntstatus.h | sort -Vr | head -n 1)" -[[ -n $ntstatus ]] || { echo "Unable to find ntstatus.h" >&2; exit 1; } +[[ -n $ntstatus ]] || { + echo "Unable to find ntstatus.h" >&2 + exit 1 +} declare -A errors { - echo "// Code generated by 'mkerrors.bash'; DO NOT EDIT." - echo - echo "package windows" - echo "import \"syscall\"" - echo "const (" + echo "// Code generated by 'mkerrors.bash'; DO NOT EDIT." + echo + echo "package windows" + echo 'import "syscall"' + echo "const (" - while read -r line; do - unset vtype - if [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +([A-Z0-9_]+\()?([A-Z][A-Z0-9_]+k?)\)? ]]; then - key="${BASH_REMATCH[1]}" - value="${BASH_REMATCH[3]}" - elif [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +([A-Z0-9_]+\()?((0x)?[0-9A-Fa-f]+)L?\)? ]]; then - key="${BASH_REMATCH[1]}" - value="${BASH_REMATCH[3]}" - vtype="${BASH_REMATCH[2]}" - elif [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +\(\(([A-Z]+)\)((0x)?[0-9A-Fa-f]+)L?\) ]]; then - key="${BASH_REMATCH[1]}" - value="${BASH_REMATCH[3]}" - vtype="${BASH_REMATCH[2]}" - else - continue - fi - [[ -n $key && -n $value ]] || continue - [[ -z ${errors["$key"]} ]] || continue - errors["$key"]="$value" - if [[ -v vtype ]]; then - if [[ $key == FACILITY_* || $key == NO_ERROR ]]; then - vtype="" - elif [[ $vtype == *HANDLE* || $vtype == *HRESULT* ]]; then - vtype="Handle" - else - vtype="syscall.Errno" - fi - last_vtype="$vtype" - else - vtype="" - if [[ $last_vtype == Handle && $value == NO_ERROR ]]; then - value="S_OK" - elif [[ $last_vtype == syscall.Errno && $value == NO_ERROR ]]; then - value="ERROR_SUCCESS" - fi - fi + while read -r line; do + unset vtype + if [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +([A-Z0-9_]+\()?([A-Z][A-Z0-9_]+k?)\)? ]]; then + key="${BASH_REMATCH[1]}" + value="${BASH_REMATCH[3]}" + elif [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +([A-Z0-9_]+\()?((0x)?[0-9A-Fa-f]+)L?\)? ]]; then + key="${BASH_REMATCH[1]}" + value="${BASH_REMATCH[3]}" + vtype="${BASH_REMATCH[2]}" + elif [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +\(\(([A-Z]+)\)((0x)?[0-9A-Fa-f]+)L?\) ]]; then + key="${BASH_REMATCH[1]}" + value="${BASH_REMATCH[3]}" + vtype="${BASH_REMATCH[2]}" + else + continue + fi + [[ -n $key && -n $value ]] || continue + [[ -z ${errors["$key"]} ]] || continue + errors["$key"]="$value" + if [[ -v vtype ]]; then + if [[ $key == FACILITY_* || $key == NO_ERROR ]]; then + vtype="" + elif [[ $vtype == *HANDLE* || $vtype == *HRESULT* ]]; then + vtype="Handle" + else + vtype="syscall.Errno" + fi + last_vtype="$vtype" + else + vtype="" + if [[ $last_vtype == Handle && $value == NO_ERROR ]]; then + value="S_OK" + elif [[ $last_vtype == syscall.Errno && $value == NO_ERROR ]]; then + value="ERROR_SUCCESS" + fi + fi - echo "$key $vtype = $value" - done < "$winerror" + echo "$key $vtype = $value" + done <"$winerror" - while read -r line; do - [[ $line =~ ^#define\ (STATUS_[^\s]+)\ +\(\(NTSTATUS\)((0x)?[0-9a-fA-F]+)L?\) ]] || continue - echo "${BASH_REMATCH[1]} NTStatus = ${BASH_REMATCH[2]}" - done < "$ntstatus" + while read -r line; do + [[ $line =~ ^#define\ (STATUS_[^\s]+)\ +\(\(NTSTATUS\)((0x)?[0-9a-fA-F]+)L?\) ]] || continue + echo "${BASH_REMATCH[1]} NTStatus = ${BASH_REMATCH[2]}" + done <"$ntstatus" - echo ")" -} | gofmt > "zerrors_windows.go" + echo ")" +} | gofmt >"zerrors_windows.go" diff --git a/vendor/golang.org/x/sys/windows/mkknownfolderids.bash b/vendor/golang.org/x/sys/windows/mkknownfolderids.bash index ab8924e..7180da8 100644 --- a/vendor/golang.org/x/sys/windows/mkknownfolderids.bash +++ b/vendor/golang.org/x/sys/windows/mkknownfolderids.bash @@ -8,20 +8,23 @@ set -e shopt -s nullglob knownfolders="$(printf '%s\n' "/mnt/c/Program Files (x86)/Windows Kits/"/*/Include/*/um/KnownFolders.h | sort -Vr | head -n 1)" -[[ -n $knownfolders ]] || { echo "Unable to find KnownFolders.h" >&2; exit 1; } +[[ -n $knownfolders ]] || { + echo "Unable to find KnownFolders.h" >&2 + exit 1 +} { - echo "// Code generated by 'mkknownfolderids.bash'; DO NOT EDIT." - echo - echo "package windows" - echo "type KNOWNFOLDERID GUID" - echo "var (" - while read -r line; do - [[ $line =~ DEFINE_KNOWN_FOLDER\((FOLDERID_[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+)\) ]] || continue - printf "%s = &KNOWNFOLDERID{0x%08x, 0x%04x, 0x%04x, [8]byte{0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x}}\n" \ - "${BASH_REMATCH[1]}" $(( "${BASH_REMATCH[2]}" )) $(( "${BASH_REMATCH[3]}" )) $(( "${BASH_REMATCH[4]}" )) \ - $(( "${BASH_REMATCH[5]}" )) $(( "${BASH_REMATCH[6]}" )) $(( "${BASH_REMATCH[7]}" )) $(( "${BASH_REMATCH[8]}" )) \ - $(( "${BASH_REMATCH[9]}" )) $(( "${BASH_REMATCH[10]}" )) $(( "${BASH_REMATCH[11]}" )) $(( "${BASH_REMATCH[12]}" )) - done < "$knownfolders" - echo ")" -} | gofmt > "zknownfolderids_windows.go" + echo "// Code generated by 'mkknownfolderids.bash'; DO NOT EDIT." + echo + echo "package windows" + echo "type KNOWNFOLDERID GUID" + echo "var (" + while read -r line; do + [[ $line =~ DEFINE_KNOWN_FOLDER\((FOLDERID_[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+),[\t\ ]*(0x[^,]+)\) ]] || continue + printf "%s = &KNOWNFOLDERID{0x%08x, 0x%04x, 0x%04x, [8]byte{0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x}}\n" \ + "${BASH_REMATCH[1]}" $(("${BASH_REMATCH[2]}")) $(("${BASH_REMATCH[3]}")) $(("${BASH_REMATCH[4]}")) \ + $(("${BASH_REMATCH[5]}")) $(("${BASH_REMATCH[6]}")) $(("${BASH_REMATCH[7]}")) $(("${BASH_REMATCH[8]}")) \ + $(("${BASH_REMATCH[9]}")) $(("${BASH_REMATCH[10]}")) $(("${BASH_REMATCH[11]}")) $(("${BASH_REMATCH[12]}")) + done <"$knownfolders" + echo ")" +} | gofmt >"zknownfolderids_windows.go" diff --git a/vendor/modules.txt b/vendor/modules.txt index 0e8b253..0e47d6e 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -8,7 +8,7 @@ github.com/fsnotify/fsnotify ## explicit; go 1.14 github.com/go-chi/chi/v5 github.com/go-chi/chi/v5/middleware -# github.com/go-viper/mapstructure/v2 v2.1.0 +# github.com/go-viper/mapstructure/v2 v2.2.1 ## explicit; go 1.18 github.com/go-viper/mapstructure/v2 github.com/go-viper/mapstructure/v2/internal/errors @@ -27,40 +27,24 @@ github.com/knadh/koanf/parsers/yaml # github.com/knadh/koanf/providers/confmap v0.1.0 ## explicit; go 1.18 github.com/knadh/koanf/providers/confmap -# github.com/knadh/koanf/providers/env v0.1.0 +# github.com/knadh/koanf/providers/env v1.0.0 ## explicit; go 1.18 github.com/knadh/koanf/providers/env -# github.com/knadh/koanf/providers/file v1.1.0 +# github.com/knadh/koanf/providers/file v1.1.2 ## explicit; go 1.18 github.com/knadh/koanf/providers/file # github.com/knadh/koanf/v2 v2.1.1 ## explicit; go 1.18 github.com/knadh/koanf/v2 -# github.com/mattn/go-colorable v0.1.13 -## explicit; go 1.15 -github.com/mattn/go-colorable -# github.com/mattn/go-isatty v0.0.20 -## explicit; go 1.15 -github.com/mattn/go-isatty # github.com/mitchellh/copystructure v1.2.0 ## explicit; go 1.15 github.com/mitchellh/copystructure # github.com/mitchellh/reflectwalk v1.0.2 ## explicit github.com/mitchellh/reflectwalk -# github.com/pkg/errors v0.9.1 -## explicit -github.com/pkg/errors # github.com/pmezard/go-difflib v1.0.0 ## explicit github.com/pmezard/go-difflib/difflib -# github.com/rs/zerolog v1.33.0 -## explicit; go 1.15 -github.com/rs/zerolog -github.com/rs/zerolog/internal/cbor -github.com/rs/zerolog/internal/json -github.com/rs/zerolog/log -github.com/rs/zerolog/pkgerrors # github.com/stretchr/objx v0.5.2 ## explicit; go 1.20 github.com/stretchr/objx @@ -69,7 +53,7 @@ github.com/stretchr/objx github.com/stretchr/testify/assert github.com/stretchr/testify/mock github.com/stretchr/testify/require -# golang.org/x/sys v0.25.0 +# golang.org/x/sys v0.26.0 ## explicit; go 1.18 golang.org/x/sys/unix golang.org/x/sys/windows