mirror of
https://github.com/wahyd4/say-it-backend.git
synced 2026-08-08 21:07:38 +10:00
@@ -0,0 +1,41 @@
|
|||||||
|
# This is a basic workflow to help you get started with Actions
|
||||||
|
|
||||||
|
name: ci
|
||||||
|
|
||||||
|
# Controls when the action will run. Triggers the workflow on push or pull request
|
||||||
|
# events but only for the master branch
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ master ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ master ]
|
||||||
|
|
||||||
|
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
|
||||||
|
jobs:
|
||||||
|
# This workflow contains a single job called "build"
|
||||||
|
ci:
|
||||||
|
# The type of runner that the job will run on
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
# Steps represent a sequence of tasks that will be executed as part of the job
|
||||||
|
steps:
|
||||||
|
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Build and push backend docker image
|
||||||
|
run: |
|
||||||
|
docker build . --tag docker.pkg.github.com/wahyd4/say-it-backend/say-it:v0.1.$GITHUB_RUN_NUMBER
|
||||||
|
docker login docker.pkg.github.com -u wahyd4 -p ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
docker push docker.pkg.github.com/wahyd4/say-it-backend/say-it:v0.1.$GITHUB_RUN_NUMBER
|
||||||
|
- name: deploy deployment to cluster
|
||||||
|
uses: wahyd4/kubectl-helm-action@master
|
||||||
|
env:
|
||||||
|
KUBE_CONFIG_DATA: ${{ secrets.KUBE_CONFIG_DATA }}
|
||||||
|
with:
|
||||||
|
args: |
|
||||||
|
set -e
|
||||||
|
IMAGE_VERSION=v0.1.$GITHUB_RUN_NUMBER
|
||||||
|
rm -rf tmp && mkdir tmp
|
||||||
|
cat manifest.yaml | sed "s/{{IMAGE_VERSION}}/${IMAGE_VERSION}/g" > tmp/manifest.yaml
|
||||||
|
kubectl apply -f tmp/manifest.yaml -n apps
|
||||||
|
rm -rf tmp
|
||||||
+3
-1
@@ -1,2 +1,4 @@
|
|||||||
token.json
|
token.json
|
||||||
|
.vscode
|
||||||
|
say-it-backend
|
||||||
|
vendor
|
||||||
|
|||||||
+15
-9
@@ -1,20 +1,26 @@
|
|||||||
FROM golang:1.8-alpine3.6
|
FROM golang:1.15-alpine AS build
|
||||||
|
|
||||||
|
RUN apk add --no-cache git openssh
|
||||||
|
|
||||||
|
ENV GOOS=linux
|
||||||
|
ENV GOARCH=amd64
|
||||||
|
|
||||||
# RUN apt-get update && apt-get install -y ca-certificates
|
WORKDIR /app
|
||||||
|
|
||||||
COPY say-it-backend /root/
|
COPY . .
|
||||||
|
|
||||||
EXPOSE 8080
|
|
||||||
|
|
||||||
CMD chmod +x /root/say-it-backend
|
|
||||||
|
|
||||||
ENTRYPOINT /root/say-it-backend
|
|
||||||
|
|
||||||
|
RUN go mod download
|
||||||
|
RUN go build -o say-it main.go
|
||||||
|
|
||||||
|
FROM alpine:3.12
|
||||||
|
|
||||||
|
RUN apk add --no-cache bash \
|
||||||
|
&& adduser -D -u 1000 junv
|
||||||
|
|
||||||
|
WORKDIR /home/junv
|
||||||
|
|
||||||
|
USER junv
|
||||||
|
|
||||||
|
COPY --from=build /app/say-it say-it
|
||||||
|
|
||||||
|
CMD ["/home/junv/say-it"]
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
module github.com/wahyd4/say-it-backend
|
||||||
|
|
||||||
|
go 1.15
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/Sirupsen/logrus v0.11.0 // indirect
|
||||||
|
github.com/gin-gonic/gin v1.6.3
|
||||||
|
github.com/sirupsen/logrus v1.7.0
|
||||||
|
gopkg.in/gin-gonic/gin.v1 v1.1.4 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
github.com/Sirupsen/logrus v0.11.0/go.mod h1:rmk17hk6i8ZSAJkSDa7nOxamrG+SP4P0mm+DAvExv4U=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||||
|
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||||
|
github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
|
||||||
|
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
|
||||||
|
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||||
|
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
|
||||||
|
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
|
||||||
|
github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no=
|
||||||
|
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
|
||||||
|
github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY=
|
||||||
|
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
|
||||||
|
github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
|
||||||
|
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||||
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
|
github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
|
||||||
|
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||||
|
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
|
||||||
|
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
|
||||||
|
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
|
||||||
|
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
|
||||||
|
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM=
|
||||||
|
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
|
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
|
||||||
|
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
|
||||||
|
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
|
||||||
|
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
|
||||||
|
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg=
|
||||||
|
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/gin-gonic/gin.v1 v1.1.4/go.mod h1:Eljh74A/zAvUOQ835v6ySeZ+5gQG6tKjbZTaZ9iWU3A=
|
||||||
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||||
|
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
@@ -10,8 +10,8 @@ import (
|
|||||||
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
|
||||||
log "github.com/Sirupsen/logrus"
|
"github.com/gin-gonic/gin"
|
||||||
"gopkg.in/gin-gonic/gin.v1"
|
log "github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Token struct {
|
type Token struct {
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: say-it
|
||||||
|
spec:
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app: say-it
|
||||||
|
replicas: 1
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app: say-it
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: say-it
|
||||||
|
image: "docker.pkg.github.com/wahyd4/say-it-backend/say-it:{{IMAGE_VERSION}}"
|
||||||
|
securityContext:
|
||||||
|
runAsUser: 1000
|
||||||
|
imagePullPolicy: Always
|
||||||
|
env:
|
||||||
|
- name: CLIENT_ID
|
||||||
|
valueFrom:
|
||||||
|
{ secretKeyRef: { name: say-it-credentials, key: clientId } }
|
||||||
|
- name: CLIENT_SECRET
|
||||||
|
valueFrom:
|
||||||
|
{ secretKeyRef: { name: say-it-credentials, key: clientSecret } }
|
||||||
|
ports:
|
||||||
|
- containerPort: 8080
|
||||||
|
name: say-it-port
|
||||||
|
protocol: TCP
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 20m
|
||||||
|
memory: 32Mi
|
||||||
|
limits:
|
||||||
|
cpu: 50m
|
||||||
|
memory: 128Mi
|
||||||
|
imagePullSecrets:
|
||||||
|
- name: regcred
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: say-it
|
||||||
|
labels:
|
||||||
|
app: say-it
|
||||||
|
spec:
|
||||||
|
type: ClusterIP
|
||||||
|
ports:
|
||||||
|
- port: 80
|
||||||
|
targetPort: say-it-port
|
||||||
|
protocol: TCP
|
||||||
|
name: web
|
||||||
|
selector:
|
||||||
|
app: say-it
|
||||||
|
|
||||||
|
---
|
||||||
|
apiVersion: networking.k8s.io/v1beta1
|
||||||
|
kind: Ingress
|
||||||
|
metadata:
|
||||||
|
name: say-it-ingress
|
||||||
|
annotations:
|
||||||
|
kubernetes.io/ingress.class: "nginx"
|
||||||
|
kubernetes.io/tls-acme: "true"
|
||||||
|
cert-manager.io/cluster-issuer: "letsencrypt-prod"
|
||||||
|
spec:
|
||||||
|
tls:
|
||||||
|
- hosts:
|
||||||
|
- say-it.home.toozhao.com
|
||||||
|
secretName: say-it-tls
|
||||||
|
rules:
|
||||||
|
- host: say-it.home.toozhao.com
|
||||||
|
http:
|
||||||
|
paths:
|
||||||
|
- path: /
|
||||||
|
pathType: Prefix
|
||||||
|
backend:
|
||||||
|
serviceName: say-it
|
||||||
|
servicePort: 80
|
||||||
|
|
||||||
|
# ---
|
||||||
|
# apiVersion: monitoring.coreos.com/v1
|
||||||
|
# kind: ServiceMonitor
|
||||||
|
# metadata:
|
||||||
|
# name: say-it
|
||||||
|
# labels:
|
||||||
|
# app: say-it
|
||||||
|
# release: prometheus # this can make the service monitor be discovered by prometheus
|
||||||
|
# spec:
|
||||||
|
# namespaceSelector:
|
||||||
|
# matchNames:
|
||||||
|
# - apps
|
||||||
|
# selector:
|
||||||
|
# matchLabels:
|
||||||
|
# app: say-it
|
||||||
|
# endpoints:
|
||||||
|
# - port: metrics-port
|
||||||
|
# interval: 30s
|
||||||
-66
@@ -1,66 +0,0 @@
|
|||||||
# 0.10.0
|
|
||||||
|
|
||||||
* feature: Add a test hook (#180)
|
|
||||||
* feature: `ParseLevel` is now case-insensitive (#326)
|
|
||||||
* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308)
|
|
||||||
* performance: avoid re-allocations on `WithFields` (#335)
|
|
||||||
|
|
||||||
# 0.9.0
|
|
||||||
|
|
||||||
* logrus/text_formatter: don't emit empty msg
|
|
||||||
* logrus/hooks/airbrake: move out of main repository
|
|
||||||
* logrus/hooks/sentry: move out of main repository
|
|
||||||
* logrus/hooks/papertrail: move out of main repository
|
|
||||||
* logrus/hooks/bugsnag: move out of main repository
|
|
||||||
* logrus/core: run tests with `-race`
|
|
||||||
* logrus/core: detect TTY based on `stderr`
|
|
||||||
* logrus/core: support `WithError` on logger
|
|
||||||
* logrus/core: Solaris support
|
|
||||||
|
|
||||||
# 0.8.7
|
|
||||||
|
|
||||||
* logrus/core: fix possible race (#216)
|
|
||||||
* logrus/doc: small typo fixes and doc improvements
|
|
||||||
|
|
||||||
|
|
||||||
# 0.8.6
|
|
||||||
|
|
||||||
* hooks/raven: allow passing an initialized client
|
|
||||||
|
|
||||||
# 0.8.5
|
|
||||||
|
|
||||||
* logrus/core: revert #208
|
|
||||||
|
|
||||||
# 0.8.4
|
|
||||||
|
|
||||||
* formatter/text: fix data race (#218)
|
|
||||||
|
|
||||||
# 0.8.3
|
|
||||||
|
|
||||||
* logrus/core: fix entry log level (#208)
|
|
||||||
* logrus/core: improve performance of text formatter by 40%
|
|
||||||
* logrus/core: expose `LevelHooks` type
|
|
||||||
* logrus/core: add support for DragonflyBSD and NetBSD
|
|
||||||
* formatter/text: print structs more verbosely
|
|
||||||
|
|
||||||
# 0.8.2
|
|
||||||
|
|
||||||
* logrus: fix more Fatal family functions
|
|
||||||
|
|
||||||
# 0.8.1
|
|
||||||
|
|
||||||
* logrus: fix not exiting on `Fatalf` and `Fatalln`
|
|
||||||
|
|
||||||
# 0.8.0
|
|
||||||
|
|
||||||
* logrus: defaults to stderr instead of stdout
|
|
||||||
* hooks/sentry: add special field for `*http.Request`
|
|
||||||
* formatter/text: ignore Windows for colors
|
|
||||||
|
|
||||||
# 0.7.3
|
|
||||||
|
|
||||||
* formatter/\*: allow configuration of timestamp layout
|
|
||||||
|
|
||||||
# 0.7.2
|
|
||||||
|
|
||||||
* formatter/text: Add configuration option for time format (#158)
|
|
||||||
-21
@@ -1,21 +0,0 @@
|
|||||||
The MIT License (MIT)
|
|
||||||
|
|
||||||
Copyright (c) 2014 Simon Eskildsen
|
|
||||||
|
|
||||||
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.
|
|
||||||
-425
@@ -1,425 +0,0 @@
|
|||||||
# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/> [](https://travis-ci.org/Sirupsen/logrus) [](https://godoc.org/github.com/Sirupsen/logrus)
|
|
||||||
|
|
||||||
Logrus is a structured logger for Go (golang), completely API compatible with
|
|
||||||
the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not
|
|
||||||
yet stable (pre 1.0). Logrus itself is completely stable and has been used in
|
|
||||||
many large deployments. The core API is unlikely to change much but please
|
|
||||||
version control your Logrus to make sure you aren't fetching latest `master` on
|
|
||||||
every build.**
|
|
||||||
|
|
||||||
Nicely color-coded in development (when a TTY is attached, otherwise just
|
|
||||||
plain text):
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash
|
|
||||||
or Splunk:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
|
|
||||||
ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
|
|
||||||
|
|
||||||
{"level":"warning","msg":"The group's number increased tremendously!",
|
|
||||||
"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
|
|
||||||
|
|
||||||
{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
|
|
||||||
"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
|
|
||||||
|
|
||||||
{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
|
|
||||||
"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
|
|
||||||
|
|
||||||
{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
|
|
||||||
"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
|
|
||||||
```
|
|
||||||
|
|
||||||
With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not
|
|
||||||
attached, the output is compatible with the
|
|
||||||
[logfmt](http://godoc.org/github.com/kr/logfmt) format:
|
|
||||||
|
|
||||||
```text
|
|
||||||
time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
|
|
||||||
time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
|
|
||||||
time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
|
|
||||||
time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
|
|
||||||
time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
|
|
||||||
time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
|
|
||||||
exit status 1
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Example
|
|
||||||
|
|
||||||
The simplest way to use Logrus is simply the package-level exported logger:
|
|
||||||
|
|
||||||
```go
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
log "github.com/Sirupsen/logrus"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"animal": "walrus",
|
|
||||||
}).Info("A walrus appears")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Note that it's completely api-compatible with the stdlib logger, so you can
|
|
||||||
replace your `log` imports everywhere with `log "github.com/Sirupsen/logrus"`
|
|
||||||
and you'll now have the flexibility of Logrus. You can customize it all you
|
|
||||||
want:
|
|
||||||
|
|
||||||
```go
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
log "github.com/Sirupsen/logrus"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
// Log as JSON instead of the default ASCII formatter.
|
|
||||||
log.SetFormatter(&log.JSONFormatter{})
|
|
||||||
|
|
||||||
// Output to stderr instead of stdout, could also be a file.
|
|
||||||
log.SetOutput(os.Stderr)
|
|
||||||
|
|
||||||
// Only log the warning severity or above.
|
|
||||||
log.SetLevel(log.WarnLevel)
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"animal": "walrus",
|
|
||||||
"size": 10,
|
|
||||||
}).Info("A group of walrus emerges from the ocean")
|
|
||||||
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"omg": true,
|
|
||||||
"number": 122,
|
|
||||||
}).Warn("The group's number increased tremendously!")
|
|
||||||
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"omg": true,
|
|
||||||
"number": 100,
|
|
||||||
}).Fatal("The ice breaks!")
|
|
||||||
|
|
||||||
// A common pattern is to re-use fields between logging statements by re-using
|
|
||||||
// the logrus.Entry returned from WithFields()
|
|
||||||
contextLogger := log.WithFields(log.Fields{
|
|
||||||
"common": "this is a common field",
|
|
||||||
"other": "I also should be logged always",
|
|
||||||
})
|
|
||||||
|
|
||||||
contextLogger.Info("I'll be logged with common and other field")
|
|
||||||
contextLogger.Info("Me too")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
For more advanced usage such as logging to multiple locations from the same
|
|
||||||
application, you can also create an instance of the `logrus` Logger:
|
|
||||||
|
|
||||||
```go
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/Sirupsen/logrus"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Create a new instance of the logger. You can have any number of instances.
|
|
||||||
var log = logrus.New()
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
// The API for setting attributes is a little different than the package level
|
|
||||||
// exported logger. See Godoc.
|
|
||||||
log.Out = os.Stderr
|
|
||||||
|
|
||||||
log.WithFields(logrus.Fields{
|
|
||||||
"animal": "walrus",
|
|
||||||
"size": 10,
|
|
||||||
}).Info("A group of walrus emerges from the ocean")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Fields
|
|
||||||
|
|
||||||
Logrus encourages careful, structured logging though logging fields instead of
|
|
||||||
long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
|
|
||||||
to send event %s to topic %s with key %d")`, you should log the much more
|
|
||||||
discoverable:
|
|
||||||
|
|
||||||
```go
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"event": event,
|
|
||||||
"topic": topic,
|
|
||||||
"key": key,
|
|
||||||
}).Fatal("Failed to send event")
|
|
||||||
```
|
|
||||||
|
|
||||||
We've found this API forces you to think about logging in a way that produces
|
|
||||||
much more useful logging messages. We've been in countless situations where just
|
|
||||||
a single added field to a log statement that was already there would've saved us
|
|
||||||
hours. The `WithFields` call is optional.
|
|
||||||
|
|
||||||
In general, with Logrus using any of the `printf`-family functions should be
|
|
||||||
seen as a hint you should add a field, however, you can still use the
|
|
||||||
`printf`-family functions with Logrus.
|
|
||||||
|
|
||||||
#### Hooks
|
|
||||||
|
|
||||||
You can add hooks for logging levels. For example to send errors to an exception
|
|
||||||
tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
|
|
||||||
multiple places simultaneously, e.g. syslog.
|
|
||||||
|
|
||||||
Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
|
|
||||||
`init`:
|
|
||||||
|
|
||||||
```go
|
|
||||||
import (
|
|
||||||
log "github.com/Sirupsen/logrus"
|
|
||||||
"gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake"
|
|
||||||
logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog"
|
|
||||||
"log/syslog"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
|
|
||||||
// Use the Airbrake hook to report errors that have Error severity or above to
|
|
||||||
// an exception tracker. You can create custom hooks, see the Hooks section.
|
|
||||||
log.AddHook(airbrake.NewHook(123, "xyz", "production"))
|
|
||||||
|
|
||||||
hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
|
|
||||||
if err != nil {
|
|
||||||
log.Error("Unable to connect to local syslog daemon")
|
|
||||||
} else {
|
|
||||||
log.AddHook(hook)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
|
|
||||||
|
|
||||||
| Hook | Description |
|
|
||||||
| ----- | ----------- |
|
|
||||||
| [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. |
|
|
||||||
| [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. |
|
|
||||||
| [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. |
|
|
||||||
| [Syslog](https://github.com/Sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. |
|
|
||||||
| [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. |
|
|
||||||
| [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. |
|
|
||||||
| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. |
|
|
||||||
| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) |
|
|
||||||
| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. |
|
|
||||||
| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` |
|
|
||||||
| [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) |
|
|
||||||
| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) |
|
|
||||||
| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem |
|
|
||||||
| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger |
|
|
||||||
| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail |
|
|
||||||
| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar |
|
|
||||||
| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd |
|
|
||||||
| [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb |
|
|
||||||
| [Influxus] (http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB] (http://influxdata.com/) |
|
|
||||||
| [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb |
|
|
||||||
| [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit |
|
|
||||||
| [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic |
|
|
||||||
| [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) |
|
|
||||||
| [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) |
|
|
||||||
| [KafkaLogrus](https://github.com/goibibo/KafkaLogrus) | Hook for logging to kafka |
|
|
||||||
| [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) |
|
|
||||||
| [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch|
|
|
||||||
| [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)|
|
|
||||||
| [Scribe](https://github.com/sagar8192/logrus-scribe-hook) | Hook for logging to [Scribe](https://github.com/facebookarchive/scribe)|
|
|
||||||
| [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) |
|
|
||||||
| [logz.io](https://github.com/ripcurld00d/logrus-logzio-hook) | Hook for logging to [logz.io](https://logz.io), a Log as a Service using Logstash |
|
|
||||||
| [Logmatic.io](https://github.com/logmatic/logmatic-go) | Hook for logging to [Logmatic.io](http://logmatic.io/) |
|
|
||||||
| [Pushover](https://github.com/toorop/logrus_pushover) | Send error via [Pushover](https://pushover.net) |
|
|
||||||
|
|
||||||
|
|
||||||
#### Level logging
|
|
||||||
|
|
||||||
Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic.
|
|
||||||
|
|
||||||
```go
|
|
||||||
log.Debug("Useful debugging information.")
|
|
||||||
log.Info("Something noteworthy happened!")
|
|
||||||
log.Warn("You should probably take a look at this.")
|
|
||||||
log.Error("Something failed but I'm not quitting.")
|
|
||||||
// Calls os.Exit(1) after logging
|
|
||||||
log.Fatal("Bye.")
|
|
||||||
// Calls panic() after logging
|
|
||||||
log.Panic("I'm bailing.")
|
|
||||||
```
|
|
||||||
|
|
||||||
You can set the logging level on a `Logger`, then it will only log entries with
|
|
||||||
that severity or anything above it:
|
|
||||||
|
|
||||||
```go
|
|
||||||
// Will log anything that is info or above (warn, error, fatal, panic). Default.
|
|
||||||
log.SetLevel(log.InfoLevel)
|
|
||||||
```
|
|
||||||
|
|
||||||
It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
|
|
||||||
environment if your application has that.
|
|
||||||
|
|
||||||
#### Entries
|
|
||||||
|
|
||||||
Besides the fields added with `WithField` or `WithFields` some fields are
|
|
||||||
automatically added to all logging events:
|
|
||||||
|
|
||||||
1. `time`. The timestamp when the entry was created.
|
|
||||||
2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
|
|
||||||
the `AddFields` call. E.g. `Failed to send event.`
|
|
||||||
3. `level`. The logging level. E.g. `info`.
|
|
||||||
|
|
||||||
#### Environments
|
|
||||||
|
|
||||||
Logrus has no notion of environment.
|
|
||||||
|
|
||||||
If you wish for hooks and formatters to only be used in specific environments,
|
|
||||||
you should handle that yourself. For example, if your application has a global
|
|
||||||
variable `Environment`, which is a string representation of the environment you
|
|
||||||
could do:
|
|
||||||
|
|
||||||
```go
|
|
||||||
import (
|
|
||||||
log "github.com/Sirupsen/logrus"
|
|
||||||
)
|
|
||||||
|
|
||||||
init() {
|
|
||||||
// do something here to set environment depending on an environment variable
|
|
||||||
// or command-line flag
|
|
||||||
if Environment == "production" {
|
|
||||||
log.SetFormatter(&log.JSONFormatter{})
|
|
||||||
} else {
|
|
||||||
// The TextFormatter is default, you don't actually have to do this.
|
|
||||||
log.SetFormatter(&log.TextFormatter{})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
This configuration is how `logrus` was intended to be used, but JSON in
|
|
||||||
production is mostly only useful if you do log aggregation with tools like
|
|
||||||
Splunk or Logstash.
|
|
||||||
|
|
||||||
#### Formatters
|
|
||||||
|
|
||||||
The built-in logging formatters are:
|
|
||||||
|
|
||||||
* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
|
|
||||||
without colors.
|
|
||||||
* *Note:* to force colored output when there is no TTY, set the `ForceColors`
|
|
||||||
field to `true`. To force no colored output even if there is a TTY set the
|
|
||||||
`DisableColors` field to `true`
|
|
||||||
* `logrus.JSONFormatter`. Logs fields as JSON.
|
|
||||||
|
|
||||||
Third party logging formatters:
|
|
||||||
|
|
||||||
* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
|
|
||||||
* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
|
|
||||||
* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦.
|
|
||||||
|
|
||||||
You can define your formatter by implementing the `Formatter` interface,
|
|
||||||
requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
|
|
||||||
`Fields` type (`map[string]interface{}`) with all your fields as well as the
|
|
||||||
default ones (see Entries section above):
|
|
||||||
|
|
||||||
```go
|
|
||||||
type MyJSONFormatter struct {
|
|
||||||
}
|
|
||||||
|
|
||||||
log.SetFormatter(new(MyJSONFormatter))
|
|
||||||
|
|
||||||
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
|
|
||||||
// Note this doesn't include Time, Level and Message which are available on
|
|
||||||
// the Entry. Consult `godoc` on information about those fields or read the
|
|
||||||
// source of the official loggers.
|
|
||||||
serialized, err := json.Marshal(entry.Data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
|
|
||||||
}
|
|
||||||
return append(serialized, '\n'), nil
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Logger as an `io.Writer`
|
|
||||||
|
|
||||||
Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
|
|
||||||
|
|
||||||
```go
|
|
||||||
w := logger.Writer()
|
|
||||||
defer w.Close()
|
|
||||||
|
|
||||||
srv := http.Server{
|
|
||||||
// create a stdlib log.Logger that writes to
|
|
||||||
// logrus.Logger.
|
|
||||||
ErrorLog: log.New(w, "", 0),
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Each line written to that writer will be printed the usual way, using formatters
|
|
||||||
and hooks. The level for those entries is `info`.
|
|
||||||
|
|
||||||
#### Rotation
|
|
||||||
|
|
||||||
Log rotation is not provided with Logrus. Log rotation should be done by an
|
|
||||||
external program (like `logrotate(8)`) that can compress and delete old log
|
|
||||||
entries. It should not be a feature of the application-level logger.
|
|
||||||
|
|
||||||
#### Tools
|
|
||||||
|
|
||||||
| Tool | Description |
|
|
||||||
| ---- | ----------- |
|
|
||||||
|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.|
|
|
||||||
|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper arround Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) |
|
|
||||||
|
|
||||||
#### Testing
|
|
||||||
|
|
||||||
Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
|
|
||||||
|
|
||||||
* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook
|
|
||||||
* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
|
|
||||||
|
|
||||||
```go
|
|
||||||
logger, hook := NewNullLogger()
|
|
||||||
logger.Error("Hello error")
|
|
||||||
|
|
||||||
assert.Equal(1, len(hook.Entries))
|
|
||||||
assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
|
|
||||||
assert.Equal("Hello error", hook.LastEntry().Message)
|
|
||||||
|
|
||||||
hook.Reset()
|
|
||||||
assert.Nil(hook.LastEntry())
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Fatal handlers
|
|
||||||
|
|
||||||
Logrus can register one or more functions that will be called when any `fatal`
|
|
||||||
level message is logged. The registered handlers will be executed before
|
|
||||||
logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need
|
|
||||||
to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
|
|
||||||
|
|
||||||
```
|
|
||||||
...
|
|
||||||
handler := func() {
|
|
||||||
// gracefully shutdown something...
|
|
||||||
}
|
|
||||||
logrus.RegisterExitHandler(handler)
|
|
||||||
...
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Thread safty
|
|
||||||
|
|
||||||
By default Logger is protected by mutex for concurrent writes, this mutex is invoked when calling hooks and writing logs.
|
|
||||||
If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.
|
|
||||||
|
|
||||||
Situation when locking is not needed includes:
|
|
||||||
|
|
||||||
* You have no hooks registered, or hooks calling is already thread-safe.
|
|
||||||
|
|
||||||
* Writing to logger.Out is already thread-safe, for example:
|
|
||||||
|
|
||||||
1) logger.Out is protected by locks.
|
|
||||||
|
|
||||||
2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing)
|
|
||||||
|
|
||||||
(Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)
|
|
||||||
-64
@@ -1,64 +0,0 @@
|
|||||||
package logrus
|
|
||||||
|
|
||||||
// The following code was sourced and modified from the
|
|
||||||
// https://bitbucket.org/tebeka/atexit package governed by the following license:
|
|
||||||
//
|
|
||||||
// Copyright (c) 2012 Miki Tebeka <miki.tebeka@gmail.com>.
|
|
||||||
//
|
|
||||||
// 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.
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
)
|
|
||||||
|
|
||||||
var handlers = []func(){}
|
|
||||||
|
|
||||||
func runHandler(handler func()) {
|
|
||||||
defer func() {
|
|
||||||
if err := recover(); err != nil {
|
|
||||||
fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
handler()
|
|
||||||
}
|
|
||||||
|
|
||||||
func runHandlers() {
|
|
||||||
for _, handler := range handlers {
|
|
||||||
runHandler(handler)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
|
|
||||||
func Exit(code int) {
|
|
||||||
runHandlers()
|
|
||||||
os.Exit(code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke
|
|
||||||
// all handlers. The handlers will also be invoked when any Fatal log entry is
|
|
||||||
// made.
|
|
||||||
//
|
|
||||||
// This method is useful when a caller wishes to use logrus to log a fatal
|
|
||||||
// message but also needs to gracefully shutdown. An example usecase could be
|
|
||||||
// closing database connections, or sending a alert that the application is
|
|
||||||
// closing.
|
|
||||||
func RegisterExitHandler(handler func()) {
|
|
||||||
handlers = append(handlers, handler)
|
|
||||||
}
|
|
||||||
-26
@@ -1,26 +0,0 @@
|
|||||||
/*
|
|
||||||
Package logrus is a structured logger for Go, completely API compatible with the standard library logger.
|
|
||||||
|
|
||||||
|
|
||||||
The simplest way to use Logrus is simply the package-level exported logger:
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
log "github.com/Sirupsen/logrus"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"animal": "walrus",
|
|
||||||
"number": 1,
|
|
||||||
"size": 10,
|
|
||||||
}).Info("A walrus appears")
|
|
||||||
}
|
|
||||||
|
|
||||||
Output:
|
|
||||||
time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10
|
|
||||||
|
|
||||||
For a full guide visit https://github.com/Sirupsen/logrus
|
|
||||||
*/
|
|
||||||
package logrus
|
|
||||||
-275
@@ -1,275 +0,0 @@
|
|||||||
package logrus
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
var bufferPool *sync.Pool
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
bufferPool = &sync.Pool{
|
|
||||||
New: func() interface{} {
|
|
||||||
return new(bytes.Buffer)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Defines the key when adding errors using WithError.
|
|
||||||
var ErrorKey = "error"
|
|
||||||
|
|
||||||
// An entry is the final or intermediate Logrus logging entry. It contains all
|
|
||||||
// the fields passed with WithField{,s}. It's finally logged when Debug, Info,
|
|
||||||
// Warn, Error, Fatal or Panic is called on it. These objects can be reused and
|
|
||||||
// passed around as much as you wish to avoid field duplication.
|
|
||||||
type Entry struct {
|
|
||||||
Logger *Logger
|
|
||||||
|
|
||||||
// Contains all the fields set by the user.
|
|
||||||
Data Fields
|
|
||||||
|
|
||||||
// Time at which the log entry was created
|
|
||||||
Time time.Time
|
|
||||||
|
|
||||||
// Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic
|
|
||||||
Level Level
|
|
||||||
|
|
||||||
// Message passed to Debug, Info, Warn, Error, Fatal or Panic
|
|
||||||
Message string
|
|
||||||
|
|
||||||
// When formatter is called in entry.log(), an Buffer may be set to entry
|
|
||||||
Buffer *bytes.Buffer
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewEntry(logger *Logger) *Entry {
|
|
||||||
return &Entry{
|
|
||||||
Logger: logger,
|
|
||||||
// Default is three fields, give a little extra room
|
|
||||||
Data: make(Fields, 5),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the string representation from the reader and ultimately the
|
|
||||||
// formatter.
|
|
||||||
func (entry *Entry) String() (string, error) {
|
|
||||||
serialized, err := entry.Logger.Formatter.Format(entry)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
str := string(serialized)
|
|
||||||
return str, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add an error as single field (using the key defined in ErrorKey) to the Entry.
|
|
||||||
func (entry *Entry) WithError(err error) *Entry {
|
|
||||||
return entry.WithField(ErrorKey, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add a single field to the Entry.
|
|
||||||
func (entry *Entry) WithField(key string, value interface{}) *Entry {
|
|
||||||
return entry.WithFields(Fields{key: value})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add a map of fields to the Entry.
|
|
||||||
func (entry *Entry) WithFields(fields Fields) *Entry {
|
|
||||||
data := make(Fields, len(entry.Data)+len(fields))
|
|
||||||
for k, v := range entry.Data {
|
|
||||||
data[k] = v
|
|
||||||
}
|
|
||||||
for k, v := range fields {
|
|
||||||
data[k] = v
|
|
||||||
}
|
|
||||||
return &Entry{Logger: entry.Logger, Data: data}
|
|
||||||
}
|
|
||||||
|
|
||||||
// This function is not declared with a pointer value because otherwise
|
|
||||||
// race conditions will occur when using multiple goroutines
|
|
||||||
func (entry Entry) log(level Level, msg string) {
|
|
||||||
var buffer *bytes.Buffer
|
|
||||||
entry.Time = time.Now()
|
|
||||||
entry.Level = level
|
|
||||||
entry.Message = msg
|
|
||||||
|
|
||||||
if err := entry.Logger.Hooks.Fire(level, &entry); err != nil {
|
|
||||||
entry.Logger.mu.Lock()
|
|
||||||
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
|
|
||||||
entry.Logger.mu.Unlock()
|
|
||||||
}
|
|
||||||
buffer = bufferPool.Get().(*bytes.Buffer)
|
|
||||||
buffer.Reset()
|
|
||||||
defer bufferPool.Put(buffer)
|
|
||||||
entry.Buffer = buffer
|
|
||||||
serialized, err := entry.Logger.Formatter.Format(&entry)
|
|
||||||
entry.Buffer = nil
|
|
||||||
if err != nil {
|
|
||||||
entry.Logger.mu.Lock()
|
|
||||||
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
|
|
||||||
entry.Logger.mu.Unlock()
|
|
||||||
} else {
|
|
||||||
entry.Logger.mu.Lock()
|
|
||||||
_, err = entry.Logger.Out.Write(serialized)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
|
|
||||||
}
|
|
||||||
entry.Logger.mu.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
// To avoid Entry#log() returning a value that only would make sense for
|
|
||||||
// panic() to use in Entry#Panic(), we avoid the allocation by checking
|
|
||||||
// directly here.
|
|
||||||
if level <= PanicLevel {
|
|
||||||
panic(&entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Debug(args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= DebugLevel {
|
|
||||||
entry.log(DebugLevel, fmt.Sprint(args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Print(args ...interface{}) {
|
|
||||||
entry.Info(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Info(args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= InfoLevel {
|
|
||||||
entry.log(InfoLevel, fmt.Sprint(args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Warn(args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= WarnLevel {
|
|
||||||
entry.log(WarnLevel, fmt.Sprint(args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Warning(args ...interface{}) {
|
|
||||||
entry.Warn(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Error(args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= ErrorLevel {
|
|
||||||
entry.log(ErrorLevel, fmt.Sprint(args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Fatal(args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= FatalLevel {
|
|
||||||
entry.log(FatalLevel, fmt.Sprint(args...))
|
|
||||||
}
|
|
||||||
Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Panic(args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= PanicLevel {
|
|
||||||
entry.log(PanicLevel, fmt.Sprint(args...))
|
|
||||||
}
|
|
||||||
panic(fmt.Sprint(args...))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Entry Printf family functions
|
|
||||||
|
|
||||||
func (entry *Entry) Debugf(format string, args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= DebugLevel {
|
|
||||||
entry.Debug(fmt.Sprintf(format, args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Infof(format string, args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= InfoLevel {
|
|
||||||
entry.Info(fmt.Sprintf(format, args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Printf(format string, args ...interface{}) {
|
|
||||||
entry.Infof(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Warnf(format string, args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= WarnLevel {
|
|
||||||
entry.Warn(fmt.Sprintf(format, args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Warningf(format string, args ...interface{}) {
|
|
||||||
entry.Warnf(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Errorf(format string, args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= ErrorLevel {
|
|
||||||
entry.Error(fmt.Sprintf(format, args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Fatalf(format string, args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= FatalLevel {
|
|
||||||
entry.Fatal(fmt.Sprintf(format, args...))
|
|
||||||
}
|
|
||||||
Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Panicf(format string, args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= PanicLevel {
|
|
||||||
entry.Panic(fmt.Sprintf(format, args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Entry Println family functions
|
|
||||||
|
|
||||||
func (entry *Entry) Debugln(args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= DebugLevel {
|
|
||||||
entry.Debug(entry.sprintlnn(args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Infoln(args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= InfoLevel {
|
|
||||||
entry.Info(entry.sprintlnn(args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Println(args ...interface{}) {
|
|
||||||
entry.Infoln(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Warnln(args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= WarnLevel {
|
|
||||||
entry.Warn(entry.sprintlnn(args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Warningln(args ...interface{}) {
|
|
||||||
entry.Warnln(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Errorln(args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= ErrorLevel {
|
|
||||||
entry.Error(entry.sprintlnn(args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Fatalln(args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= FatalLevel {
|
|
||||||
entry.Fatal(entry.sprintlnn(args...))
|
|
||||||
}
|
|
||||||
Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry *Entry) Panicln(args ...interface{}) {
|
|
||||||
if entry.Logger.Level >= PanicLevel {
|
|
||||||
entry.Panic(entry.sprintlnn(args...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sprintlnn => Sprint no newline. This is to get the behavior of how
|
|
||||||
// fmt.Sprintln where spaces are always added between operands, regardless of
|
|
||||||
// their type. Instead of vendoring the Sprintln implementation to spare a
|
|
||||||
// string allocation, we do the simplest thing.
|
|
||||||
func (entry *Entry) sprintlnn(args ...interface{}) string {
|
|
||||||
msg := fmt.Sprintln(args...)
|
|
||||||
return msg[:len(msg)-1]
|
|
||||||
}
|
|
||||||
-193
@@ -1,193 +0,0 @@
|
|||||||
package logrus
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
// std is the name of the standard logger in stdlib `log`
|
|
||||||
std = New()
|
|
||||||
)
|
|
||||||
|
|
||||||
func StandardLogger() *Logger {
|
|
||||||
return std
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetOutput sets the standard logger output.
|
|
||||||
func SetOutput(out io.Writer) {
|
|
||||||
std.mu.Lock()
|
|
||||||
defer std.mu.Unlock()
|
|
||||||
std.Out = out
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetFormatter sets the standard logger formatter.
|
|
||||||
func SetFormatter(formatter Formatter) {
|
|
||||||
std.mu.Lock()
|
|
||||||
defer std.mu.Unlock()
|
|
||||||
std.Formatter = formatter
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetLevel sets the standard logger level.
|
|
||||||
func SetLevel(level Level) {
|
|
||||||
std.mu.Lock()
|
|
||||||
defer std.mu.Unlock()
|
|
||||||
std.Level = level
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetLevel returns the standard logger level.
|
|
||||||
func GetLevel() Level {
|
|
||||||
std.mu.Lock()
|
|
||||||
defer std.mu.Unlock()
|
|
||||||
return std.Level
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddHook adds a hook to the standard logger hooks.
|
|
||||||
func AddHook(hook Hook) {
|
|
||||||
std.mu.Lock()
|
|
||||||
defer std.mu.Unlock()
|
|
||||||
std.Hooks.Add(hook)
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
|
|
||||||
func WithError(err error) *Entry {
|
|
||||||
return std.WithField(ErrorKey, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithField creates an entry from the standard logger and adds a field to
|
|
||||||
// it. If you want multiple fields, use `WithFields`.
|
|
||||||
//
|
|
||||||
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
|
|
||||||
// or Panic on the Entry it returns.
|
|
||||||
func WithField(key string, value interface{}) *Entry {
|
|
||||||
return std.WithField(key, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithFields creates an entry from the standard logger and adds multiple
|
|
||||||
// fields to it. This is simply a helper for `WithField`, invoking it
|
|
||||||
// once for each field.
|
|
||||||
//
|
|
||||||
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
|
|
||||||
// or Panic on the Entry it returns.
|
|
||||||
func WithFields(fields Fields) *Entry {
|
|
||||||
return std.WithFields(fields)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Debug logs a message at level Debug on the standard logger.
|
|
||||||
func Debug(args ...interface{}) {
|
|
||||||
std.Debug(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Print logs a message at level Info on the standard logger.
|
|
||||||
func Print(args ...interface{}) {
|
|
||||||
std.Print(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Info logs a message at level Info on the standard logger.
|
|
||||||
func Info(args ...interface{}) {
|
|
||||||
std.Info(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Warn logs a message at level Warn on the standard logger.
|
|
||||||
func Warn(args ...interface{}) {
|
|
||||||
std.Warn(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Warning logs a message at level Warn on the standard logger.
|
|
||||||
func Warning(args ...interface{}) {
|
|
||||||
std.Warning(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Error logs a message at level Error on the standard logger.
|
|
||||||
func Error(args ...interface{}) {
|
|
||||||
std.Error(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Panic logs a message at level Panic on the standard logger.
|
|
||||||
func Panic(args ...interface{}) {
|
|
||||||
std.Panic(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fatal logs a message at level Fatal on the standard logger.
|
|
||||||
func Fatal(args ...interface{}) {
|
|
||||||
std.Fatal(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Debugf logs a message at level Debug on the standard logger.
|
|
||||||
func Debugf(format string, args ...interface{}) {
|
|
||||||
std.Debugf(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Printf logs a message at level Info on the standard logger.
|
|
||||||
func Printf(format string, args ...interface{}) {
|
|
||||||
std.Printf(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Infof logs a message at level Info on the standard logger.
|
|
||||||
func Infof(format string, args ...interface{}) {
|
|
||||||
std.Infof(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Warnf logs a message at level Warn on the standard logger.
|
|
||||||
func Warnf(format string, args ...interface{}) {
|
|
||||||
std.Warnf(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Warningf logs a message at level Warn on the standard logger.
|
|
||||||
func Warningf(format string, args ...interface{}) {
|
|
||||||
std.Warningf(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Errorf logs a message at level Error on the standard logger.
|
|
||||||
func Errorf(format string, args ...interface{}) {
|
|
||||||
std.Errorf(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Panicf logs a message at level Panic on the standard logger.
|
|
||||||
func Panicf(format string, args ...interface{}) {
|
|
||||||
std.Panicf(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fatalf logs a message at level Fatal on the standard logger.
|
|
||||||
func Fatalf(format string, args ...interface{}) {
|
|
||||||
std.Fatalf(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Debugln logs a message at level Debug on the standard logger.
|
|
||||||
func Debugln(args ...interface{}) {
|
|
||||||
std.Debugln(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Println logs a message at level Info on the standard logger.
|
|
||||||
func Println(args ...interface{}) {
|
|
||||||
std.Println(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Infoln logs a message at level Info on the standard logger.
|
|
||||||
func Infoln(args ...interface{}) {
|
|
||||||
std.Infoln(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Warnln logs a message at level Warn on the standard logger.
|
|
||||||
func Warnln(args ...interface{}) {
|
|
||||||
std.Warnln(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Warningln logs a message at level Warn on the standard logger.
|
|
||||||
func Warningln(args ...interface{}) {
|
|
||||||
std.Warningln(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Errorln logs a message at level Error on the standard logger.
|
|
||||||
func Errorln(args ...interface{}) {
|
|
||||||
std.Errorln(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Panicln logs a message at level Panic on the standard logger.
|
|
||||||
func Panicln(args ...interface{}) {
|
|
||||||
std.Panicln(args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fatalln logs a message at level Fatal on the standard logger.
|
|
||||||
func Fatalln(args ...interface{}) {
|
|
||||||
std.Fatalln(args...)
|
|
||||||
}
|
|
||||||
-45
@@ -1,45 +0,0 @@
|
|||||||
package logrus
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
const DefaultTimestampFormat = time.RFC3339
|
|
||||||
|
|
||||||
// The Formatter interface is used to implement a custom Formatter. It takes an
|
|
||||||
// `Entry`. It exposes all the fields, including the default ones:
|
|
||||||
//
|
|
||||||
// * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
|
|
||||||
// * `entry.Data["time"]`. The timestamp.
|
|
||||||
// * `entry.Data["level"]. The level the entry was logged at.
|
|
||||||
//
|
|
||||||
// Any additional fields added with `WithField` or `WithFields` are also in
|
|
||||||
// `entry.Data`. Format is expected to return an array of bytes which are then
|
|
||||||
// logged to `logger.Out`.
|
|
||||||
type Formatter interface {
|
|
||||||
Format(*Entry) ([]byte, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// This is to not silently overwrite `time`, `msg` and `level` fields when
|
|
||||||
// dumping it. If this code wasn't there doing:
|
|
||||||
//
|
|
||||||
// logrus.WithField("level", 1).Info("hello")
|
|
||||||
//
|
|
||||||
// Would just silently drop the user provided level. Instead with this code
|
|
||||||
// it'll logged as:
|
|
||||||
//
|
|
||||||
// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
|
|
||||||
//
|
|
||||||
// It's not exported because it's still using Data in an opinionated way. It's to
|
|
||||||
// avoid code duplication between the two default formatters.
|
|
||||||
func prefixFieldClashes(data Fields) {
|
|
||||||
if t, ok := data["time"]; ok {
|
|
||||||
data["fields.time"] = t
|
|
||||||
}
|
|
||||||
|
|
||||||
if m, ok := data["msg"]; ok {
|
|
||||||
data["fields.msg"] = m
|
|
||||||
}
|
|
||||||
|
|
||||||
if l, ok := data["level"]; ok {
|
|
||||||
data["fields.level"] = l
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-34
@@ -1,34 +0,0 @@
|
|||||||
package logrus
|
|
||||||
|
|
||||||
// A hook to be fired when logging on the logging levels returned from
|
|
||||||
// `Levels()` on your implementation of the interface. Note that this is not
|
|
||||||
// fired in a goroutine or a channel with workers, you should handle such
|
|
||||||
// functionality yourself if your call is non-blocking and you don't wish for
|
|
||||||
// the logging calls for levels returned from `Levels()` to block.
|
|
||||||
type Hook interface {
|
|
||||||
Levels() []Level
|
|
||||||
Fire(*Entry) error
|
|
||||||
}
|
|
||||||
|
|
||||||
// Internal type for storing the hooks on a logger instance.
|
|
||||||
type LevelHooks map[Level][]Hook
|
|
||||||
|
|
||||||
// Add a hook to an instance of logger. This is called with
|
|
||||||
// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
|
|
||||||
func (hooks LevelHooks) Add(hook Hook) {
|
|
||||||
for _, level := range hook.Levels() {
|
|
||||||
hooks[level] = append(hooks[level], hook)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fire all the hooks for the passed level. Used by `entry.log` to fire
|
|
||||||
// appropriate hooks for a log entry.
|
|
||||||
func (hooks LevelHooks) Fire(level Level, entry *Entry) error {
|
|
||||||
for _, hook := range hooks[level] {
|
|
||||||
if err := hook.Fire(entry); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
-41
@@ -1,41 +0,0 @@
|
|||||||
package logrus
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
)
|
|
||||||
|
|
||||||
type JSONFormatter struct {
|
|
||||||
// TimestampFormat sets the format used for marshaling timestamps.
|
|
||||||
TimestampFormat string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
|
|
||||||
data := make(Fields, len(entry.Data)+3)
|
|
||||||
for k, v := range entry.Data {
|
|
||||||
switch v := v.(type) {
|
|
||||||
case error:
|
|
||||||
// Otherwise errors are ignored by `encoding/json`
|
|
||||||
// https://github.com/Sirupsen/logrus/issues/137
|
|
||||||
data[k] = v.Error()
|
|
||||||
default:
|
|
||||||
data[k] = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
prefixFieldClashes(data)
|
|
||||||
|
|
||||||
timestampFormat := f.TimestampFormat
|
|
||||||
if timestampFormat == "" {
|
|
||||||
timestampFormat = DefaultTimestampFormat
|
|
||||||
}
|
|
||||||
|
|
||||||
data["time"] = entry.Time.Format(timestampFormat)
|
|
||||||
data["msg"] = entry.Message
|
|
||||||
data["level"] = entry.Level.String()
|
|
||||||
|
|
||||||
serialized, err := json.Marshal(data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
|
|
||||||
}
|
|
||||||
return append(serialized, '\n'), nil
|
|
||||||
}
|
|
||||||
-308
@@ -1,308 +0,0 @@
|
|||||||
package logrus
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Logger struct {
|
|
||||||
// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
|
|
||||||
// file, or leave it default which is `os.Stderr`. You can also set this to
|
|
||||||
// something more adventorous, such as logging to Kafka.
|
|
||||||
Out io.Writer
|
|
||||||
// Hooks for the logger instance. These allow firing events based on logging
|
|
||||||
// levels and log entries. For example, to send errors to an error tracking
|
|
||||||
// service, log to StatsD or dump the core on fatal errors.
|
|
||||||
Hooks LevelHooks
|
|
||||||
// All log entries pass through the formatter before logged to Out. The
|
|
||||||
// included formatters are `TextFormatter` and `JSONFormatter` for which
|
|
||||||
// TextFormatter is the default. In development (when a TTY is attached) it
|
|
||||||
// logs with colors, but to a file it wouldn't. You can easily implement your
|
|
||||||
// own that implements the `Formatter` interface, see the `README` or included
|
|
||||||
// formatters for examples.
|
|
||||||
Formatter Formatter
|
|
||||||
// The logging level the logger should log at. This is typically (and defaults
|
|
||||||
// to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
|
|
||||||
// logged. `logrus.Debug` is useful in
|
|
||||||
Level Level
|
|
||||||
// Used to sync writing to the log. Locking is enabled by Default
|
|
||||||
mu MutexWrap
|
|
||||||
// Reusable empty entry
|
|
||||||
entryPool sync.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
type MutexWrap struct {
|
|
||||||
lock sync.Mutex
|
|
||||||
disabled bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (mw *MutexWrap) Lock() {
|
|
||||||
if !mw.disabled {
|
|
||||||
mw.lock.Lock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (mw *MutexWrap) Unlock() {
|
|
||||||
if !mw.disabled {
|
|
||||||
mw.lock.Unlock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (mw *MutexWrap) Disable() {
|
|
||||||
mw.disabled = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Creates a new logger. Configuration should be set by changing `Formatter`,
|
|
||||||
// `Out` and `Hooks` directly on the default logger instance. You can also just
|
|
||||||
// instantiate your own:
|
|
||||||
//
|
|
||||||
// var log = &Logger{
|
|
||||||
// Out: os.Stderr,
|
|
||||||
// Formatter: new(JSONFormatter),
|
|
||||||
// Hooks: make(LevelHooks),
|
|
||||||
// Level: logrus.DebugLevel,
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// It's recommended to make this a global instance called `log`.
|
|
||||||
func New() *Logger {
|
|
||||||
return &Logger{
|
|
||||||
Out: os.Stderr,
|
|
||||||
Formatter: new(TextFormatter),
|
|
||||||
Hooks: make(LevelHooks),
|
|
||||||
Level: InfoLevel,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) newEntry() *Entry {
|
|
||||||
entry, ok := logger.entryPool.Get().(*Entry)
|
|
||||||
if ok {
|
|
||||||
return entry
|
|
||||||
}
|
|
||||||
return NewEntry(logger)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) releaseEntry(entry *Entry) {
|
|
||||||
logger.entryPool.Put(entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Adds a field to the log entry, note that it doesn't log until you call
|
|
||||||
// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry.
|
|
||||||
// If you want multiple fields, use `WithFields`.
|
|
||||||
func (logger *Logger) WithField(key string, value interface{}) *Entry {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
defer logger.releaseEntry(entry)
|
|
||||||
return entry.WithField(key, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Adds a struct of fields to the log entry. All it does is call `WithField` for
|
|
||||||
// each `Field`.
|
|
||||||
func (logger *Logger) WithFields(fields Fields) *Entry {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
defer logger.releaseEntry(entry)
|
|
||||||
return entry.WithFields(fields)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add an error as single field to the log entry. All it does is call
|
|
||||||
// `WithError` for the given `error`.
|
|
||||||
func (logger *Logger) WithError(err error) *Entry {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
defer logger.releaseEntry(entry)
|
|
||||||
return entry.WithError(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Debugf(format string, args ...interface{}) {
|
|
||||||
if logger.Level >= DebugLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Debugf(format, args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Infof(format string, args ...interface{}) {
|
|
||||||
if logger.Level >= InfoLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Infof(format, args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Printf(format string, args ...interface{}) {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Printf(format, args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Warnf(format string, args ...interface{}) {
|
|
||||||
if logger.Level >= WarnLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Warnf(format, args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Warningf(format string, args ...interface{}) {
|
|
||||||
if logger.Level >= WarnLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Warnf(format, args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Errorf(format string, args ...interface{}) {
|
|
||||||
if logger.Level >= ErrorLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Errorf(format, args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Fatalf(format string, args ...interface{}) {
|
|
||||||
if logger.Level >= FatalLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Fatalf(format, args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Panicf(format string, args ...interface{}) {
|
|
||||||
if logger.Level >= PanicLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Panicf(format, args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Debug(args ...interface{}) {
|
|
||||||
if logger.Level >= DebugLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Debug(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Info(args ...interface{}) {
|
|
||||||
if logger.Level >= InfoLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Info(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Print(args ...interface{}) {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Info(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Warn(args ...interface{}) {
|
|
||||||
if logger.Level >= WarnLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Warn(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Warning(args ...interface{}) {
|
|
||||||
if logger.Level >= WarnLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Warn(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Error(args ...interface{}) {
|
|
||||||
if logger.Level >= ErrorLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Error(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Fatal(args ...interface{}) {
|
|
||||||
if logger.Level >= FatalLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Fatal(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Panic(args ...interface{}) {
|
|
||||||
if logger.Level >= PanicLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Panic(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Debugln(args ...interface{}) {
|
|
||||||
if logger.Level >= DebugLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Debugln(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Infoln(args ...interface{}) {
|
|
||||||
if logger.Level >= InfoLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Infoln(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Println(args ...interface{}) {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Println(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Warnln(args ...interface{}) {
|
|
||||||
if logger.Level >= WarnLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Warnln(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Warningln(args ...interface{}) {
|
|
||||||
if logger.Level >= WarnLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Warnln(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Errorln(args ...interface{}) {
|
|
||||||
if logger.Level >= ErrorLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Errorln(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Fatalln(args ...interface{}) {
|
|
||||||
if logger.Level >= FatalLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Fatalln(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) Panicln(args ...interface{}) {
|
|
||||||
if logger.Level >= PanicLevel {
|
|
||||||
entry := logger.newEntry()
|
|
||||||
entry.Panicln(args...)
|
|
||||||
logger.releaseEntry(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//When file is opened with appending mode, it's safe to
|
|
||||||
//write concurrently to a file (within 4k message on Linux).
|
|
||||||
//In these cases user can choose to disable the lock.
|
|
||||||
func (logger *Logger) SetNoLock() {
|
|
||||||
logger.mu.Disable()
|
|
||||||
}
|
|
||||||
-143
@@ -1,143 +0,0 @@
|
|||||||
package logrus
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Fields type, used to pass to `WithFields`.
|
|
||||||
type Fields map[string]interface{}
|
|
||||||
|
|
||||||
// Level type
|
|
||||||
type Level uint8
|
|
||||||
|
|
||||||
// Convert the Level to a string. E.g. PanicLevel becomes "panic".
|
|
||||||
func (level Level) String() string {
|
|
||||||
switch level {
|
|
||||||
case DebugLevel:
|
|
||||||
return "debug"
|
|
||||||
case InfoLevel:
|
|
||||||
return "info"
|
|
||||||
case WarnLevel:
|
|
||||||
return "warning"
|
|
||||||
case ErrorLevel:
|
|
||||||
return "error"
|
|
||||||
case FatalLevel:
|
|
||||||
return "fatal"
|
|
||||||
case PanicLevel:
|
|
||||||
return "panic"
|
|
||||||
}
|
|
||||||
|
|
||||||
return "unknown"
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParseLevel takes a string level and returns the Logrus log level constant.
|
|
||||||
func ParseLevel(lvl string) (Level, error) {
|
|
||||||
switch strings.ToLower(lvl) {
|
|
||||||
case "panic":
|
|
||||||
return PanicLevel, nil
|
|
||||||
case "fatal":
|
|
||||||
return FatalLevel, nil
|
|
||||||
case "error":
|
|
||||||
return ErrorLevel, nil
|
|
||||||
case "warn", "warning":
|
|
||||||
return WarnLevel, nil
|
|
||||||
case "info":
|
|
||||||
return InfoLevel, nil
|
|
||||||
case "debug":
|
|
||||||
return DebugLevel, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var l Level
|
|
||||||
return l, fmt.Errorf("not a valid logrus Level: %q", lvl)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A constant exposing all logging levels
|
|
||||||
var AllLevels = []Level{
|
|
||||||
PanicLevel,
|
|
||||||
FatalLevel,
|
|
||||||
ErrorLevel,
|
|
||||||
WarnLevel,
|
|
||||||
InfoLevel,
|
|
||||||
DebugLevel,
|
|
||||||
}
|
|
||||||
|
|
||||||
// These are the different logging levels. You can set the logging level to log
|
|
||||||
// on your instance of logger, obtained with `logrus.New()`.
|
|
||||||
const (
|
|
||||||
// PanicLevel level, highest level of severity. Logs and then calls panic with the
|
|
||||||
// message passed to Debug, Info, ...
|
|
||||||
PanicLevel Level = iota
|
|
||||||
// FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the
|
|
||||||
// logging level is set to Panic.
|
|
||||||
FatalLevel
|
|
||||||
// ErrorLevel level. Logs. Used for errors that should definitely be noted.
|
|
||||||
// Commonly used for hooks to send errors to an error tracking service.
|
|
||||||
ErrorLevel
|
|
||||||
// WarnLevel level. Non-critical entries that deserve eyes.
|
|
||||||
WarnLevel
|
|
||||||
// InfoLevel level. General operational entries about what's going on inside the
|
|
||||||
// application.
|
|
||||||
InfoLevel
|
|
||||||
// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
|
|
||||||
DebugLevel
|
|
||||||
)
|
|
||||||
|
|
||||||
// Won't compile if StdLogger can't be realized by a log.Logger
|
|
||||||
var (
|
|
||||||
_ StdLogger = &log.Logger{}
|
|
||||||
_ StdLogger = &Entry{}
|
|
||||||
_ StdLogger = &Logger{}
|
|
||||||
)
|
|
||||||
|
|
||||||
// StdLogger is what your logrus-enabled library should take, that way
|
|
||||||
// it'll accept a stdlib logger and a logrus logger. There's no standard
|
|
||||||
// interface, this is the closest we get, unfortunately.
|
|
||||||
type StdLogger interface {
|
|
||||||
Print(...interface{})
|
|
||||||
Printf(string, ...interface{})
|
|
||||||
Println(...interface{})
|
|
||||||
|
|
||||||
Fatal(...interface{})
|
|
||||||
Fatalf(string, ...interface{})
|
|
||||||
Fatalln(...interface{})
|
|
||||||
|
|
||||||
Panic(...interface{})
|
|
||||||
Panicf(string, ...interface{})
|
|
||||||
Panicln(...interface{})
|
|
||||||
}
|
|
||||||
|
|
||||||
// The FieldLogger interface generalizes the Entry and Logger types
|
|
||||||
type FieldLogger interface {
|
|
||||||
WithField(key string, value interface{}) *Entry
|
|
||||||
WithFields(fields Fields) *Entry
|
|
||||||
WithError(err error) *Entry
|
|
||||||
|
|
||||||
Debugf(format string, args ...interface{})
|
|
||||||
Infof(format string, args ...interface{})
|
|
||||||
Printf(format string, args ...interface{})
|
|
||||||
Warnf(format string, args ...interface{})
|
|
||||||
Warningf(format string, args ...interface{})
|
|
||||||
Errorf(format string, args ...interface{})
|
|
||||||
Fatalf(format string, args ...interface{})
|
|
||||||
Panicf(format string, args ...interface{})
|
|
||||||
|
|
||||||
Debug(args ...interface{})
|
|
||||||
Info(args ...interface{})
|
|
||||||
Print(args ...interface{})
|
|
||||||
Warn(args ...interface{})
|
|
||||||
Warning(args ...interface{})
|
|
||||||
Error(args ...interface{})
|
|
||||||
Fatal(args ...interface{})
|
|
||||||
Panic(args ...interface{})
|
|
||||||
|
|
||||||
Debugln(args ...interface{})
|
|
||||||
Infoln(args ...interface{})
|
|
||||||
Println(args ...interface{})
|
|
||||||
Warnln(args ...interface{})
|
|
||||||
Warningln(args ...interface{})
|
|
||||||
Errorln(args ...interface{})
|
|
||||||
Fatalln(args ...interface{})
|
|
||||||
Panicln(args ...interface{})
|
|
||||||
}
|
|
||||||
-8
@@ -1,8 +0,0 @@
|
|||||||
// +build appengine
|
|
||||||
|
|
||||||
package logrus
|
|
||||||
|
|
||||||
// IsTerminal returns true if stderr's file descriptor is a terminal.
|
|
||||||
func IsTerminal() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
-10
@@ -1,10 +0,0 @@
|
|||||||
// +build darwin freebsd openbsd netbsd dragonfly
|
|
||||||
// +build !appengine
|
|
||||||
|
|
||||||
package logrus
|
|
||||||
|
|
||||||
import "syscall"
|
|
||||||
|
|
||||||
const ioctlReadTermios = syscall.TIOCGETA
|
|
||||||
|
|
||||||
type Termios syscall.Termios
|
|
||||||
-14
@@ -1,14 +0,0 @@
|
|||||||
// Based on ssh/terminal:
|
|
||||||
// Copyright 2013 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.
|
|
||||||
|
|
||||||
// +build !appengine
|
|
||||||
|
|
||||||
package logrus
|
|
||||||
|
|
||||||
import "syscall"
|
|
||||||
|
|
||||||
const ioctlReadTermios = syscall.TCGETS
|
|
||||||
|
|
||||||
type Termios syscall.Termios
|
|
||||||
-22
@@ -1,22 +0,0 @@
|
|||||||
// Based on ssh/terminal:
|
|
||||||
// Copyright 2011 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.
|
|
||||||
|
|
||||||
// +build linux darwin freebsd openbsd netbsd dragonfly
|
|
||||||
// +build !appengine
|
|
||||||
|
|
||||||
package logrus
|
|
||||||
|
|
||||||
import (
|
|
||||||
"syscall"
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
// IsTerminal returns true if stderr's file descriptor is a terminal.
|
|
||||||
func IsTerminal() bool {
|
|
||||||
fd := syscall.Stderr
|
|
||||||
var termios Termios
|
|
||||||
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
|
|
||||||
return err == 0
|
|
||||||
}
|
|
||||||
-15
@@ -1,15 +0,0 @@
|
|||||||
// +build solaris,!appengine
|
|
||||||
|
|
||||||
package logrus
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"golang.org/x/sys/unix"
|
|
||||||
)
|
|
||||||
|
|
||||||
// IsTerminal returns true if the given file descriptor is a terminal.
|
|
||||||
func IsTerminal() bool {
|
|
||||||
_, err := unix.IoctlGetTermios(int(os.Stdout.Fd()), unix.TCGETA)
|
|
||||||
return err == nil
|
|
||||||
}
|
|
||||||
-27
@@ -1,27 +0,0 @@
|
|||||||
// Based on ssh/terminal:
|
|
||||||
// Copyright 2011 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.
|
|
||||||
|
|
||||||
// +build windows,!appengine
|
|
||||||
|
|
||||||
package logrus
|
|
||||||
|
|
||||||
import (
|
|
||||||
"syscall"
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
var kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
|
||||||
|
|
||||||
var (
|
|
||||||
procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
|
|
||||||
)
|
|
||||||
|
|
||||||
// IsTerminal returns true if stderr's file descriptor is a terminal.
|
|
||||||
func IsTerminal() bool {
|
|
||||||
fd := syscall.Stderr
|
|
||||||
var st uint32
|
|
||||||
r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
|
|
||||||
return r != 0 && e == 0
|
|
||||||
}
|
|
||||||
-168
@@ -1,168 +0,0 @@
|
|||||||
package logrus
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"runtime"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
nocolor = 0
|
|
||||||
red = 31
|
|
||||||
green = 32
|
|
||||||
yellow = 33
|
|
||||||
blue = 34
|
|
||||||
gray = 37
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
baseTimestamp time.Time
|
|
||||||
isTerminal bool
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
baseTimestamp = time.Now()
|
|
||||||
isTerminal = IsTerminal()
|
|
||||||
}
|
|
||||||
|
|
||||||
func miniTS() int {
|
|
||||||
return int(time.Since(baseTimestamp) / time.Second)
|
|
||||||
}
|
|
||||||
|
|
||||||
type TextFormatter struct {
|
|
||||||
// Set to true to bypass checking for a TTY before outputting colors.
|
|
||||||
ForceColors bool
|
|
||||||
|
|
||||||
// Force disabling colors.
|
|
||||||
DisableColors bool
|
|
||||||
|
|
||||||
// Disable timestamp logging. useful when output is redirected to logging
|
|
||||||
// system that already adds timestamps.
|
|
||||||
DisableTimestamp bool
|
|
||||||
|
|
||||||
// Enable logging the full timestamp when a TTY is attached instead of just
|
|
||||||
// the time passed since beginning of execution.
|
|
||||||
FullTimestamp bool
|
|
||||||
|
|
||||||
// TimestampFormat to use for display when a full timestamp is printed
|
|
||||||
TimestampFormat string
|
|
||||||
|
|
||||||
// The fields are sorted by default for a consistent output. For applications
|
|
||||||
// that log extremely frequently and don't use the JSON formatter this may not
|
|
||||||
// be desired.
|
|
||||||
DisableSorting bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
|
|
||||||
var b *bytes.Buffer
|
|
||||||
var keys []string = make([]string, 0, len(entry.Data))
|
|
||||||
for k := range entry.Data {
|
|
||||||
keys = append(keys, k)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !f.DisableSorting {
|
|
||||||
sort.Strings(keys)
|
|
||||||
}
|
|
||||||
if entry.Buffer != nil {
|
|
||||||
b = entry.Buffer
|
|
||||||
} else {
|
|
||||||
b = &bytes.Buffer{}
|
|
||||||
}
|
|
||||||
|
|
||||||
prefixFieldClashes(entry.Data)
|
|
||||||
|
|
||||||
isColorTerminal := isTerminal && (runtime.GOOS != "windows")
|
|
||||||
isColored := (f.ForceColors || isColorTerminal) && !f.DisableColors
|
|
||||||
|
|
||||||
timestampFormat := f.TimestampFormat
|
|
||||||
if timestampFormat == "" {
|
|
||||||
timestampFormat = DefaultTimestampFormat
|
|
||||||
}
|
|
||||||
if isColored {
|
|
||||||
f.printColored(b, entry, keys, timestampFormat)
|
|
||||||
} else {
|
|
||||||
if !f.DisableTimestamp {
|
|
||||||
f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat))
|
|
||||||
}
|
|
||||||
f.appendKeyValue(b, "level", entry.Level.String())
|
|
||||||
if entry.Message != "" {
|
|
||||||
f.appendKeyValue(b, "msg", entry.Message)
|
|
||||||
}
|
|
||||||
for _, key := range keys {
|
|
||||||
f.appendKeyValue(b, key, entry.Data[key])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
b.WriteByte('\n')
|
|
||||||
return b.Bytes(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) {
|
|
||||||
var levelColor int
|
|
||||||
switch entry.Level {
|
|
||||||
case DebugLevel:
|
|
||||||
levelColor = gray
|
|
||||||
case WarnLevel:
|
|
||||||
levelColor = yellow
|
|
||||||
case ErrorLevel, FatalLevel, PanicLevel:
|
|
||||||
levelColor = red
|
|
||||||
default:
|
|
||||||
levelColor = blue
|
|
||||||
}
|
|
||||||
|
|
||||||
levelText := strings.ToUpper(entry.Level.String())[0:4]
|
|
||||||
|
|
||||||
if !f.FullTimestamp {
|
|
||||||
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message)
|
|
||||||
} else {
|
|
||||||
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message)
|
|
||||||
}
|
|
||||||
for _, k := range keys {
|
|
||||||
v := entry.Data[k]
|
|
||||||
fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
|
|
||||||
f.appendValue(b, v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func needsQuoting(text string) bool {
|
|
||||||
for _, ch := range text {
|
|
||||||
if !((ch >= 'a' && ch <= 'z') ||
|
|
||||||
(ch >= 'A' && ch <= 'Z') ||
|
|
||||||
(ch >= '0' && ch <= '9') ||
|
|
||||||
ch == '-' || ch == '.') {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
|
|
||||||
|
|
||||||
b.WriteString(key)
|
|
||||||
b.WriteByte('=')
|
|
||||||
f.appendValue(b, value)
|
|
||||||
b.WriteByte(' ')
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
|
|
||||||
switch value := value.(type) {
|
|
||||||
case string:
|
|
||||||
if !needsQuoting(value) {
|
|
||||||
b.WriteString(value)
|
|
||||||
} else {
|
|
||||||
fmt.Fprintf(b, "%q", value)
|
|
||||||
}
|
|
||||||
case error:
|
|
||||||
errmsg := value.Error()
|
|
||||||
if !needsQuoting(errmsg) {
|
|
||||||
b.WriteString(errmsg)
|
|
||||||
} else {
|
|
||||||
fmt.Fprintf(b, "%q", errmsg)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
fmt.Fprint(b, value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-53
@@ -1,53 +0,0 @@
|
|||||||
package logrus
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"io"
|
|
||||||
"runtime"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (logger *Logger) Writer() *io.PipeWriter {
|
|
||||||
return logger.WriterLevel(InfoLevel)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
|
|
||||||
reader, writer := io.Pipe()
|
|
||||||
|
|
||||||
var printFunc func(args ...interface{})
|
|
||||||
switch level {
|
|
||||||
case DebugLevel:
|
|
||||||
printFunc = logger.Debug
|
|
||||||
case InfoLevel:
|
|
||||||
printFunc = logger.Info
|
|
||||||
case WarnLevel:
|
|
||||||
printFunc = logger.Warn
|
|
||||||
case ErrorLevel:
|
|
||||||
printFunc = logger.Error
|
|
||||||
case FatalLevel:
|
|
||||||
printFunc = logger.Fatal
|
|
||||||
case PanicLevel:
|
|
||||||
printFunc = logger.Panic
|
|
||||||
default:
|
|
||||||
printFunc = logger.Print
|
|
||||||
}
|
|
||||||
|
|
||||||
go logger.writerScanner(reader, printFunc)
|
|
||||||
runtime.SetFinalizer(writer, writerFinalizer)
|
|
||||||
|
|
||||||
return writer
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger *Logger) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
|
|
||||||
scanner := bufio.NewScanner(reader)
|
|
||||||
for scanner.Scan() {
|
|
||||||
printFunc(scanner.Text())
|
|
||||||
}
|
|
||||||
if err := scanner.Err(); err != nil {
|
|
||||||
logger.Errorf("Error while reading from Writer: %s", err)
|
|
||||||
}
|
|
||||||
reader.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func writerFinalizer(writer *io.PipeWriter) {
|
|
||||||
writer.Close()
|
|
||||||
}
|
|
||||||
-229
@@ -1,229 +0,0 @@
|
|||||||
List of all the awesome people working to make Gin the best Web Framework in Go.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
##gin 0.x series authors
|
|
||||||
|
|
||||||
**Maintainer:** Manu Martinez-Almeida (@manucorporat), Javier Provecho (@javierprovecho)
|
|
||||||
|
|
||||||
People and companies, who have contributed, in alphabetical order.
|
|
||||||
|
|
||||||
**@858806258 (杰哥)**
|
|
||||||
- Fix typo in example
|
|
||||||
|
|
||||||
|
|
||||||
**@achedeuzot (Klemen Sever)**
|
|
||||||
- Fix newline debug printing
|
|
||||||
|
|
||||||
|
|
||||||
**@adammck (Adam Mckaig)**
|
|
||||||
- Add MIT license
|
|
||||||
|
|
||||||
|
|
||||||
**@AlexanderChen1989 (Alexander)**
|
|
||||||
- Typos in README
|
|
||||||
|
|
||||||
|
|
||||||
**@alexanderdidenko (Aleksandr Didenko)**
|
|
||||||
- Add support multipart/form-data
|
|
||||||
|
|
||||||
|
|
||||||
**@alexandernyquist (Alexander Nyquist)**
|
|
||||||
- Using template.Must to fix multiple return issue
|
|
||||||
- ★ Added support for OPTIONS verb
|
|
||||||
- ★ Setting response headers before calling WriteHeader
|
|
||||||
- Improved documentation for model binding
|
|
||||||
- ★ Added Content.Redirect()
|
|
||||||
- ★ Added tons of Unit tests
|
|
||||||
|
|
||||||
|
|
||||||
**@austinheap (Austin Heap)**
|
|
||||||
- Added travis CI integration
|
|
||||||
|
|
||||||
|
|
||||||
**@andredublin (Andre Dublin)**
|
|
||||||
- Fix typo in comment
|
|
||||||
|
|
||||||
|
|
||||||
**@bredov (Ludwig Valda Vasquez)**
|
|
||||||
- Fix html templating in debug mode
|
|
||||||
|
|
||||||
|
|
||||||
**@bluele (Jun Kimura)**
|
|
||||||
- Fixes code examples in README
|
|
||||||
|
|
||||||
|
|
||||||
**@chad-russell**
|
|
||||||
- ★ Support for serializing gin.H into XML
|
|
||||||
|
|
||||||
|
|
||||||
**@dickeyxxx (Jeff Dickey)**
|
|
||||||
- Typos in README
|
|
||||||
- Add example about serving static files
|
|
||||||
|
|
||||||
|
|
||||||
**@donileo (Adonis)**
|
|
||||||
- Add NoMethod handler
|
|
||||||
|
|
||||||
|
|
||||||
**@dutchcoders (DutchCoders)**
|
|
||||||
- ★ Fix security bug that allows client to spoof ip
|
|
||||||
- Fix typo. r.HTMLTemplates -> SetHTMLTemplate
|
|
||||||
|
|
||||||
|
|
||||||
**@el3ctro- (Joshua Loper)**
|
|
||||||
- Fix typo in example
|
|
||||||
|
|
||||||
|
|
||||||
**@ethankan (Ethan Kan)**
|
|
||||||
- Unsigned integers in binding
|
|
||||||
|
|
||||||
|
|
||||||
**(Evgeny Persienko)**
|
|
||||||
- Validate sub structures
|
|
||||||
|
|
||||||
|
|
||||||
**@frankbille (Frank Bille)**
|
|
||||||
- Add support for HTTP Realm Auth
|
|
||||||
|
|
||||||
|
|
||||||
**@fmd (Fareed Dudhia)**
|
|
||||||
- Fix typo. SetHTTPTemplate -> SetHTMLTemplate
|
|
||||||
|
|
||||||
|
|
||||||
**@ironiridis (Christopher Harrington)**
|
|
||||||
- Remove old reference
|
|
||||||
|
|
||||||
|
|
||||||
**@jammie-stackhouse (Jamie Stackhouse)**
|
|
||||||
- Add more shortcuts for router methods
|
|
||||||
|
|
||||||
|
|
||||||
**@jasonrhansen**
|
|
||||||
- Fix spelling and grammar errors in documentation
|
|
||||||
|
|
||||||
|
|
||||||
**@JasonSoft (Jason Lee)**
|
|
||||||
- Fix typo in comment
|
|
||||||
|
|
||||||
|
|
||||||
**@joiggama (Ignacio Galindo)**
|
|
||||||
- Add utf-8 charset header on renders
|
|
||||||
|
|
||||||
|
|
||||||
**@julienschmidt (Julien Schmidt)**
|
|
||||||
- gofmt the code examples
|
|
||||||
|
|
||||||
|
|
||||||
**@kelcecil (Kel Cecil)**
|
|
||||||
- Fix readme typo
|
|
||||||
|
|
||||||
|
|
||||||
**@kyledinh (Kyle Dinh)**
|
|
||||||
- Adds RunTLS()
|
|
||||||
|
|
||||||
|
|
||||||
**@LinusU (Linus Unnebäck)**
|
|
||||||
- Small fixes in README
|
|
||||||
|
|
||||||
|
|
||||||
**@loongmxbt (Saint Asky)**
|
|
||||||
- Fix typo in example
|
|
||||||
|
|
||||||
|
|
||||||
**@lucas-clemente (Lucas Clemente)**
|
|
||||||
- ★ work around path.Join removing trailing slashes from routes
|
|
||||||
|
|
||||||
|
|
||||||
**@mattn (Yasuhiro Matsumoto)**
|
|
||||||
- Improve color logger
|
|
||||||
|
|
||||||
|
|
||||||
**@mdigger (Dmitry Sedykh)**
|
|
||||||
- Fixes Form binding when content-type is x-www-form-urlencoded
|
|
||||||
- No repeat call c.Writer.Status() in gin.Logger
|
|
||||||
- Fixes Content-Type for json render
|
|
||||||
|
|
||||||
|
|
||||||
**@mirzac (Mirza Ceric)**
|
|
||||||
- Fix debug printing
|
|
||||||
|
|
||||||
|
|
||||||
**@mopemope (Yutaka Matsubara)**
|
|
||||||
- ★ Adds Godep support (Dependencies Manager)
|
|
||||||
- Fix variadic parameter in the flexible render API
|
|
||||||
- Fix Corrupted plain render
|
|
||||||
- Add Pluggable View Renderer Example
|
|
||||||
|
|
||||||
|
|
||||||
**@msemenistyi (Mykyta Semenistyi)**
|
|
||||||
- update Readme.md. Add code to String method
|
|
||||||
|
|
||||||
|
|
||||||
**@msoedov (Sasha Myasoedov)**
|
|
||||||
- ★ Adds tons of unit tests.
|
|
||||||
|
|
||||||
|
|
||||||
**@ngerakines (Nick Gerakines)**
|
|
||||||
- ★ Improves API, c.GET() doesn't panic
|
|
||||||
- Adds MustGet() method
|
|
||||||
|
|
||||||
|
|
||||||
**@r8k (Rajiv Kilaparti)**
|
|
||||||
- Fix Port usage in README.
|
|
||||||
|
|
||||||
|
|
||||||
**@rayrod2030 (Ray Rodriguez)**
|
|
||||||
- Fix typo in example
|
|
||||||
|
|
||||||
|
|
||||||
**@rns**
|
|
||||||
- Fix typo in example
|
|
||||||
|
|
||||||
|
|
||||||
**@RobAWilkinson (Robert Wilkinson)**
|
|
||||||
- Add example of forms and params
|
|
||||||
|
|
||||||
|
|
||||||
**@rogierlommers (Rogier Lommers)**
|
|
||||||
- Add updated static serve example
|
|
||||||
|
|
||||||
|
|
||||||
**@se77en (Damon Zhao)**
|
|
||||||
- Improve color logging
|
|
||||||
|
|
||||||
|
|
||||||
**@silasb (Silas Baronda)**
|
|
||||||
- Fixing quotes in README
|
|
||||||
|
|
||||||
|
|
||||||
**@SkuliOskarsson (Skuli Oskarsson)**
|
|
||||||
- Fixes some texts in README II
|
|
||||||
|
|
||||||
|
|
||||||
**@slimmy (Jimmy Pettersson)**
|
|
||||||
- Added messages for required bindings
|
|
||||||
|
|
||||||
|
|
||||||
**@smira (Andrey Smirnov)**
|
|
||||||
- Add support for ignored/unexported fields in binding
|
|
||||||
|
|
||||||
|
|
||||||
**@superalsrk (SRK.Lyu)**
|
|
||||||
- Update httprouter godeps
|
|
||||||
|
|
||||||
|
|
||||||
**@tebeka (Miki Tebeka)**
|
|
||||||
- Use net/http constants instead of numeric values
|
|
||||||
|
|
||||||
|
|
||||||
**@techjanitor**
|
|
||||||
- Update context.go reserved IPs
|
|
||||||
|
|
||||||
|
|
||||||
**@yosssi (Keiji Yoshida)**
|
|
||||||
- Fix link in README
|
|
||||||
|
|
||||||
|
|
||||||
**@yuyabee**
|
|
||||||
- Fixed README
|
|
||||||
-298
@@ -1,298 +0,0 @@
|
|||||||
**Machine:** intel i7 ivy bridge quad-core. 8GB RAM.
|
|
||||||
**Date:** June 4th, 2015
|
|
||||||
[https://github.com/gin-gonic/go-http-routing-benchmark](https://github.com/gin-gonic/go-http-routing-benchmark)
|
|
||||||
|
|
||||||
```
|
|
||||||
BenchmarkAce_Param 5000000 372 ns/op 32 B/op 1 allocs/op
|
|
||||||
BenchmarkBear_Param 1000000 1165 ns/op 424 B/op 5 allocs/op
|
|
||||||
BenchmarkBeego_Param 1000000 2440 ns/op 720 B/op 10 allocs/op
|
|
||||||
BenchmarkBone_Param 1000000 1067 ns/op 384 B/op 3 allocs/op
|
|
||||||
BenchmarkDenco_Param 5000000 240 ns/op 32 B/op 1 allocs/op
|
|
||||||
BenchmarkEcho_Param 10000000 130 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGin_Param 10000000 133 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGocraftWeb_Param 1000000 1826 ns/op 656 B/op 9 allocs/op
|
|
||||||
BenchmarkGoji_Param 2000000 957 ns/op 336 B/op 2 allocs/op
|
|
||||||
BenchmarkGoJsonRest_Param 1000000 2021 ns/op 657 B/op 14 allocs/op
|
|
||||||
BenchmarkGoRestful_Param 200000 8825 ns/op 2496 B/op 31 allocs/op
|
|
||||||
BenchmarkGorillaMux_Param 500000 3340 ns/op 784 B/op 9 allocs/op
|
|
||||||
BenchmarkHttpRouter_Param 10000000 152 ns/op 32 B/op 1 allocs/op
|
|
||||||
BenchmarkHttpTreeMux_Param 2000000 717 ns/op 336 B/op 2 allocs/op
|
|
||||||
BenchmarkKocha_Param 3000000 423 ns/op 56 B/op 3 allocs/op
|
|
||||||
BenchmarkMacaron_Param 1000000 3410 ns/op 1104 B/op 11 allocs/op
|
|
||||||
BenchmarkMartini_Param 200000 7101 ns/op 1152 B/op 12 allocs/op
|
|
||||||
BenchmarkPat_Param 1000000 2040 ns/op 656 B/op 14 allocs/op
|
|
||||||
BenchmarkPossum_Param 1000000 2048 ns/op 624 B/op 7 allocs/op
|
|
||||||
BenchmarkR2router_Param 1000000 1144 ns/op 432 B/op 6 allocs/op
|
|
||||||
BenchmarkRevel_Param 200000 6725 ns/op 1672 B/op 28 allocs/op
|
|
||||||
BenchmarkRivet_Param 1000000 1121 ns/op 464 B/op 5 allocs/op
|
|
||||||
BenchmarkTango_Param 1000000 1479 ns/op 256 B/op 10 allocs/op
|
|
||||||
BenchmarkTigerTonic_Param 1000000 3393 ns/op 992 B/op 19 allocs/op
|
|
||||||
BenchmarkTraffic_Param 300000 5525 ns/op 1984 B/op 23 allocs/op
|
|
||||||
BenchmarkVulcan_Param 2000000 924 ns/op 98 B/op 3 allocs/op
|
|
||||||
BenchmarkZeus_Param 1000000 1084 ns/op 368 B/op 3 allocs/op
|
|
||||||
BenchmarkAce_Param5 3000000 614 ns/op 160 B/op 1 allocs/op
|
|
||||||
BenchmarkBear_Param5 1000000 1617 ns/op 469 B/op 5 allocs/op
|
|
||||||
BenchmarkBeego_Param5 1000000 3373 ns/op 992 B/op 13 allocs/op
|
|
||||||
BenchmarkBone_Param5 1000000 1478 ns/op 432 B/op 3 allocs/op
|
|
||||||
BenchmarkDenco_Param5 3000000 570 ns/op 160 B/op 1 allocs/op
|
|
||||||
BenchmarkEcho_Param5 5000000 256 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGin_Param5 10000000 222 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGocraftWeb_Param5 1000000 2789 ns/op 928 B/op 12 allocs/op
|
|
||||||
BenchmarkGoji_Param5 1000000 1287 ns/op 336 B/op 2 allocs/op
|
|
||||||
BenchmarkGoJsonRest_Param5 1000000 3670 ns/op 1105 B/op 17 allocs/op
|
|
||||||
BenchmarkGoRestful_Param5 200000 10756 ns/op 2672 B/op 31 allocs/op
|
|
||||||
BenchmarkGorillaMux_Param5 300000 5543 ns/op 912 B/op 9 allocs/op
|
|
||||||
BenchmarkHttpRouter_Param5 5000000 403 ns/op 160 B/op 1 allocs/op
|
|
||||||
BenchmarkHttpTreeMux_Param5 1000000 1089 ns/op 336 B/op 2 allocs/op
|
|
||||||
BenchmarkKocha_Param5 1000000 1682 ns/op 440 B/op 10 allocs/op
|
|
||||||
BenchmarkMacaron_Param5 300000 4596 ns/op 1376 B/op 14 allocs/op
|
|
||||||
BenchmarkMartini_Param5 100000 15703 ns/op 1280 B/op 12 allocs/op
|
|
||||||
BenchmarkPat_Param5 300000 5320 ns/op 1008 B/op 42 allocs/op
|
|
||||||
BenchmarkPossum_Param5 1000000 2155 ns/op 624 B/op 7 allocs/op
|
|
||||||
BenchmarkR2router_Param5 1000000 1559 ns/op 432 B/op 6 allocs/op
|
|
||||||
BenchmarkRevel_Param5 200000 8184 ns/op 2024 B/op 35 allocs/op
|
|
||||||
BenchmarkRivet_Param5 1000000 1914 ns/op 528 B/op 9 allocs/op
|
|
||||||
BenchmarkTango_Param5 1000000 3280 ns/op 944 B/op 18 allocs/op
|
|
||||||
BenchmarkTigerTonic_Param5 200000 11638 ns/op 2519 B/op 53 allocs/op
|
|
||||||
BenchmarkTraffic_Param5 200000 8941 ns/op 2280 B/op 31 allocs/op
|
|
||||||
BenchmarkVulcan_Param5 1000000 1279 ns/op 98 B/op 3 allocs/op
|
|
||||||
BenchmarkZeus_Param5 1000000 1574 ns/op 416 B/op 3 allocs/op
|
|
||||||
BenchmarkAce_Param20 1000000 1528 ns/op 640 B/op 1 allocs/op
|
|
||||||
BenchmarkBear_Param20 300000 4906 ns/op 1633 B/op 5 allocs/op
|
|
||||||
BenchmarkBeego_Param20 200000 10529 ns/op 3868 B/op 17 allocs/op
|
|
||||||
BenchmarkBone_Param20 300000 7362 ns/op 2539 B/op 5 allocs/op
|
|
||||||
BenchmarkDenco_Param20 1000000 1884 ns/op 640 B/op 1 allocs/op
|
|
||||||
BenchmarkEcho_Param20 2000000 689 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGin_Param20 3000000 545 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGocraftWeb_Param20 200000 9437 ns/op 3804 B/op 16 allocs/op
|
|
||||||
BenchmarkGoji_Param20 500000 3987 ns/op 1246 B/op 2 allocs/op
|
|
||||||
BenchmarkGoJsonRest_Param20 100000 12799 ns/op 4492 B/op 21 allocs/op
|
|
||||||
BenchmarkGoRestful_Param20 100000 19451 ns/op 5244 B/op 33 allocs/op
|
|
||||||
BenchmarkGorillaMux_Param20 100000 12456 ns/op 3275 B/op 11 allocs/op
|
|
||||||
BenchmarkHttpRouter_Param20 1000000 1333 ns/op 640 B/op 1 allocs/op
|
|
||||||
BenchmarkHttpTreeMux_Param20 300000 6490 ns/op 2187 B/op 4 allocs/op
|
|
||||||
BenchmarkKocha_Param20 300000 5335 ns/op 1808 B/op 27 allocs/op
|
|
||||||
BenchmarkMacaron_Param20 200000 11325 ns/op 4252 B/op 18 allocs/op
|
|
||||||
BenchmarkMartini_Param20 20000 64419 ns/op 3644 B/op 14 allocs/op
|
|
||||||
BenchmarkPat_Param20 50000 24672 ns/op 4888 B/op 151 allocs/op
|
|
||||||
BenchmarkPossum_Param20 1000000 2085 ns/op 624 B/op 7 allocs/op
|
|
||||||
BenchmarkR2router_Param20 300000 6809 ns/op 2283 B/op 8 allocs/op
|
|
||||||
BenchmarkRevel_Param20 100000 16600 ns/op 5551 B/op 54 allocs/op
|
|
||||||
BenchmarkRivet_Param20 200000 8428 ns/op 2620 B/op 26 allocs/op
|
|
||||||
BenchmarkTango_Param20 100000 16302 ns/op 8224 B/op 48 allocs/op
|
|
||||||
BenchmarkTigerTonic_Param20 30000 46828 ns/op 10538 B/op 178 allocs/op
|
|
||||||
BenchmarkTraffic_Param20 50000 28871 ns/op 7998 B/op 66 allocs/op
|
|
||||||
BenchmarkVulcan_Param20 1000000 2267 ns/op 98 B/op 3 allocs/op
|
|
||||||
BenchmarkZeus_Param20 300000 6828 ns/op 2507 B/op 5 allocs/op
|
|
||||||
BenchmarkAce_ParamWrite 3000000 502 ns/op 40 B/op 2 allocs/op
|
|
||||||
BenchmarkBear_ParamWrite 1000000 1303 ns/op 424 B/op 5 allocs/op
|
|
||||||
BenchmarkBeego_ParamWrite 1000000 2489 ns/op 728 B/op 11 allocs/op
|
|
||||||
BenchmarkBone_ParamWrite 1000000 1181 ns/op 384 B/op 3 allocs/op
|
|
||||||
BenchmarkDenco_ParamWrite 5000000 315 ns/op 32 B/op 1 allocs/op
|
|
||||||
BenchmarkEcho_ParamWrite 10000000 237 ns/op 8 B/op 1 allocs/op
|
|
||||||
BenchmarkGin_ParamWrite 5000000 336 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGocraftWeb_ParamWrite 1000000 2079 ns/op 664 B/op 10 allocs/op
|
|
||||||
BenchmarkGoji_ParamWrite 1000000 1092 ns/op 336 B/op 2 allocs/op
|
|
||||||
BenchmarkGoJsonRest_ParamWrite 1000000 3329 ns/op 1136 B/op 19 allocs/op
|
|
||||||
BenchmarkGoRestful_ParamWrite 200000 9273 ns/op 2504 B/op 32 allocs/op
|
|
||||||
BenchmarkGorillaMux_ParamWrite 500000 3919 ns/op 792 B/op 10 allocs/op
|
|
||||||
BenchmarkHttpRouter_ParamWrite 10000000 223 ns/op 32 B/op 1 allocs/op
|
|
||||||
BenchmarkHttpTreeMux_ParamWrite 2000000 788 ns/op 336 B/op 2 allocs/op
|
|
||||||
BenchmarkKocha_ParamWrite 3000000 549 ns/op 56 B/op 3 allocs/op
|
|
||||||
BenchmarkMacaron_ParamWrite 500000 4558 ns/op 1216 B/op 16 allocs/op
|
|
||||||
BenchmarkMartini_ParamWrite 200000 8850 ns/op 1256 B/op 16 allocs/op
|
|
||||||
BenchmarkPat_ParamWrite 500000 3679 ns/op 1088 B/op 19 allocs/op
|
|
||||||
BenchmarkPossum_ParamWrite 1000000 2114 ns/op 624 B/op 7 allocs/op
|
|
||||||
BenchmarkR2router_ParamWrite 1000000 1320 ns/op 432 B/op 6 allocs/op
|
|
||||||
BenchmarkRevel_ParamWrite 200000 8048 ns/op 2128 B/op 33 allocs/op
|
|
||||||
BenchmarkRivet_ParamWrite 1000000 1393 ns/op 472 B/op 6 allocs/op
|
|
||||||
BenchmarkTango_ParamWrite 2000000 819 ns/op 136 B/op 5 allocs/op
|
|
||||||
BenchmarkTigerTonic_ParamWrite 300000 5860 ns/op 1440 B/op 25 allocs/op
|
|
||||||
BenchmarkTraffic_ParamWrite 200000 7429 ns/op 2400 B/op 27 allocs/op
|
|
||||||
BenchmarkVulcan_ParamWrite 2000000 972 ns/op 98 B/op 3 allocs/op
|
|
||||||
BenchmarkZeus_ParamWrite 1000000 1226 ns/op 368 B/op 3 allocs/op
|
|
||||||
BenchmarkAce_GithubStatic 5000000 294 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkBear_GithubStatic 3000000 575 ns/op 88 B/op 3 allocs/op
|
|
||||||
BenchmarkBeego_GithubStatic 1000000 1561 ns/op 368 B/op 7 allocs/op
|
|
||||||
BenchmarkBone_GithubStatic 200000 12301 ns/op 2880 B/op 60 allocs/op
|
|
||||||
BenchmarkDenco_GithubStatic 20000000 74.6 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkEcho_GithubStatic 10000000 176 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGin_GithubStatic 10000000 159 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGocraftWeb_GithubStatic 1000000 1116 ns/op 304 B/op 6 allocs/op
|
|
||||||
BenchmarkGoji_GithubStatic 5000000 413 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGoRestful_GithubStatic 30000 55200 ns/op 3520 B/op 36 allocs/op
|
|
||||||
BenchmarkGoJsonRest_GithubStatic 1000000 1504 ns/op 337 B/op 12 allocs/op
|
|
||||||
BenchmarkGorillaMux_GithubStatic 100000 23620 ns/op 464 B/op 8 allocs/op
|
|
||||||
BenchmarkHttpRouter_GithubStatic 20000000 78.3 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkHttpTreeMux_GithubStatic 20000000 84.9 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkKocha_GithubStatic 20000000 111 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkMacaron_GithubStatic 1000000 2686 ns/op 752 B/op 8 allocs/op
|
|
||||||
BenchmarkMartini_GithubStatic 100000 22244 ns/op 832 B/op 11 allocs/op
|
|
||||||
BenchmarkPat_GithubStatic 100000 13278 ns/op 3648 B/op 76 allocs/op
|
|
||||||
BenchmarkPossum_GithubStatic 1000000 1429 ns/op 480 B/op 4 allocs/op
|
|
||||||
BenchmarkR2router_GithubStatic 2000000 726 ns/op 144 B/op 5 allocs/op
|
|
||||||
BenchmarkRevel_GithubStatic 300000 6271 ns/op 1288 B/op 25 allocs/op
|
|
||||||
BenchmarkRivet_GithubStatic 3000000 474 ns/op 112 B/op 2 allocs/op
|
|
||||||
BenchmarkTango_GithubStatic 1000000 1842 ns/op 256 B/op 10 allocs/op
|
|
||||||
BenchmarkTigerTonic_GithubStatic 5000000 361 ns/op 48 B/op 1 allocs/op
|
|
||||||
BenchmarkTraffic_GithubStatic 30000 47197 ns/op 18920 B/op 149 allocs/op
|
|
||||||
BenchmarkVulcan_GithubStatic 1000000 1415 ns/op 98 B/op 3 allocs/op
|
|
||||||
BenchmarkZeus_GithubStatic 1000000 2522 ns/op 512 B/op 11 allocs/op
|
|
||||||
BenchmarkAce_GithubParam 3000000 578 ns/op 96 B/op 1 allocs/op
|
|
||||||
BenchmarkBear_GithubParam 1000000 1592 ns/op 464 B/op 5 allocs/op
|
|
||||||
BenchmarkBeego_GithubParam 1000000 2891 ns/op 784 B/op 11 allocs/op
|
|
||||||
BenchmarkBone_GithubParam 300000 6440 ns/op 1456 B/op 16 allocs/op
|
|
||||||
BenchmarkDenco_GithubParam 3000000 514 ns/op 128 B/op 1 allocs/op
|
|
||||||
BenchmarkEcho_GithubParam 5000000 292 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGin_GithubParam 10000000 242 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGocraftWeb_GithubParam 1000000 2343 ns/op 720 B/op 10 allocs/op
|
|
||||||
BenchmarkGoji_GithubParam 1000000 1566 ns/op 336 B/op 2 allocs/op
|
|
||||||
BenchmarkGoJsonRest_GithubParam 1000000 2828 ns/op 721 B/op 15 allocs/op
|
|
||||||
BenchmarkGoRestful_GithubParam 10000 177711 ns/op 2816 B/op 35 allocs/op
|
|
||||||
BenchmarkGorillaMux_GithubParam 100000 13591 ns/op 816 B/op 9 allocs/op
|
|
||||||
BenchmarkHttpRouter_GithubParam 5000000 352 ns/op 96 B/op 1 allocs/op
|
|
||||||
BenchmarkHttpTreeMux_GithubParam 2000000 973 ns/op 336 B/op 2 allocs/op
|
|
||||||
BenchmarkKocha_GithubParam 2000000 889 ns/op 128 B/op 5 allocs/op
|
|
||||||
BenchmarkMacaron_GithubParam 500000 4047 ns/op 1168 B/op 12 allocs/op
|
|
||||||
BenchmarkMartini_GithubParam 50000 28982 ns/op 1184 B/op 12 allocs/op
|
|
||||||
BenchmarkPat_GithubParam 200000 8747 ns/op 2480 B/op 56 allocs/op
|
|
||||||
BenchmarkPossum_GithubParam 1000000 2158 ns/op 624 B/op 7 allocs/op
|
|
||||||
BenchmarkR2router_GithubParam 1000000 1352 ns/op 432 B/op 6 allocs/op
|
|
||||||
BenchmarkRevel_GithubParam 200000 7673 ns/op 1784 B/op 30 allocs/op
|
|
||||||
BenchmarkRivet_GithubParam 1000000 1573 ns/op 480 B/op 6 allocs/op
|
|
||||||
BenchmarkTango_GithubParam 1000000 2418 ns/op 480 B/op 13 allocs/op
|
|
||||||
BenchmarkTigerTonic_GithubParam 300000 6048 ns/op 1440 B/op 28 allocs/op
|
|
||||||
BenchmarkTraffic_GithubParam 100000 20143 ns/op 6024 B/op 55 allocs/op
|
|
||||||
BenchmarkVulcan_GithubParam 1000000 2224 ns/op 98 B/op 3 allocs/op
|
|
||||||
BenchmarkZeus_GithubParam 500000 4156 ns/op 1312 B/op 12 allocs/op
|
|
||||||
BenchmarkAce_GithubAll 10000 109482 ns/op 13792 B/op 167 allocs/op
|
|
||||||
BenchmarkBear_GithubAll 10000 287490 ns/op 79952 B/op 943 allocs/op
|
|
||||||
BenchmarkBeego_GithubAll 3000 562184 ns/op 146272 B/op 2092 allocs/op
|
|
||||||
BenchmarkBone_GithubAll 500 2578716 ns/op 648016 B/op 8119 allocs/op
|
|
||||||
BenchmarkDenco_GithubAll 20000 94955 ns/op 20224 B/op 167 allocs/op
|
|
||||||
BenchmarkEcho_GithubAll 30000 58705 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGin_GithubAll 30000 50991 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGocraftWeb_GithubAll 5000 449648 ns/op 133280 B/op 1889 allocs/op
|
|
||||||
BenchmarkGoji_GithubAll 2000 689748 ns/op 56113 B/op 334 allocs/op
|
|
||||||
BenchmarkGoJsonRest_GithubAll 5000 537769 ns/op 135995 B/op 2940 allocs/op
|
|
||||||
BenchmarkGoRestful_GithubAll 100 18410628 ns/op 797236 B/op 7725 allocs/op
|
|
||||||
BenchmarkGorillaMux_GithubAll 200 8036360 ns/op 153137 B/op 1791 allocs/op
|
|
||||||
BenchmarkHttpRouter_GithubAll 20000 63506 ns/op 13792 B/op 167 allocs/op
|
|
||||||
BenchmarkHttpTreeMux_GithubAll 10000 165927 ns/op 56112 B/op 334 allocs/op
|
|
||||||
BenchmarkKocha_GithubAll 10000 171362 ns/op 23304 B/op 843 allocs/op
|
|
||||||
BenchmarkMacaron_GithubAll 2000 817008 ns/op 224960 B/op 2315 allocs/op
|
|
||||||
BenchmarkMartini_GithubAll 100 12609209 ns/op 237952 B/op 2686 allocs/op
|
|
||||||
BenchmarkPat_GithubAll 300 4830398 ns/op 1504101 B/op 32222 allocs/op
|
|
||||||
BenchmarkPossum_GithubAll 10000 301716 ns/op 97440 B/op 812 allocs/op
|
|
||||||
BenchmarkR2router_GithubAll 10000 270691 ns/op 77328 B/op 1182 allocs/op
|
|
||||||
BenchmarkRevel_GithubAll 1000 1491919 ns/op 345553 B/op 5918 allocs/op
|
|
||||||
BenchmarkRivet_GithubAll 10000 283860 ns/op 84272 B/op 1079 allocs/op
|
|
||||||
BenchmarkTango_GithubAll 5000 473821 ns/op 87078 B/op 2470 allocs/op
|
|
||||||
BenchmarkTigerTonic_GithubAll 2000 1120131 ns/op 241088 B/op 6052 allocs/op
|
|
||||||
BenchmarkTraffic_GithubAll 200 8708979 ns/op 2664762 B/op 22390 allocs/op
|
|
||||||
BenchmarkVulcan_GithubAll 5000 353392 ns/op 19894 B/op 609 allocs/op
|
|
||||||
BenchmarkZeus_GithubAll 2000 944234 ns/op 300688 B/op 2648 allocs/op
|
|
||||||
BenchmarkAce_GPlusStatic 5000000 251 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkBear_GPlusStatic 3000000 415 ns/op 72 B/op 3 allocs/op
|
|
||||||
BenchmarkBeego_GPlusStatic 1000000 1416 ns/op 352 B/op 7 allocs/op
|
|
||||||
BenchmarkBone_GPlusStatic 10000000 192 ns/op 32 B/op 1 allocs/op
|
|
||||||
BenchmarkDenco_GPlusStatic 30000000 47.6 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkEcho_GPlusStatic 10000000 131 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGin_GPlusStatic 10000000 131 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGocraftWeb_GPlusStatic 1000000 1035 ns/op 288 B/op 6 allocs/op
|
|
||||||
BenchmarkGoji_GPlusStatic 5000000 304 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGoJsonRest_GPlusStatic 1000000 1286 ns/op 337 B/op 12 allocs/op
|
|
||||||
BenchmarkGoRestful_GPlusStatic 200000 9649 ns/op 2160 B/op 30 allocs/op
|
|
||||||
BenchmarkGorillaMux_GPlusStatic 1000000 2346 ns/op 464 B/op 8 allocs/op
|
|
||||||
BenchmarkHttpRouter_GPlusStatic 30000000 42.7 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkHttpTreeMux_GPlusStatic 30000000 49.5 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkKocha_GPlusStatic 20000000 74.8 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkMacaron_GPlusStatic 1000000 2520 ns/op 736 B/op 8 allocs/op
|
|
||||||
BenchmarkMartini_GPlusStatic 300000 5310 ns/op 832 B/op 11 allocs/op
|
|
||||||
BenchmarkPat_GPlusStatic 5000000 398 ns/op 96 B/op 2 allocs/op
|
|
||||||
BenchmarkPossum_GPlusStatic 1000000 1434 ns/op 480 B/op 4 allocs/op
|
|
||||||
BenchmarkR2router_GPlusStatic 2000000 646 ns/op 144 B/op 5 allocs/op
|
|
||||||
BenchmarkRevel_GPlusStatic 300000 6172 ns/op 1272 B/op 25 allocs/op
|
|
||||||
BenchmarkRivet_GPlusStatic 3000000 444 ns/op 112 B/op 2 allocs/op
|
|
||||||
BenchmarkTango_GPlusStatic 1000000 1400 ns/op 208 B/op 10 allocs/op
|
|
||||||
BenchmarkTigerTonic_GPlusStatic 10000000 213 ns/op 32 B/op 1 allocs/op
|
|
||||||
BenchmarkTraffic_GPlusStatic 1000000 3091 ns/op 1208 B/op 16 allocs/op
|
|
||||||
BenchmarkVulcan_GPlusStatic 2000000 863 ns/op 98 B/op 3 allocs/op
|
|
||||||
BenchmarkZeus_GPlusStatic 10000000 237 ns/op 16 B/op 1 allocs/op
|
|
||||||
BenchmarkAce_GPlusParam 3000000 435 ns/op 64 B/op 1 allocs/op
|
|
||||||
BenchmarkBear_GPlusParam 1000000 1205 ns/op 448 B/op 5 allocs/op
|
|
||||||
BenchmarkBeego_GPlusParam 1000000 2494 ns/op 720 B/op 10 allocs/op
|
|
||||||
BenchmarkBone_GPlusParam 1000000 1126 ns/op 384 B/op 3 allocs/op
|
|
||||||
BenchmarkDenco_GPlusParam 5000000 325 ns/op 64 B/op 1 allocs/op
|
|
||||||
BenchmarkEcho_GPlusParam 10000000 168 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGin_GPlusParam 10000000 170 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGocraftWeb_GPlusParam 1000000 1895 ns/op 656 B/op 9 allocs/op
|
|
||||||
BenchmarkGoji_GPlusParam 1000000 1071 ns/op 336 B/op 2 allocs/op
|
|
||||||
BenchmarkGoJsonRest_GPlusParam 1000000 2282 ns/op 657 B/op 14 allocs/op
|
|
||||||
BenchmarkGoRestful_GPlusParam 100000 19400 ns/op 2560 B/op 33 allocs/op
|
|
||||||
BenchmarkGorillaMux_GPlusParam 500000 5001 ns/op 784 B/op 9 allocs/op
|
|
||||||
BenchmarkHttpRouter_GPlusParam 10000000 240 ns/op 64 B/op 1 allocs/op
|
|
||||||
BenchmarkHttpTreeMux_GPlusParam 2000000 797 ns/op 336 B/op 2 allocs/op
|
|
||||||
BenchmarkKocha_GPlusParam 3000000 505 ns/op 56 B/op 3 allocs/op
|
|
||||||
BenchmarkMacaron_GPlusParam 1000000 3668 ns/op 1104 B/op 11 allocs/op
|
|
||||||
BenchmarkMartini_GPlusParam 200000 10672 ns/op 1152 B/op 12 allocs/op
|
|
||||||
BenchmarkPat_GPlusParam 1000000 2376 ns/op 704 B/op 14 allocs/op
|
|
||||||
BenchmarkPossum_GPlusParam 1000000 2090 ns/op 624 B/op 7 allocs/op
|
|
||||||
BenchmarkR2router_GPlusParam 1000000 1233 ns/op 432 B/op 6 allocs/op
|
|
||||||
BenchmarkRevel_GPlusParam 200000 6778 ns/op 1704 B/op 28 allocs/op
|
|
||||||
BenchmarkRivet_GPlusParam 1000000 1279 ns/op 464 B/op 5 allocs/op
|
|
||||||
BenchmarkTango_GPlusParam 1000000 1981 ns/op 272 B/op 10 allocs/op
|
|
||||||
BenchmarkTigerTonic_GPlusParam 500000 3893 ns/op 1064 B/op 19 allocs/op
|
|
||||||
BenchmarkTraffic_GPlusParam 200000 6585 ns/op 2000 B/op 23 allocs/op
|
|
||||||
BenchmarkVulcan_GPlusParam 1000000 1233 ns/op 98 B/op 3 allocs/op
|
|
||||||
BenchmarkZeus_GPlusParam 1000000 1350 ns/op 368 B/op 3 allocs/op
|
|
||||||
BenchmarkAce_GPlus2Params 3000000 512 ns/op 64 B/op 1 allocs/op
|
|
||||||
BenchmarkBear_GPlus2Params 1000000 1564 ns/op 464 B/op 5 allocs/op
|
|
||||||
BenchmarkBeego_GPlus2Params 1000000 3043 ns/op 784 B/op 11 allocs/op
|
|
||||||
BenchmarkBone_GPlus2Params 1000000 3152 ns/op 736 B/op 7 allocs/op
|
|
||||||
BenchmarkDenco_GPlus2Params 3000000 431 ns/op 64 B/op 1 allocs/op
|
|
||||||
BenchmarkEcho_GPlus2Params 5000000 247 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGin_GPlus2Params 10000000 219 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGocraftWeb_GPlus2Params 1000000 2363 ns/op 720 B/op 10 allocs/op
|
|
||||||
BenchmarkGoji_GPlus2Params 1000000 1540 ns/op 336 B/op 2 allocs/op
|
|
||||||
BenchmarkGoJsonRest_GPlus2Params 1000000 2872 ns/op 721 B/op 15 allocs/op
|
|
||||||
BenchmarkGoRestful_GPlus2Params 100000 23030 ns/op 2720 B/op 35 allocs/op
|
|
||||||
BenchmarkGorillaMux_GPlus2Params 200000 10516 ns/op 816 B/op 9 allocs/op
|
|
||||||
BenchmarkHttpRouter_GPlus2Params 5000000 273 ns/op 64 B/op 1 allocs/op
|
|
||||||
BenchmarkHttpTreeMux_GPlus2Params 2000000 939 ns/op 336 B/op 2 allocs/op
|
|
||||||
BenchmarkKocha_GPlus2Params 2000000 844 ns/op 128 B/op 5 allocs/op
|
|
||||||
BenchmarkMacaron_GPlus2Params 500000 3914 ns/op 1168 B/op 12 allocs/op
|
|
||||||
BenchmarkMartini_GPlus2Params 50000 35759 ns/op 1280 B/op 16 allocs/op
|
|
||||||
BenchmarkPat_GPlus2Params 200000 7089 ns/op 2304 B/op 41 allocs/op
|
|
||||||
BenchmarkPossum_GPlus2Params 1000000 2093 ns/op 624 B/op 7 allocs/op
|
|
||||||
BenchmarkR2router_GPlus2Params 1000000 1320 ns/op 432 B/op 6 allocs/op
|
|
||||||
BenchmarkRevel_GPlus2Params 200000 7351 ns/op 1800 B/op 30 allocs/op
|
|
||||||
BenchmarkRivet_GPlus2Params 1000000 1485 ns/op 480 B/op 6 allocs/op
|
|
||||||
BenchmarkTango_GPlus2Params 1000000 2111 ns/op 448 B/op 12 allocs/op
|
|
||||||
BenchmarkTigerTonic_GPlus2Params 300000 6271 ns/op 1528 B/op 28 allocs/op
|
|
||||||
BenchmarkTraffic_GPlus2Params 100000 14886 ns/op 3312 B/op 34 allocs/op
|
|
||||||
BenchmarkVulcan_GPlus2Params 1000000 1883 ns/op 98 B/op 3 allocs/op
|
|
||||||
BenchmarkZeus_GPlus2Params 1000000 2686 ns/op 784 B/op 6 allocs/op
|
|
||||||
BenchmarkAce_GPlusAll 300000 5912 ns/op 640 B/op 11 allocs/op
|
|
||||||
BenchmarkBear_GPlusAll 100000 16448 ns/op 5072 B/op 61 allocs/op
|
|
||||||
BenchmarkBeego_GPlusAll 50000 32916 ns/op 8976 B/op 129 allocs/op
|
|
||||||
BenchmarkBone_GPlusAll 50000 25836 ns/op 6992 B/op 76 allocs/op
|
|
||||||
BenchmarkDenco_GPlusAll 500000 4462 ns/op 672 B/op 11 allocs/op
|
|
||||||
BenchmarkEcho_GPlusAll 500000 2806 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGin_GPlusAll 500000 2579 ns/op 0 B/op 0 allocs/op
|
|
||||||
BenchmarkGocraftWeb_GPlusAll 50000 25223 ns/op 8144 B/op 116 allocs/op
|
|
||||||
BenchmarkGoji_GPlusAll 100000 14237 ns/op 3696 B/op 22 allocs/op
|
|
||||||
BenchmarkGoJsonRest_GPlusAll 50000 29227 ns/op 8221 B/op 183 allocs/op
|
|
||||||
BenchmarkGoRestful_GPlusAll 10000 203144 ns/op 36064 B/op 441 allocs/op
|
|
||||||
BenchmarkGorillaMux_GPlusAll 20000 80906 ns/op 9712 B/op 115 allocs/op
|
|
||||||
BenchmarkHttpRouter_GPlusAll 500000 3040 ns/op 640 B/op 11 allocs/op
|
|
||||||
BenchmarkHttpTreeMux_GPlusAll 200000 9627 ns/op 3696 B/op 22 allocs/op
|
|
||||||
BenchmarkKocha_GPlusAll 200000 8108 ns/op 976 B/op 43 allocs/op
|
|
||||||
BenchmarkMacaron_GPlusAll 30000 48083 ns/op 13968 B/op 142 allocs/op
|
|
||||||
BenchmarkMartini_GPlusAll 10000 196978 ns/op 15072 B/op 178 allocs/op
|
|
||||||
BenchmarkPat_GPlusAll 30000 58865 ns/op 16880 B/op 343 allocs/op
|
|
||||||
BenchmarkPossum_GPlusAll 100000 19685 ns/op 6240 B/op 52 allocs/op
|
|
||||||
BenchmarkR2router_GPlusAll 100000 16251 ns/op 5040 B/op 76 allocs/op
|
|
||||||
BenchmarkRevel_GPlusAll 20000 93489 ns/op 21656 B/op 368 allocs/op
|
|
||||||
BenchmarkRivet_GPlusAll 100000 16907 ns/op 5408 B/op 64 allocs/op
|
|
||||||
```
|
|
||||||
-150
@@ -1,150 +0,0 @@
|
|||||||
#CHANGELOG
|
|
||||||
|
|
||||||
###Gin 1.0rc2 (...)
|
|
||||||
|
|
||||||
- [PERFORMANCE] Fast path for writing Content-Type.
|
|
||||||
- [PERFORMANCE] Much faster 404 routing
|
|
||||||
- [PERFORMANCE] Allocation optimizations
|
|
||||||
- [PERFORMANCE] Faster root tree lookup
|
|
||||||
- [PERFORMANCE] Zero overhead, String() and JSON() rendering.
|
|
||||||
- [PERFORMANCE] Faster ClientIP parsing
|
|
||||||
- [PERFORMANCE] Much faster SSE implementation
|
|
||||||
- [NEW] Benchmarks suite
|
|
||||||
- [NEW] Bind validation can be disabled and replaced with custom validators.
|
|
||||||
- [NEW] More flexible HTML render
|
|
||||||
- [NEW] Multipart and PostForm bindings
|
|
||||||
- [NEW] Adds method to return all the registered routes
|
|
||||||
- [NEW] Context.HandlerName() returns the main handler's name
|
|
||||||
- [NEW] Adds Error.IsType() helper
|
|
||||||
- [FIX] Binding multipart form
|
|
||||||
- [FIX] Integration tests
|
|
||||||
- [FIX] Crash when binding non struct object in Context.
|
|
||||||
- [FIX] RunTLS() implementation
|
|
||||||
- [FIX] Logger() unit tests
|
|
||||||
- [FIX] Adds SetHTMLTemplate() warning
|
|
||||||
- [FIX] Context.IsAborted()
|
|
||||||
- [FIX] More unit tests
|
|
||||||
- [FIX] JSON, XML, HTML renders accept custom content-types
|
|
||||||
- [FIX] gin.AbortIndex is unexported
|
|
||||||
- [FIX] Better approach to avoid directory listing in StaticFS()
|
|
||||||
- [FIX] Context.ClientIP() always returns the IP with trimmed spaces.
|
|
||||||
- [FIX] Better warning when running in debug mode.
|
|
||||||
- [FIX] Google App Engine integration. debugPrint does not use os.Stdout
|
|
||||||
- [FIX] Fixes integer overflow in error type
|
|
||||||
- [FIX] Error implements the json.Marshaller interface
|
|
||||||
- [FIX] MIT license in every file
|
|
||||||
|
|
||||||
|
|
||||||
###Gin 1.0rc1 (May 22, 2015)
|
|
||||||
|
|
||||||
- [PERFORMANCE] Zero allocation router
|
|
||||||
- [PERFORMANCE] Faster JSON, XML and text rendering
|
|
||||||
- [PERFORMANCE] Custom hand optimized HttpRouter for Gin
|
|
||||||
- [PERFORMANCE] Misc code optimizations. Inlining, tail call optimizations
|
|
||||||
- [NEW] Built-in support for golang.org/x/net/context
|
|
||||||
- [NEW] Any(path, handler). Create a route that matches any path
|
|
||||||
- [NEW] Refactored rendering pipeline (faster and static typeded)
|
|
||||||
- [NEW] Refactored errors API
|
|
||||||
- [NEW] IndentedJSON() prints pretty JSON
|
|
||||||
- [NEW] Added gin.DefaultWriter
|
|
||||||
- [NEW] UNIX socket support
|
|
||||||
- [NEW] RouterGroup.BasePath is exposed
|
|
||||||
- [NEW] JSON validation using go-validate-yourself (very powerful options)
|
|
||||||
- [NEW] Completed suite of unit tests
|
|
||||||
- [NEW] HTTP streaming with c.Stream()
|
|
||||||
- [NEW] StaticFile() creates a router for serving just one file.
|
|
||||||
- [NEW] StaticFS() has an option to disable directory listing.
|
|
||||||
- [NEW] StaticFS() for serving static files through virtual filesystems
|
|
||||||
- [NEW] Server-Sent Events native support
|
|
||||||
- [NEW] WrapF() and WrapH() helpers for wrapping http.HandlerFunc and http.Handler
|
|
||||||
- [NEW] Added LoggerWithWriter() middleware
|
|
||||||
- [NEW] Added RecoveryWithWriter() middleware
|
|
||||||
- [NEW] Added DefaultPostFormValue()
|
|
||||||
- [NEW] Added DefaultFormValue()
|
|
||||||
- [NEW] Added DefaultParamValue()
|
|
||||||
- [FIX] BasicAuth() when using custom realm
|
|
||||||
- [FIX] Bug when serving static files in nested routing group
|
|
||||||
- [FIX] Redirect using built-in http.Redirect()
|
|
||||||
- [FIX] Logger when printing the requested path
|
|
||||||
- [FIX] Documentation typos
|
|
||||||
- [FIX] Context.Engine renamed to Context.engine
|
|
||||||
- [FIX] Better debugging messages
|
|
||||||
- [FIX] ErrorLogger
|
|
||||||
- [FIX] Debug HTTP render
|
|
||||||
- [FIX] Refactored binding and render modules
|
|
||||||
- [FIX] Refactored Context initialization
|
|
||||||
- [FIX] Refactored BasicAuth()
|
|
||||||
- [FIX] NoMethod/NoRoute handlers
|
|
||||||
- [FIX] Hijacking http
|
|
||||||
- [FIX] Better support for Google App Engine (using log instead of fmt)
|
|
||||||
|
|
||||||
|
|
||||||
###Gin 0.6 (Mar 9, 2015)
|
|
||||||
|
|
||||||
- [NEW] Support multipart/form-data
|
|
||||||
- [NEW] NoMethod handler
|
|
||||||
- [NEW] Validate sub structures
|
|
||||||
- [NEW] Support for HTTP Realm Auth
|
|
||||||
- [FIX] Unsigned integers in binding
|
|
||||||
- [FIX] Improve color logger
|
|
||||||
|
|
||||||
|
|
||||||
###Gin 0.5 (Feb 7, 2015)
|
|
||||||
|
|
||||||
- [NEW] Content Negotiation
|
|
||||||
- [FIX] Solved security bug that allow a client to spoof ip
|
|
||||||
- [FIX] Fix unexported/ignored fields in binding
|
|
||||||
|
|
||||||
|
|
||||||
###Gin 0.4 (Aug 21, 2014)
|
|
||||||
|
|
||||||
- [NEW] Development mode
|
|
||||||
- [NEW] Unit tests
|
|
||||||
- [NEW] Add Content.Redirect()
|
|
||||||
- [FIX] Deferring WriteHeader()
|
|
||||||
- [FIX] Improved documentation for model binding
|
|
||||||
|
|
||||||
|
|
||||||
###Gin 0.3 (Jul 18, 2014)
|
|
||||||
|
|
||||||
- [PERFORMANCE] Normal log and error log are printed in the same call.
|
|
||||||
- [PERFORMANCE] Improve performance of NoRouter()
|
|
||||||
- [PERFORMANCE] Improve context's memory locality, reduce CPU cache faults.
|
|
||||||
- [NEW] Flexible rendering API
|
|
||||||
- [NEW] Add Context.File()
|
|
||||||
- [NEW] Add shorcut RunTLS() for http.ListenAndServeTLS
|
|
||||||
- [FIX] Rename NotFound404() to NoRoute()
|
|
||||||
- [FIX] Errors in context are purged
|
|
||||||
- [FIX] Adds HEAD method in Static file serving
|
|
||||||
- [FIX] Refactors Static() file serving
|
|
||||||
- [FIX] Using keyed initialization to fix app-engine integration
|
|
||||||
- [FIX] Can't unmarshal JSON array, #63
|
|
||||||
- [FIX] Renaming Context.Req to Context.Request
|
|
||||||
- [FIX] Check application/x-www-form-urlencoded when parsing form
|
|
||||||
|
|
||||||
|
|
||||||
###Gin 0.2b (Jul 08, 2014)
|
|
||||||
- [PERFORMANCE] Using sync.Pool to allocatio/gc overhead
|
|
||||||
- [NEW] Travis CI integration
|
|
||||||
- [NEW] Completely new logger
|
|
||||||
- [NEW] New API for serving static files. gin.Static()
|
|
||||||
- [NEW] gin.H() can be serialized into XML
|
|
||||||
- [NEW] Typed errors. Errors can be typed. Internet/external/custom.
|
|
||||||
- [NEW] Support for Godeps
|
|
||||||
- [NEW] Travis/Godocs badges in README
|
|
||||||
- [NEW] New Bind() and BindWith() methods for parsing request body.
|
|
||||||
- [NEW] Add Content.Copy()
|
|
||||||
- [NEW] Add context.LastError()
|
|
||||||
- [NEW] Add shorcut for OPTIONS HTTP method
|
|
||||||
- [FIX] Tons of README fixes
|
|
||||||
- [FIX] Header is written before body
|
|
||||||
- [FIX] BasicAuth() and changes API a little bit
|
|
||||||
- [FIX] Recovery() middleware only prints panics
|
|
||||||
- [FIX] Context.Get() does not panic anymore. Use MustGet() instead.
|
|
||||||
- [FIX] Multiple http.WriteHeader() in NotFound handlers
|
|
||||||
- [FIX] Engine.Run() panics if http server can't be setted up
|
|
||||||
- [FIX] Crash when route path doesn't start with '/'
|
|
||||||
- [FIX] Do not update header when status code is negative
|
|
||||||
- [FIX] Setting response headers before calling WriteHeader in context.String()
|
|
||||||
- [FIX] Add MIT license
|
|
||||||
- [FIX] Changes behaviour of ErrorLogger() and Logger()
|
|
||||||
-21
@@ -1,21 +0,0 @@
|
|||||||
The MIT License (MIT)
|
|
||||||
|
|
||||||
Copyright (c) 2014 Manuel Martínez-Almeida
|
|
||||||
|
|
||||||
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.
|
|
||||||
-733
@@ -1,733 +0,0 @@
|
|||||||
|
|
||||||
#Gin Web Framework
|
|
||||||
|
|
||||||
<img align="right" src="https://raw.githubusercontent.com/gin-gonic/gin/master/logo.jpg">
|
|
||||||
[](https://travis-ci.org/gin-gonic/gin)
|
|
||||||
[](https://codecov.io/gh/gin-gonic/gin)
|
|
||||||
[](https://goreportcard.com/report/github.com/gin-gonic/gin)
|
|
||||||
[](https://godoc.org/github.com/gin-gonic/gin)
|
|
||||||
[](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
|
||||||
|
|
||||||
Gin is a web framework written in Go (Golang). It features a martini-like API with much better performance, up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
```sh
|
|
||||||
$ cat test.go
|
|
||||||
```
|
|
||||||
```go
|
|
||||||
package main
|
|
||||||
|
|
||||||
import "gopkg.in/gin-gonic/gin.v1"
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
r := gin.Default()
|
|
||||||
r.GET("/ping", func(c *gin.Context) {
|
|
||||||
c.JSON(200, gin.H{
|
|
||||||
"message": "pong",
|
|
||||||
})
|
|
||||||
})
|
|
||||||
r.Run() // listen and serve on 0.0.0.0:8080
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Benchmarks
|
|
||||||
|
|
||||||
Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter)
|
|
||||||
|
|
||||||
[See all benchmarks](/BENCHMARKS.md)
|
|
||||||
|
|
||||||
|
|
||||||
Benchmark name | (1) | (2) | (3) | (4)
|
|
||||||
--------------------------------|----------:|----------:|----------:|------:
|
|
||||||
BenchmarkAce_GithubAll | 10000 | 109482 | 13792 | 167
|
|
||||||
BenchmarkBear_GithubAll | 10000 | 287490 | 79952 | 943
|
|
||||||
BenchmarkBeego_GithubAll | 3000 | 562184 | 146272 | 2092
|
|
||||||
BenchmarkBone_GithubAll | 500 | 2578716 | 648016 | 8119
|
|
||||||
BenchmarkDenco_GithubAll | 20000 | 94955 | 20224 | 167
|
|
||||||
BenchmarkEcho_GithubAll | 30000 | 58705 | 0 | 0
|
|
||||||
**BenchmarkGin_GithubAll** | **30000** | **50991** | **0** | **0**
|
|
||||||
BenchmarkGocraftWeb_GithubAll | 5000 | 449648 | 133280 | 1889
|
|
||||||
BenchmarkGoji_GithubAll | 2000 | 689748 | 56113 | 334
|
|
||||||
BenchmarkGoJsonRest_GithubAll | 5000 | 537769 | 135995 | 2940
|
|
||||||
BenchmarkGoRestful_GithubAll | 100 | 18410628 | 797236 | 7725
|
|
||||||
BenchmarkGorillaMux_GithubAll | 200 | 8036360 | 153137 | 1791
|
|
||||||
BenchmarkHttpRouter_GithubAll | 20000 | 63506 | 13792 | 167
|
|
||||||
BenchmarkHttpTreeMux_GithubAll | 10000 | 165927 | 56112 | 334
|
|
||||||
BenchmarkKocha_GithubAll | 10000 | 171362 | 23304 | 843
|
|
||||||
BenchmarkMacaron_GithubAll | 2000 | 817008 | 224960 | 2315
|
|
||||||
BenchmarkMartini_GithubAll | 100 | 12609209 | 237952 | 2686
|
|
||||||
BenchmarkPat_GithubAll | 300 | 4830398 | 1504101 | 32222
|
|
||||||
BenchmarkPossum_GithubAll | 10000 | 301716 | 97440 | 812
|
|
||||||
BenchmarkR2router_GithubAll | 10000 | 270691 | 77328 | 1182
|
|
||||||
BenchmarkRevel_GithubAll | 1000 | 1491919 | 345553 | 5918
|
|
||||||
BenchmarkRivet_GithubAll | 10000 | 283860 | 84272 | 1079
|
|
||||||
BenchmarkTango_GithubAll | 5000 | 473821 | 87078 | 2470
|
|
||||||
BenchmarkTigerTonic_GithubAll | 2000 | 1120131 | 241088 | 6052
|
|
||||||
BenchmarkTraffic_GithubAll | 200 | 8708979 | 2664762 | 22390
|
|
||||||
BenchmarkVulcan_GithubAll | 5000 | 353392 | 19894 | 609
|
|
||||||
BenchmarkZeus_GithubAll | 2000 | 944234 | 300688 | 2648
|
|
||||||
|
|
||||||
(1): Total Repetitions
|
|
||||||
(2): Single Repetition Duration (ns/op)
|
|
||||||
(3): Heap Memory (B/op)
|
|
||||||
(4): Average Allocations per Repetition (allocs/op)
|
|
||||||
|
|
||||||
## Gin v1. stable
|
|
||||||
|
|
||||||
- [x] Zero allocation router.
|
|
||||||
- [x] Still the fastest http router and framework. From routing to writing.
|
|
||||||
- [x] Complete suite of unit tests
|
|
||||||
- [x] Battle tested
|
|
||||||
- [x] API frozen, new releases will not break your code.
|
|
||||||
|
|
||||||
|
|
||||||
## Start using it
|
|
||||||
|
|
||||||
1. Download and install it:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
$ go get gopkg.in/gin-gonic/gin.v1
|
|
||||||
```
|
|
||||||
|
|
||||||
2. Import it in your code:
|
|
||||||
|
|
||||||
```go
|
|
||||||
import "gopkg.in/gin-gonic/gin.v1"
|
|
||||||
```
|
|
||||||
|
|
||||||
3. (Optional) Import `net/http`. This is required for example if using constants such as `http.StatusOK`.
|
|
||||||
|
|
||||||
```go
|
|
||||||
import "net/http"
|
|
||||||
```
|
|
||||||
|
|
||||||
## API Examples
|
|
||||||
|
|
||||||
#### Using GET, POST, PUT, PATCH, DELETE and OPTIONS
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
// Creates a gin router with default middleware:
|
|
||||||
// logger and recovery (crash-free) middleware
|
|
||||||
router := gin.Default()
|
|
||||||
|
|
||||||
router.GET("/someGet", getting)
|
|
||||||
router.POST("/somePost", posting)
|
|
||||||
router.PUT("/somePut", putting)
|
|
||||||
router.DELETE("/someDelete", deleting)
|
|
||||||
router.PATCH("/somePatch", patching)
|
|
||||||
router.HEAD("/someHead", head)
|
|
||||||
router.OPTIONS("/someOptions", options)
|
|
||||||
|
|
||||||
// By default it serves on :8080 unless a
|
|
||||||
// PORT environment variable was defined.
|
|
||||||
router.Run()
|
|
||||||
// router.Run(":3000") for a hard coded port
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Parameters in path
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
|
|
||||||
// This handler will match /user/john but will not match neither /user/ or /user
|
|
||||||
router.GET("/user/:name", func(c *gin.Context) {
|
|
||||||
name := c.Param("name")
|
|
||||||
c.String(http.StatusOK, "Hello %s", name)
|
|
||||||
})
|
|
||||||
|
|
||||||
// However, this one will match /user/john/ and also /user/john/send
|
|
||||||
// If no other routers match /user/john, it will redirect to /user/john/
|
|
||||||
router.GET("/user/:name/*action", func(c *gin.Context) {
|
|
||||||
name := c.Param("name")
|
|
||||||
action := c.Param("action")
|
|
||||||
message := name + " is " + action
|
|
||||||
c.String(http.StatusOK, message)
|
|
||||||
})
|
|
||||||
|
|
||||||
router.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Querystring parameters
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
|
|
||||||
// Query string parameters are parsed using the existing underlying request object.
|
|
||||||
// The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe
|
|
||||||
router.GET("/welcome", func(c *gin.Context) {
|
|
||||||
firstname := c.DefaultQuery("firstname", "Guest")
|
|
||||||
lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")
|
|
||||||
|
|
||||||
c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
|
|
||||||
})
|
|
||||||
router.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Multipart/Urlencoded Form
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
|
|
||||||
router.POST("/form_post", func(c *gin.Context) {
|
|
||||||
message := c.PostForm("message")
|
|
||||||
nick := c.DefaultPostForm("nick", "anonymous")
|
|
||||||
|
|
||||||
c.JSON(200, gin.H{
|
|
||||||
"status": "posted",
|
|
||||||
"message": message,
|
|
||||||
"nick": nick,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
router.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Another example: query + post form
|
|
||||||
|
|
||||||
```
|
|
||||||
POST /post?id=1234&page=1 HTTP/1.1
|
|
||||||
Content-Type: application/x-www-form-urlencoded
|
|
||||||
|
|
||||||
name=manu&message=this_is_great
|
|
||||||
```
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
|
|
||||||
router.POST("/post", func(c *gin.Context) {
|
|
||||||
|
|
||||||
id := c.Query("id")
|
|
||||||
page := c.DefaultQuery("page", "0")
|
|
||||||
name := c.PostForm("name")
|
|
||||||
message := c.PostForm("message")
|
|
||||||
|
|
||||||
fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
|
|
||||||
})
|
|
||||||
router.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```
|
|
||||||
id: 1234; page: 1; name: manu; message: this_is_great
|
|
||||||
```
|
|
||||||
|
|
||||||
### Another example: upload file
|
|
||||||
|
|
||||||
References issue [#548](https://github.com/gin-gonic/gin/issues/548).
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
|
|
||||||
router.POST("/upload", func(c *gin.Context) {
|
|
||||||
|
|
||||||
file, header , err := c.Request.FormFile("upload")
|
|
||||||
filename := header.Filename
|
|
||||||
fmt.Println(header.Filename)
|
|
||||||
out, err := os.Create("./tmp/"+filename+".png")
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
defer out.Close()
|
|
||||||
_, err = io.Copy(out, file)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
router.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Grouping routes
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
|
|
||||||
// Simple group: v1
|
|
||||||
v1 := router.Group("/v1")
|
|
||||||
{
|
|
||||||
v1.POST("/login", loginEndpoint)
|
|
||||||
v1.POST("/submit", submitEndpoint)
|
|
||||||
v1.POST("/read", readEndpoint)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Simple group: v2
|
|
||||||
v2 := router.Group("/v2")
|
|
||||||
{
|
|
||||||
v2.POST("/login", loginEndpoint)
|
|
||||||
v2.POST("/submit", submitEndpoint)
|
|
||||||
v2.POST("/read", readEndpoint)
|
|
||||||
}
|
|
||||||
|
|
||||||
router.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
#### Blank Gin without middleware by default
|
|
||||||
|
|
||||||
Use
|
|
||||||
|
|
||||||
```go
|
|
||||||
r := gin.New()
|
|
||||||
```
|
|
||||||
instead of
|
|
||||||
|
|
||||||
```go
|
|
||||||
r := gin.Default()
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
#### Using middleware
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
// Creates a router without any middleware by default
|
|
||||||
r := gin.New()
|
|
||||||
|
|
||||||
// Global middleware
|
|
||||||
r.Use(gin.Logger())
|
|
||||||
r.Use(gin.Recovery())
|
|
||||||
|
|
||||||
// Per route middleware, you can add as many as you desire.
|
|
||||||
r.GET("/benchmark", MyBenchLogger(), benchEndpoint)
|
|
||||||
|
|
||||||
// Authorization group
|
|
||||||
// authorized := r.Group("/", AuthRequired())
|
|
||||||
// exactly the same as:
|
|
||||||
authorized := r.Group("/")
|
|
||||||
// per group middleware! in this case we use the custom created
|
|
||||||
// AuthRequired() middleware just in the "authorized" group.
|
|
||||||
authorized.Use(AuthRequired())
|
|
||||||
{
|
|
||||||
authorized.POST("/login", loginEndpoint)
|
|
||||||
authorized.POST("/submit", submitEndpoint)
|
|
||||||
authorized.POST("/read", readEndpoint)
|
|
||||||
|
|
||||||
// nested group
|
|
||||||
testing := authorized.Group("testing")
|
|
||||||
testing.GET("/analytics", analyticsEndpoint)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Listen and serve on 0.0.0.0:8080
|
|
||||||
r.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Model binding and validation
|
|
||||||
|
|
||||||
To bind a request body into a type, use model binding. We currently support binding of JSON, XML and standard form values (foo=bar&boo=baz).
|
|
||||||
|
|
||||||
Note that you need to set the corresponding binding tag on all fields you want to bind. For example, when binding from JSON, set `json:"fieldname"`.
|
|
||||||
|
|
||||||
When using the Bind-method, Gin tries to infer the binder depending on the Content-Type header. If you are sure what you are binding, you can use BindWith.
|
|
||||||
|
|
||||||
You can also specify that specific fields are required. If a field is decorated with `binding:"required"` and has a empty value when binding, the current request will fail with an error.
|
|
||||||
|
|
||||||
```go
|
|
||||||
// Binding from JSON
|
|
||||||
type Login struct {
|
|
||||||
User string `form:"user" json:"user" binding:"required"`
|
|
||||||
Password string `form:"password" json:"password" binding:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
|
|
||||||
// Example for binding JSON ({"user": "manu", "password": "123"})
|
|
||||||
router.POST("/loginJSON", func(c *gin.Context) {
|
|
||||||
var json Login
|
|
||||||
if c.BindJSON(&json) == nil {
|
|
||||||
if json.User == "manu" && json.Password == "123" {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
|
|
||||||
} else {
|
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// Example for binding a HTML form (user=manu&password=123)
|
|
||||||
router.POST("/loginForm", func(c *gin.Context) {
|
|
||||||
var form Login
|
|
||||||
// This will infer what binder to use depending on the content-type header.
|
|
||||||
if c.Bind(&form) == nil {
|
|
||||||
if form.User == "manu" && form.Password == "123" {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
|
|
||||||
} else {
|
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// Listen and serve on 0.0.0.0:8080
|
|
||||||
router.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
###Multipart/Urlencoded binding
|
|
||||||
```go
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"gopkg.in/gin-gonic/gin.v1"
|
|
||||||
)
|
|
||||||
|
|
||||||
type LoginForm struct {
|
|
||||||
User string `form:"user" binding:"required"`
|
|
||||||
Password string `form:"password" binding:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
router.POST("/login", func(c *gin.Context) {
|
|
||||||
// you can bind multipart form with explicit binding declaration:
|
|
||||||
// c.BindWith(&form, binding.Form)
|
|
||||||
// or you can simply use autobinding with Bind method:
|
|
||||||
var form LoginForm
|
|
||||||
// in this case proper binding will be automatically selected
|
|
||||||
if c.Bind(&form) == nil {
|
|
||||||
if form.User == "user" && form.Password == "password" {
|
|
||||||
c.JSON(200, gin.H{"status": "you are logged in"})
|
|
||||||
} else {
|
|
||||||
c.JSON(401, gin.H{"status": "unauthorized"})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
router.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Test it with:
|
|
||||||
```sh
|
|
||||||
$ curl -v --form user=user --form password=password http://localhost:8080/login
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
#### XML, JSON and YAML rendering
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
r := gin.Default()
|
|
||||||
|
|
||||||
// gin.H is a shortcut for map[string]interface{}
|
|
||||||
r.GET("/someJSON", func(c *gin.Context) {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
|
|
||||||
})
|
|
||||||
|
|
||||||
r.GET("/moreJSON", func(c *gin.Context) {
|
|
||||||
// You also can use a struct
|
|
||||||
var msg struct {
|
|
||||||
Name string `json:"user"`
|
|
||||||
Message string
|
|
||||||
Number int
|
|
||||||
}
|
|
||||||
msg.Name = "Lena"
|
|
||||||
msg.Message = "hey"
|
|
||||||
msg.Number = 123
|
|
||||||
// Note that msg.Name becomes "user" in the JSON
|
|
||||||
// Will output : {"user": "Lena", "Message": "hey", "Number": 123}
|
|
||||||
c.JSON(http.StatusOK, msg)
|
|
||||||
})
|
|
||||||
|
|
||||||
r.GET("/someXML", func(c *gin.Context) {
|
|
||||||
c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
|
|
||||||
})
|
|
||||||
|
|
||||||
r.GET("/someYAML", func(c *gin.Context) {
|
|
||||||
c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
|
|
||||||
})
|
|
||||||
|
|
||||||
// Listen and serve on 0.0.0.0:8080
|
|
||||||
r.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
####Serving static files
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
router.Static("/assets", "./assets")
|
|
||||||
router.StaticFS("/more_static", http.Dir("my_file_system"))
|
|
||||||
router.StaticFile("/favicon.ico", "./resources/favicon.ico")
|
|
||||||
|
|
||||||
// Listen and serve on 0.0.0.0:8080
|
|
||||||
router.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
####HTML rendering
|
|
||||||
|
|
||||||
Using LoadHTMLTemplates()
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
router.LoadHTMLGlob("templates/*")
|
|
||||||
//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
|
|
||||||
router.GET("/index", func(c *gin.Context) {
|
|
||||||
c.HTML(http.StatusOK, "index.tmpl", gin.H{
|
|
||||||
"title": "Main website",
|
|
||||||
})
|
|
||||||
})
|
|
||||||
router.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
templates/index.tmpl
|
|
||||||
```html
|
|
||||||
<html>
|
|
||||||
<h1>
|
|
||||||
{{ .title }}
|
|
||||||
</h1>
|
|
||||||
</html>
|
|
||||||
```
|
|
||||||
|
|
||||||
Using templates with same name in different directories
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
router.LoadHTMLGlob("templates/**/*")
|
|
||||||
router.GET("/posts/index", func(c *gin.Context) {
|
|
||||||
c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
|
|
||||||
"title": "Posts",
|
|
||||||
})
|
|
||||||
})
|
|
||||||
router.GET("/users/index", func(c *gin.Context) {
|
|
||||||
c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
|
|
||||||
"title": "Users",
|
|
||||||
})
|
|
||||||
})
|
|
||||||
router.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
templates/posts/index.tmpl
|
|
||||||
```html
|
|
||||||
{{ define "posts/index.tmpl" }}
|
|
||||||
<html><h1>
|
|
||||||
{{ .title }}
|
|
||||||
</h1>
|
|
||||||
<p>Using posts/index.tmpl</p>
|
|
||||||
</html>
|
|
||||||
{{ end }}
|
|
||||||
```
|
|
||||||
templates/users/index.tmpl
|
|
||||||
```html
|
|
||||||
{{ define "users/index.tmpl" }}
|
|
||||||
<html><h1>
|
|
||||||
{{ .title }}
|
|
||||||
</h1>
|
|
||||||
<p>Using users/index.tmpl</p>
|
|
||||||
</html>
|
|
||||||
{{ end }}
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also use your own html template render
|
|
||||||
|
|
||||||
```go
|
|
||||||
import "html/template"
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
html := template.Must(template.ParseFiles("file1", "file2"))
|
|
||||||
router.SetHTMLTemplate(html)
|
|
||||||
router.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
#### Redirects
|
|
||||||
|
|
||||||
Issuing a HTTP redirect is easy:
|
|
||||||
|
|
||||||
```go
|
|
||||||
r.GET("/test", func(c *gin.Context) {
|
|
||||||
c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
|
|
||||||
})
|
|
||||||
```
|
|
||||||
Both internal and external locations are supported.
|
|
||||||
|
|
||||||
|
|
||||||
#### Custom Middleware
|
|
||||||
|
|
||||||
```go
|
|
||||||
func Logger() gin.HandlerFunc {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
t := time.Now()
|
|
||||||
|
|
||||||
// Set example variable
|
|
||||||
c.Set("example", "12345")
|
|
||||||
|
|
||||||
// before request
|
|
||||||
|
|
||||||
c.Next()
|
|
||||||
|
|
||||||
// after request
|
|
||||||
latency := time.Since(t)
|
|
||||||
log.Print(latency)
|
|
||||||
|
|
||||||
// access the status we are sending
|
|
||||||
status := c.Writer.Status()
|
|
||||||
log.Println(status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
r := gin.New()
|
|
||||||
r.Use(Logger())
|
|
||||||
|
|
||||||
r.GET("/test", func(c *gin.Context) {
|
|
||||||
example := c.MustGet("example").(string)
|
|
||||||
|
|
||||||
// it would print: "12345"
|
|
||||||
log.Println(example)
|
|
||||||
})
|
|
||||||
|
|
||||||
// Listen and serve on 0.0.0.0:8080
|
|
||||||
r.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Using BasicAuth() middleware
|
|
||||||
```go
|
|
||||||
// simulate some private data
|
|
||||||
var secrets = gin.H{
|
|
||||||
"foo": gin.H{"email": "foo@bar.com", "phone": "123433"},
|
|
||||||
"austin": gin.H{"email": "austin@example.com", "phone": "666"},
|
|
||||||
"lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
r := gin.Default()
|
|
||||||
|
|
||||||
// Group using gin.BasicAuth() middleware
|
|
||||||
// gin.Accounts is a shortcut for map[string]string
|
|
||||||
authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
|
|
||||||
"foo": "bar",
|
|
||||||
"austin": "1234",
|
|
||||||
"lena": "hello2",
|
|
||||||
"manu": "4321",
|
|
||||||
}))
|
|
||||||
|
|
||||||
// /admin/secrets endpoint
|
|
||||||
// hit "localhost:8080/admin/secrets
|
|
||||||
authorized.GET("/secrets", func(c *gin.Context) {
|
|
||||||
// get user, it was set by the BasicAuth middleware
|
|
||||||
user := c.MustGet(gin.AuthUserKey).(string)
|
|
||||||
if secret, ok := secrets[user]; ok {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
|
|
||||||
} else {
|
|
||||||
c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// Listen and serve on 0.0.0.0:8080
|
|
||||||
r.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
#### Goroutines inside a middleware
|
|
||||||
When starting inside a middleware or handler, you **SHOULD NOT** use the original context inside it, you have to use a read-only copy.
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
r := gin.Default()
|
|
||||||
|
|
||||||
r.GET("/long_async", func(c *gin.Context) {
|
|
||||||
// create copy to be used inside the goroutine
|
|
||||||
cCp := c.Copy()
|
|
||||||
go func() {
|
|
||||||
// simulate a long task with time.Sleep(). 5 seconds
|
|
||||||
time.Sleep(5 * time.Second)
|
|
||||||
|
|
||||||
// note that you are using the copied context "cCp", IMPORTANT
|
|
||||||
log.Println("Done! in path " + cCp.Request.URL.Path)
|
|
||||||
}()
|
|
||||||
})
|
|
||||||
|
|
||||||
r.GET("/long_sync", func(c *gin.Context) {
|
|
||||||
// simulate a long task with time.Sleep(). 5 seconds
|
|
||||||
time.Sleep(5 * time.Second)
|
|
||||||
|
|
||||||
// since we are NOT using a goroutine, we do not have to copy the context
|
|
||||||
log.Println("Done! in path " + c.Request.URL.Path)
|
|
||||||
})
|
|
||||||
|
|
||||||
// Listen and serve on 0.0.0.0:8080
|
|
||||||
r.Run(":8080")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Custom HTTP configuration
|
|
||||||
|
|
||||||
Use `http.ListenAndServe()` directly, like this:
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
http.ListenAndServe(":8080", router)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
or
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
router := gin.Default()
|
|
||||||
|
|
||||||
s := &http.Server{
|
|
||||||
Addr: ":8080",
|
|
||||||
Handler: router,
|
|
||||||
ReadTimeout: 10 * time.Second,
|
|
||||||
WriteTimeout: 10 * time.Second,
|
|
||||||
MaxHeaderBytes: 1 << 20,
|
|
||||||
}
|
|
||||||
s.ListenAndServe()
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Graceful restart or stop
|
|
||||||
|
|
||||||
Do you want to graceful restart or stop your web server?
|
|
||||||
There are some ways this can be done.
|
|
||||||
|
|
||||||
We can use [fvbock/endless](https://github.com/fvbock/endless) to replace the default `ListenAndServe`. Refer issue [#296](https://github.com/gin-gonic/gin/issues/296) for more details.
|
|
||||||
|
|
||||||
```go
|
|
||||||
router := gin.Default()
|
|
||||||
router.GET("/", handler)
|
|
||||||
// [...]
|
|
||||||
endless.ListenAndServe(":4242", router)
|
|
||||||
```
|
|
||||||
|
|
||||||
An alternative to endless:
|
|
||||||
|
|
||||||
* [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully.
|
|
||||||
|
|
||||||
## Contributing
|
|
||||||
|
|
||||||
- With issues:
|
|
||||||
- Use the search tool before opening a new issue.
|
|
||||||
- Please provide source code and commit sha if you found a bug.
|
|
||||||
- Review existing issues and provide feedback or react to them.
|
|
||||||
- With pull requests:
|
|
||||||
- Open your pull request against develop
|
|
||||||
- Your pull request should have no more than two commits, if not you should squash them.
|
|
||||||
- It should pass all tests in the available continuous integrations systems such as TravisCI.
|
|
||||||
- You should add/modify tests to cover your proposed code changes.
|
|
||||||
- If your pull request contains a new feature, please document it on the README.
|
|
||||||
|
|
||||||
## Example
|
|
||||||
|
|
||||||
Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework.
|
|
||||||
|
|
||||||
* [drone](https://github.com/drone/drone): Drone is a Continuous Delivery platform built on Docker, written in Go
|
|
||||||
* [gorush](https://github.com/appleboy/gorush): A push notification server written in Go.
|
|
||||||
-92
@@ -1,92 +0,0 @@
|
|||||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/subtle"
|
|
||||||
"encoding/base64"
|
|
||||||
"strconv"
|
|
||||||
)
|
|
||||||
|
|
||||||
const AuthUserKey = "user"
|
|
||||||
|
|
||||||
type (
|
|
||||||
Accounts map[string]string
|
|
||||||
authPair struct {
|
|
||||||
Value string
|
|
||||||
User string
|
|
||||||
}
|
|
||||||
authPairs []authPair
|
|
||||||
)
|
|
||||||
|
|
||||||
func (a authPairs) searchCredential(authValue string) (string, bool) {
|
|
||||||
if len(authValue) == 0 {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
for _, pair := range a {
|
|
||||||
if pair.Value == authValue {
|
|
||||||
return pair.User, true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
|
|
||||||
// BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where
|
|
||||||
// the key is the user name and the value is the password, as well as the name of the Realm.
|
|
||||||
// If the realm is empty, "Authorization Required" will be used by default.
|
|
||||||
// (see http://tools.ietf.org/html/rfc2617#section-1.2)
|
|
||||||
func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {
|
|
||||||
if realm == "" {
|
|
||||||
realm = "Authorization Required"
|
|
||||||
}
|
|
||||||
realm = "Basic realm=" + strconv.Quote(realm)
|
|
||||||
pairs := processAccounts(accounts)
|
|
||||||
return func(c *Context) {
|
|
||||||
// Search user in the slice of allowed credentials
|
|
||||||
user, found := pairs.searchCredential(c.Request.Header.Get("Authorization"))
|
|
||||||
if !found {
|
|
||||||
// Credentials doesn't match, we return 401 and abort handlers chain.
|
|
||||||
c.Header("WWW-Authenticate", realm)
|
|
||||||
c.AbortWithStatus(401)
|
|
||||||
} else {
|
|
||||||
// The user credentials was found, set user's id to key AuthUserKey in this context, the userId can be read later using
|
|
||||||
// c.MustGet(gin.AuthUserKey)
|
|
||||||
c.Set(AuthUserKey, user)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where
|
|
||||||
// the key is the user name and the value is the password.
|
|
||||||
func BasicAuth(accounts Accounts) HandlerFunc {
|
|
||||||
return BasicAuthForRealm(accounts, "")
|
|
||||||
}
|
|
||||||
|
|
||||||
func processAccounts(accounts Accounts) authPairs {
|
|
||||||
assert1(len(accounts) > 0, "Empty list of authorized credentials")
|
|
||||||
pairs := make(authPairs, 0, len(accounts))
|
|
||||||
for user, password := range accounts {
|
|
||||||
assert1(len(user) > 0, "User can not be empty")
|
|
||||||
value := authorizationHeader(user, password)
|
|
||||||
pairs = append(pairs, authPair{
|
|
||||||
Value: value,
|
|
||||||
User: user,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return pairs
|
|
||||||
}
|
|
||||||
|
|
||||||
func authorizationHeader(user, password string) string {
|
|
||||||
base := user + ":" + password
|
|
||||||
return "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
|
|
||||||
}
|
|
||||||
|
|
||||||
func secureCompare(given, actual string) bool {
|
|
||||||
if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
|
|
||||||
return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
|
|
||||||
}
|
|
||||||
/* Securely compare actual to itself to keep constant time, but always return false */
|
|
||||||
return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false
|
|
||||||
}
|
|
||||||
-5
@@ -1,5 +0,0 @@
|
|||||||
coverage:
|
|
||||||
notify:
|
|
||||||
gitter:
|
|
||||||
default:
|
|
||||||
url: https://webhooks.gitter.im/e/d90dcdeeab2f1e357165
|
|
||||||
-601
@@ -1,601 +0,0 @@
|
|||||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
"math"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin/binding"
|
|
||||||
"github.com/gin-gonic/gin/render"
|
|
||||||
"github.com/manucorporat/sse"
|
|
||||||
"golang.org/x/net/context"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Content-Type MIME of the most common data formats
|
|
||||||
const (
|
|
||||||
MIMEJSON = binding.MIMEJSON
|
|
||||||
MIMEHTML = binding.MIMEHTML
|
|
||||||
MIMEXML = binding.MIMEXML
|
|
||||||
MIMEXML2 = binding.MIMEXML2
|
|
||||||
MIMEPlain = binding.MIMEPlain
|
|
||||||
MIMEPOSTForm = binding.MIMEPOSTForm
|
|
||||||
MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm
|
|
||||||
)
|
|
||||||
|
|
||||||
const abortIndex int8 = math.MaxInt8 / 2
|
|
||||||
|
|
||||||
// Context is the most important part of gin. It allows us to pass variables between middleware,
|
|
||||||
// manage the flow, validate the JSON of a request and render a JSON response for example.
|
|
||||||
type Context struct {
|
|
||||||
writermem responseWriter
|
|
||||||
Request *http.Request
|
|
||||||
Writer ResponseWriter
|
|
||||||
|
|
||||||
Params Params
|
|
||||||
handlers HandlersChain
|
|
||||||
index int8
|
|
||||||
|
|
||||||
engine *Engine
|
|
||||||
Keys map[string]interface{}
|
|
||||||
Errors errorMsgs
|
|
||||||
Accepted []string
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ context.Context = &Context{}
|
|
||||||
|
|
||||||
/************************************/
|
|
||||||
/********** CONTEXT CREATION ********/
|
|
||||||
/************************************/
|
|
||||||
|
|
||||||
func (c *Context) reset() {
|
|
||||||
c.Writer = &c.writermem
|
|
||||||
c.Params = c.Params[0:0]
|
|
||||||
c.handlers = nil
|
|
||||||
c.index = -1
|
|
||||||
c.Keys = nil
|
|
||||||
c.Errors = c.Errors[0:0]
|
|
||||||
c.Accepted = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Copy returns a copy of the current context that can be safely used outside the request's scope.
|
|
||||||
// This have to be used then the context has to be passed to a goroutine.
|
|
||||||
func (c *Context) Copy() *Context {
|
|
||||||
var cp = *c
|
|
||||||
cp.writermem.ResponseWriter = nil
|
|
||||||
cp.Writer = &cp.writermem
|
|
||||||
cp.index = abortIndex
|
|
||||||
cp.handlers = nil
|
|
||||||
return &cp
|
|
||||||
}
|
|
||||||
|
|
||||||
// HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()", this
|
|
||||||
// function will return "main.handleGetUsers"
|
|
||||||
func (c *Context) HandlerName() string {
|
|
||||||
return nameOfFunction(c.handlers.Last())
|
|
||||||
}
|
|
||||||
|
|
||||||
/************************************/
|
|
||||||
/*********** FLOW CONTROL ***********/
|
|
||||||
/************************************/
|
|
||||||
|
|
||||||
// Next should be used only inside middleware.
|
|
||||||
// It executes the pending handlers in the chain inside the calling handler.
|
|
||||||
// See example in github.
|
|
||||||
func (c *Context) Next() {
|
|
||||||
c.index++
|
|
||||||
s := int8(len(c.handlers))
|
|
||||||
for ; c.index < s; c.index++ {
|
|
||||||
c.handlers[c.index](c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsAborted returns true if the current context was aborted.
|
|
||||||
func (c *Context) IsAborted() bool {
|
|
||||||
return c.index >= abortIndex
|
|
||||||
}
|
|
||||||
|
|
||||||
// Abort prevents pending handlers from being called. Note that this will not stop the current handler.
|
|
||||||
// Let's say you have an authorization middleware that validates that the current request is authorized. If the
|
|
||||||
// authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers
|
|
||||||
// for this request are not called.
|
|
||||||
func (c *Context) Abort() {
|
|
||||||
c.index = abortIndex
|
|
||||||
}
|
|
||||||
|
|
||||||
// AbortWithStatus calls `Abort()` and writes the headers with the specified status code.
|
|
||||||
// For example, a failed attempt to authentificate a request could use: context.AbortWithStatus(401).
|
|
||||||
func (c *Context) AbortWithStatus(code int) {
|
|
||||||
c.Status(code)
|
|
||||||
c.Writer.WriteHeaderNow()
|
|
||||||
c.Abort()
|
|
||||||
}
|
|
||||||
|
|
||||||
// AbortWithError calls `AbortWithStatus()` and `Error()` internally. This method stops the chain, writes the status code and
|
|
||||||
// pushes the specified error to `c.Errors`.
|
|
||||||
// See Context.Error() for more details.
|
|
||||||
func (c *Context) AbortWithError(code int, err error) *Error {
|
|
||||||
c.AbortWithStatus(code)
|
|
||||||
return c.Error(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
/************************************/
|
|
||||||
/********* ERROR MANAGEMENT *********/
|
|
||||||
/************************************/
|
|
||||||
|
|
||||||
// Attaches an error to the current context. The error is pushed to a list of errors.
|
|
||||||
// It's a good idea to call Error for each error that occurred during the resolution of a request.
|
|
||||||
// A middleware can be used to collect all the errors
|
|
||||||
// and push them to a database together, print a log, or append it in the HTTP response.
|
|
||||||
func (c *Context) Error(err error) *Error {
|
|
||||||
var parsedError *Error
|
|
||||||
switch err.(type) {
|
|
||||||
case *Error:
|
|
||||||
parsedError = err.(*Error)
|
|
||||||
default:
|
|
||||||
parsedError = &Error{
|
|
||||||
Err: err,
|
|
||||||
Type: ErrorTypePrivate,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c.Errors = append(c.Errors, parsedError)
|
|
||||||
return parsedError
|
|
||||||
}
|
|
||||||
|
|
||||||
/************************************/
|
|
||||||
/******** METADATA MANAGEMENT********/
|
|
||||||
/************************************/
|
|
||||||
|
|
||||||
// Set is used to store a new key/value pair exclusivelly for this context.
|
|
||||||
// It also lazy initializes c.Keys if it was not used previously.
|
|
||||||
func (c *Context) Set(key string, value interface{}) {
|
|
||||||
if c.Keys == nil {
|
|
||||||
c.Keys = make(map[string]interface{})
|
|
||||||
}
|
|
||||||
c.Keys[key] = value
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get returns the value for the given key, ie: (value, true).
|
|
||||||
// If the value does not exists it returns (nil, false)
|
|
||||||
func (c *Context) Get(key string) (value interface{}, exists bool) {
|
|
||||||
if c.Keys != nil {
|
|
||||||
value, exists = c.Keys[key]
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// MustGet returns the value for the given key if it exists, otherwise it panics.
|
|
||||||
func (c *Context) MustGet(key string) interface{} {
|
|
||||||
if value, exists := c.Get(key); exists {
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
panic("Key \"" + key + "\" does not exist")
|
|
||||||
}
|
|
||||||
|
|
||||||
/************************************/
|
|
||||||
/************ INPUT DATA ************/
|
|
||||||
/************************************/
|
|
||||||
|
|
||||||
// Param returns the value of the URL param.
|
|
||||||
// It is a shortcut for c.Params.ByName(key)
|
|
||||||
// router.GET("/user/:id", func(c *gin.Context) {
|
|
||||||
// // a GET request to /user/john
|
|
||||||
// id := c.Param("id") // id == "john"
|
|
||||||
// })
|
|
||||||
func (c *Context) Param(key string) string {
|
|
||||||
return c.Params.ByName(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Query returns the keyed url query value if it exists,
|
|
||||||
// othewise it returns an empty string `("")`.
|
|
||||||
// It is shortcut for `c.Request.URL.Query().Get(key)`
|
|
||||||
// GET /path?id=1234&name=Manu&value=
|
|
||||||
// c.Query("id") == "1234"
|
|
||||||
// c.Query("name") == "Manu"
|
|
||||||
// c.Query("value") == ""
|
|
||||||
// c.Query("wtf") == ""
|
|
||||||
func (c *Context) Query(key string) string {
|
|
||||||
value, _ := c.GetQuery(key)
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
// DefaultQuery returns the keyed url query value if it exists,
|
|
||||||
// othewise it returns the specified defaultValue string.
|
|
||||||
// See: Query() and GetQuery() for further information.
|
|
||||||
// GET /?name=Manu&lastname=
|
|
||||||
// c.DefaultQuery("name", "unknown") == "Manu"
|
|
||||||
// c.DefaultQuery("id", "none") == "none"
|
|
||||||
// c.DefaultQuery("lastname", "none") == ""
|
|
||||||
func (c *Context) DefaultQuery(key, defaultValue string) string {
|
|
||||||
if value, ok := c.GetQuery(key); ok {
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetQuery is like Query(), it returns the keyed url query value
|
|
||||||
// if it exists `(value, true)` (even when the value is an empty string),
|
|
||||||
// othewise it returns `("", false)`.
|
|
||||||
// It is shortcut for `c.Request.URL.Query().Get(key)`
|
|
||||||
// GET /?name=Manu&lastname=
|
|
||||||
// ("Manu", true) == c.GetQuery("name")
|
|
||||||
// ("", false) == c.GetQuery("id")
|
|
||||||
// ("", true) == c.GetQuery("lastname")
|
|
||||||
func (c *Context) GetQuery(key string) (string, bool) {
|
|
||||||
if values, ok := c.GetQueryArray(key); ok {
|
|
||||||
return values[0], ok
|
|
||||||
}
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
|
|
||||||
// QueryArray returns a slice of strings for a given query key.
|
|
||||||
// The length of the slice depends on the number of params with the given key.
|
|
||||||
func (c *Context) QueryArray(key string) []string {
|
|
||||||
values, _ := c.GetQueryArray(key)
|
|
||||||
return values
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetQueryArray returns a slice of strings for a given query key, plus
|
|
||||||
// a boolean value whether at least one value exists for the given key.
|
|
||||||
func (c *Context) GetQueryArray(key string) ([]string, bool) {
|
|
||||||
req := c.Request
|
|
||||||
if values, ok := req.URL.Query()[key]; ok && len(values) > 0 {
|
|
||||||
return values, true
|
|
||||||
}
|
|
||||||
return []string{}, false
|
|
||||||
}
|
|
||||||
|
|
||||||
// PostForm returns the specified key from a POST urlencoded form or multipart form
|
|
||||||
// when it exists, otherwise it returns an empty string `("")`.
|
|
||||||
func (c *Context) PostForm(key string) string {
|
|
||||||
value, _ := c.GetPostForm(key)
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
// DefaultPostForm returns the specified key from a POST urlencoded form or multipart form
|
|
||||||
// when it exists, otherwise it returns the specified defaultValue string.
|
|
||||||
// See: PostForm() and GetPostForm() for further information.
|
|
||||||
func (c *Context) DefaultPostForm(key, defaultValue string) string {
|
|
||||||
if value, ok := c.GetPostForm(key); ok {
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded
|
|
||||||
// form or multipart form when it exists `(value, true)` (even when the value is an empty string),
|
|
||||||
// otherwise it returns ("", false).
|
|
||||||
// For example, during a PATCH request to update the user's email:
|
|
||||||
// email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"
|
|
||||||
// email= --> ("", true) := GetPostForm("email") // set email to ""
|
|
||||||
// --> ("", false) := GetPostForm("email") // do nothing with email
|
|
||||||
func (c *Context) GetPostForm(key string) (string, bool) {
|
|
||||||
if values, ok := c.GetPostFormArray(key); ok {
|
|
||||||
return values[0], ok
|
|
||||||
}
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
|
|
||||||
// PostFormArray returns a slice of strings for a given form key.
|
|
||||||
// The length of the slice depends on the number of params with the given key.
|
|
||||||
func (c *Context) PostFormArray(key string) []string {
|
|
||||||
values, _ := c.GetPostFormArray(key)
|
|
||||||
return values
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPostFormArray returns a slice of strings for a given form key, plus
|
|
||||||
// a boolean value whether at least one value exists for the given key.
|
|
||||||
func (c *Context) GetPostFormArray(key string) ([]string, bool) {
|
|
||||||
req := c.Request
|
|
||||||
req.ParseForm()
|
|
||||||
req.ParseMultipartForm(32 << 20) // 32 MB
|
|
||||||
if values := req.PostForm[key]; len(values) > 0 {
|
|
||||||
return values, true
|
|
||||||
}
|
|
||||||
if req.MultipartForm != nil && req.MultipartForm.File != nil {
|
|
||||||
if values := req.MultipartForm.Value[key]; len(values) > 0 {
|
|
||||||
return values, true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return []string{}, false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bind checks the Content-Type to select a binding engine automatically,
|
|
||||||
// Depending the "Content-Type" header different bindings are used:
|
|
||||||
// "application/json" --> JSON binding
|
|
||||||
// "application/xml" --> XML binding
|
|
||||||
// otherwise --> returns an error
|
|
||||||
// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
|
|
||||||
// It decodes the json payload into the struct specified as a pointer.
|
|
||||||
// Like ParseBody() but this method also writes a 400 error if the json is not valid.
|
|
||||||
func (c *Context) Bind(obj interface{}) error {
|
|
||||||
b := binding.Default(c.Request.Method, c.ContentType())
|
|
||||||
return c.BindWith(obj, b)
|
|
||||||
}
|
|
||||||
|
|
||||||
// BindJSON is a shortcut for c.BindWith(obj, binding.JSON)
|
|
||||||
func (c *Context) BindJSON(obj interface{}) error {
|
|
||||||
return c.BindWith(obj, binding.JSON)
|
|
||||||
}
|
|
||||||
|
|
||||||
// BindWith binds the passed struct pointer using the specified binding engine.
|
|
||||||
// See the binding package.
|
|
||||||
func (c *Context) BindWith(obj interface{}, b binding.Binding) error {
|
|
||||||
if err := b.Bind(c.Request, obj); err != nil {
|
|
||||||
c.AbortWithError(400, err).SetType(ErrorTypeBind)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClientIP implements a best effort algorithm to return the real client IP, it parses
|
|
||||||
// X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
|
|
||||||
func (c *Context) ClientIP() string {
|
|
||||||
if c.engine.ForwardedByClientIP {
|
|
||||||
clientIP := strings.TrimSpace(c.requestHeader("X-Real-Ip"))
|
|
||||||
if len(clientIP) > 0 {
|
|
||||||
return clientIP
|
|
||||||
}
|
|
||||||
clientIP = c.requestHeader("X-Forwarded-For")
|
|
||||||
if index := strings.IndexByte(clientIP, ','); index >= 0 {
|
|
||||||
clientIP = clientIP[0:index]
|
|
||||||
}
|
|
||||||
clientIP = strings.TrimSpace(clientIP)
|
|
||||||
if len(clientIP) > 0 {
|
|
||||||
return clientIP
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil {
|
|
||||||
return ip
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// ContentType returns the Content-Type header of the request.
|
|
||||||
func (c *Context) ContentType() string {
|
|
||||||
return filterFlags(c.requestHeader("Content-Type"))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Context) requestHeader(key string) string {
|
|
||||||
if values, _ := c.Request.Header[key]; len(values) > 0 {
|
|
||||||
return values[0]
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
/************************************/
|
|
||||||
/******** RESPONSE RENDERING ********/
|
|
||||||
/************************************/
|
|
||||||
|
|
||||||
func (c *Context) Status(code int) {
|
|
||||||
c.writermem.WriteHeader(code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Header is a intelligent shortcut for c.Writer.Header().Set(key, value)
|
|
||||||
// It writes a header in the response.
|
|
||||||
// If value == "", this method removes the header `c.Writer.Header().Del(key)`
|
|
||||||
func (c *Context) Header(key, value string) {
|
|
||||||
if len(value) == 0 {
|
|
||||||
c.Writer.Header().Del(key)
|
|
||||||
} else {
|
|
||||||
c.Writer.Header().Set(key, value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Context) SetCookie(
|
|
||||||
name string,
|
|
||||||
value string,
|
|
||||||
maxAge int,
|
|
||||||
path string,
|
|
||||||
domain string,
|
|
||||||
secure bool,
|
|
||||||
httpOnly bool,
|
|
||||||
) {
|
|
||||||
if path == "" {
|
|
||||||
path = "/"
|
|
||||||
}
|
|
||||||
http.SetCookie(c.Writer, &http.Cookie{
|
|
||||||
Name: name,
|
|
||||||
Value: url.QueryEscape(value),
|
|
||||||
MaxAge: maxAge,
|
|
||||||
Path: path,
|
|
||||||
Domain: domain,
|
|
||||||
Secure: secure,
|
|
||||||
HttpOnly: httpOnly,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Context) Cookie(name string) (string, error) {
|
|
||||||
cookie, err := c.Request.Cookie(name)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
val, _ := url.QueryUnescape(cookie.Value)
|
|
||||||
return val, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Context) Render(code int, r render.Render) {
|
|
||||||
c.Status(code)
|
|
||||||
if err := r.Render(c.Writer); err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// HTML renders the HTTP template specified by its file name.
|
|
||||||
// It also updates the HTTP code and sets the Content-Type as "text/html".
|
|
||||||
// See http://golang.org/doc/articles/wiki/
|
|
||||||
func (c *Context) HTML(code int, name string, obj interface{}) {
|
|
||||||
instance := c.engine.HTMLRender.Instance(name, obj)
|
|
||||||
c.Render(code, instance)
|
|
||||||
}
|
|
||||||
|
|
||||||
// IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.
|
|
||||||
// It also sets the Content-Type as "application/json".
|
|
||||||
// WARNING: we recommend to use this only for development propuses since printing pretty JSON is
|
|
||||||
// more CPU and bandwidth consuming. Use Context.JSON() instead.
|
|
||||||
func (c *Context) IndentedJSON(code int, obj interface{}) {
|
|
||||||
c.Render(code, render.IndentedJSON{Data: obj})
|
|
||||||
}
|
|
||||||
|
|
||||||
// JSON serializes the given struct as JSON into the response body.
|
|
||||||
// It also sets the Content-Type as "application/json".
|
|
||||||
func (c *Context) JSON(code int, obj interface{}) {
|
|
||||||
c.Status(code)
|
|
||||||
if err := render.WriteJSON(c.Writer, obj); err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// XML serializes the given struct as XML into the response body.
|
|
||||||
// It also sets the Content-Type as "application/xml".
|
|
||||||
func (c *Context) XML(code int, obj interface{}) {
|
|
||||||
c.Render(code, render.XML{Data: obj})
|
|
||||||
}
|
|
||||||
|
|
||||||
// YAML serializes the given struct as YAML into the response body.
|
|
||||||
func (c *Context) YAML(code int, obj interface{}) {
|
|
||||||
c.Render(code, render.YAML{Data: obj})
|
|
||||||
}
|
|
||||||
|
|
||||||
// String writes the given string into the response body.
|
|
||||||
func (c *Context) String(code int, format string, values ...interface{}) {
|
|
||||||
c.Status(code)
|
|
||||||
render.WriteString(c.Writer, format, values)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Redirect returns a HTTP redirect to the specific location.
|
|
||||||
func (c *Context) Redirect(code int, location string) {
|
|
||||||
c.Render(-1, render.Redirect{
|
|
||||||
Code: code,
|
|
||||||
Location: location,
|
|
||||||
Request: c.Request,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Data writes some data into the body stream and updates the HTTP code.
|
|
||||||
func (c *Context) Data(code int, contentType string, data []byte) {
|
|
||||||
c.Render(code, render.Data{
|
|
||||||
ContentType: contentType,
|
|
||||||
Data: data,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// File writes the specified file into the body stream in a efficient way.
|
|
||||||
func (c *Context) File(filepath string) {
|
|
||||||
http.ServeFile(c.Writer, c.Request, filepath)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SSEvent writes a Server-Sent Event into the body stream.
|
|
||||||
func (c *Context) SSEvent(name string, message interface{}) {
|
|
||||||
c.Render(-1, sse.Event{
|
|
||||||
Event: name,
|
|
||||||
Data: message,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Context) Stream(step func(w io.Writer) bool) {
|
|
||||||
w := c.Writer
|
|
||||||
clientGone := w.CloseNotify()
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-clientGone:
|
|
||||||
return
|
|
||||||
default:
|
|
||||||
keepOpen := step(w)
|
|
||||||
w.Flush()
|
|
||||||
if !keepOpen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/************************************/
|
|
||||||
/******** CONTENT NEGOTIATION *******/
|
|
||||||
/************************************/
|
|
||||||
|
|
||||||
type Negotiate struct {
|
|
||||||
Offered []string
|
|
||||||
HTMLName string
|
|
||||||
HTMLData interface{}
|
|
||||||
JSONData interface{}
|
|
||||||
XMLData interface{}
|
|
||||||
Data interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Context) Negotiate(code int, config Negotiate) {
|
|
||||||
switch c.NegotiateFormat(config.Offered...) {
|
|
||||||
case binding.MIMEJSON:
|
|
||||||
data := chooseData(config.JSONData, config.Data)
|
|
||||||
c.JSON(code, data)
|
|
||||||
|
|
||||||
case binding.MIMEHTML:
|
|
||||||
data := chooseData(config.HTMLData, config.Data)
|
|
||||||
c.HTML(code, config.HTMLName, data)
|
|
||||||
|
|
||||||
case binding.MIMEXML:
|
|
||||||
data := chooseData(config.XMLData, config.Data)
|
|
||||||
c.XML(code, data)
|
|
||||||
|
|
||||||
default:
|
|
||||||
c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Context) NegotiateFormat(offered ...string) string {
|
|
||||||
assert1(len(offered) > 0, "you must provide at least one offer")
|
|
||||||
|
|
||||||
if c.Accepted == nil {
|
|
||||||
c.Accepted = parseAccept(c.requestHeader("Accept"))
|
|
||||||
}
|
|
||||||
if len(c.Accepted) == 0 {
|
|
||||||
return offered[0]
|
|
||||||
}
|
|
||||||
for _, accepted := range c.Accepted {
|
|
||||||
for _, offert := range offered {
|
|
||||||
if accepted == offert {
|
|
||||||
return offert
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Context) SetAccepted(formats ...string) {
|
|
||||||
c.Accepted = formats
|
|
||||||
}
|
|
||||||
|
|
||||||
/************************************/
|
|
||||||
/***** GOLANG.ORG/X/NET/CONTEXT *****/
|
|
||||||
/************************************/
|
|
||||||
|
|
||||||
func (c *Context) Deadline() (deadline time.Time, ok bool) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Context) Done() <-chan struct{} {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Context) Err() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Context) Value(key interface{}) interface{} {
|
|
||||||
if key == 0 {
|
|
||||||
return c.Request
|
|
||||||
}
|
|
||||||
if keyAsString, ok := key.(string); ok {
|
|
||||||
val, _ := c.Get(keyAsString)
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
-71
@@ -1,71 +0,0 @@
|
|||||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"html/template"
|
|
||||||
"log"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
log.SetFlags(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsDebugging returns true if the framework is running in debug mode.
|
|
||||||
// Use SetMode(gin.Release) to switch to disable the debug mode.
|
|
||||||
func IsDebugging() bool {
|
|
||||||
return ginMode == debugCode
|
|
||||||
}
|
|
||||||
|
|
||||||
func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) {
|
|
||||||
if IsDebugging() {
|
|
||||||
nuHandlers := len(handlers)
|
|
||||||
handlerName := nameOfFunction(handlers.Last())
|
|
||||||
debugPrint("%-6s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func debugPrintLoadTemplate(tmpl *template.Template) {
|
|
||||||
if IsDebugging() {
|
|
||||||
var buf bytes.Buffer
|
|
||||||
for _, tmpl := range tmpl.Templates() {
|
|
||||||
buf.WriteString("\t- ")
|
|
||||||
buf.WriteString(tmpl.Name())
|
|
||||||
buf.WriteString("\n")
|
|
||||||
}
|
|
||||||
debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func debugPrint(format string, values ...interface{}) {
|
|
||||||
if IsDebugging() {
|
|
||||||
log.Printf("[GIN-debug] "+format, values...)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func debugPrintWARNINGNew() {
|
|
||||||
debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production.
|
|
||||||
- using env: export GIN_MODE=release
|
|
||||||
- using code: gin.SetMode(gin.ReleaseMode)
|
|
||||||
|
|
||||||
`)
|
|
||||||
}
|
|
||||||
|
|
||||||
func debugPrintWARNINGSetHTMLTemplate() {
|
|
||||||
debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called
|
|
||||||
at initialization. ie. before any route is registered or the router is listening in a socket:
|
|
||||||
|
|
||||||
router := gin.Default()
|
|
||||||
router.SetHTMLTemplate(template) // << good place
|
|
||||||
|
|
||||||
`)
|
|
||||||
}
|
|
||||||
|
|
||||||
func debugPrintError(err error) {
|
|
||||||
if err != nil {
|
|
||||||
debugPrint("[ERROR] %v\n", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-12
@@ -1,12 +0,0 @@
|
|||||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
import "log"
|
|
||||||
|
|
||||||
func (c *Context) GetCookie(name string) (string, error) {
|
|
||||||
log.Println("GetCookie() method is deprecated. Use Cookie() instead.")
|
|
||||||
return c.Cookie(name)
|
|
||||||
}
|
|
||||||
-159
@@ -1,159 +0,0 @@
|
|||||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"reflect"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ErrorType uint64
|
|
||||||
|
|
||||||
const (
|
|
||||||
ErrorTypeBind ErrorType = 1 << 63 // used when c.Bind() fails
|
|
||||||
ErrorTypeRender ErrorType = 1 << 62 // used when c.Render() fails
|
|
||||||
ErrorTypePrivate ErrorType = 1 << 0
|
|
||||||
ErrorTypePublic ErrorType = 1 << 1
|
|
||||||
|
|
||||||
ErrorTypeAny ErrorType = 1<<64 - 1
|
|
||||||
ErrorTypeNu = 2
|
|
||||||
)
|
|
||||||
|
|
||||||
type (
|
|
||||||
Error struct {
|
|
||||||
Err error
|
|
||||||
Type ErrorType
|
|
||||||
Meta interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
errorMsgs []*Error
|
|
||||||
)
|
|
||||||
|
|
||||||
var _ error = &Error{}
|
|
||||||
|
|
||||||
func (msg *Error) SetType(flags ErrorType) *Error {
|
|
||||||
msg.Type = flags
|
|
||||||
return msg
|
|
||||||
}
|
|
||||||
|
|
||||||
func (msg *Error) SetMeta(data interface{}) *Error {
|
|
||||||
msg.Meta = data
|
|
||||||
return msg
|
|
||||||
}
|
|
||||||
|
|
||||||
func (msg *Error) JSON() interface{} {
|
|
||||||
json := H{}
|
|
||||||
if msg.Meta != nil {
|
|
||||||
value := reflect.ValueOf(msg.Meta)
|
|
||||||
switch value.Kind() {
|
|
||||||
case reflect.Struct:
|
|
||||||
return msg.Meta
|
|
||||||
case reflect.Map:
|
|
||||||
for _, key := range value.MapKeys() {
|
|
||||||
json[key.String()] = value.MapIndex(key).Interface()
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
json["meta"] = msg.Meta
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if _, ok := json["error"]; !ok {
|
|
||||||
json["error"] = msg.Error()
|
|
||||||
}
|
|
||||||
return json
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON implements the json.Marshaller interface
|
|
||||||
func (msg *Error) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(msg.JSON())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Implements the error interface
|
|
||||||
func (msg *Error) Error() string {
|
|
||||||
return msg.Err.Error()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (msg *Error) IsType(flags ErrorType) bool {
|
|
||||||
return (msg.Type & flags) > 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns a readonly copy filterd the byte.
|
|
||||||
// ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic
|
|
||||||
func (a errorMsgs) ByType(typ ErrorType) errorMsgs {
|
|
||||||
if len(a) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if typ == ErrorTypeAny {
|
|
||||||
return a
|
|
||||||
}
|
|
||||||
var result errorMsgs
|
|
||||||
for _, msg := range a {
|
|
||||||
if msg.IsType(typ) {
|
|
||||||
result = append(result, msg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the last error in the slice. It returns nil if the array is empty.
|
|
||||||
// Shortcut for errors[len(errors)-1]
|
|
||||||
func (a errorMsgs) Last() *Error {
|
|
||||||
length := len(a)
|
|
||||||
if length > 0 {
|
|
||||||
return a[length-1]
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns an array will all the error messages.
|
|
||||||
// Example:
|
|
||||||
// c.Error(errors.New("first"))
|
|
||||||
// c.Error(errors.New("second"))
|
|
||||||
// c.Error(errors.New("third"))
|
|
||||||
// c.Errors.Errors() // == []string{"first", "second", "third"}
|
|
||||||
func (a errorMsgs) Errors() []string {
|
|
||||||
if len(a) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
errorStrings := make([]string, len(a))
|
|
||||||
for i, err := range a {
|
|
||||||
errorStrings[i] = err.Error()
|
|
||||||
}
|
|
||||||
return errorStrings
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a errorMsgs) JSON() interface{} {
|
|
||||||
switch len(a) {
|
|
||||||
case 0:
|
|
||||||
return nil
|
|
||||||
case 1:
|
|
||||||
return a.Last().JSON()
|
|
||||||
default:
|
|
||||||
json := make([]interface{}, len(a))
|
|
||||||
for i, err := range a {
|
|
||||||
json[i] = err.JSON()
|
|
||||||
}
|
|
||||||
return json
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a errorMsgs) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(a.JSON())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a errorMsgs) String() string {
|
|
||||||
if len(a) == 0 {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
var buffer bytes.Buffer
|
|
||||||
for i, msg := range a {
|
|
||||||
fmt.Fprintf(&buffer, "Error #%02d: %s\n", (i + 1), msg.Err)
|
|
||||||
if msg.Meta != nil {
|
|
||||||
fmt.Fprintf(&buffer, " Meta: %v\n", msg.Meta)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return buffer.String()
|
|
||||||
}
|
|
||||||
-42
@@ -1,42 +0,0 @@
|
|||||||
package gin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
)
|
|
||||||
|
|
||||||
type (
|
|
||||||
onlyfilesFS struct {
|
|
||||||
fs http.FileSystem
|
|
||||||
}
|
|
||||||
neuteredReaddirFile struct {
|
|
||||||
http.File
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// Dir returns a http.Filesystem that can be used by http.FileServer(). It is used interally
|
|
||||||
// in router.Static().
|
|
||||||
// if listDirectory == true, then it works the same as http.Dir() otherwise it returns
|
|
||||||
// a filesystem that prevents http.FileServer() to list the directory files.
|
|
||||||
func Dir(root string, listDirectory bool) http.FileSystem {
|
|
||||||
fs := http.Dir(root)
|
|
||||||
if listDirectory {
|
|
||||||
return fs
|
|
||||||
}
|
|
||||||
return &onlyfilesFS{fs}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Conforms to http.Filesystem
|
|
||||||
func (fs onlyfilesFS) Open(name string) (http.File, error) {
|
|
||||||
f, err := fs.fs.Open(name)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return neuteredReaddirFile{f}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Overrides the http.File default implementation
|
|
||||||
func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {
|
|
||||||
// this disables directory listing
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
-370
@@ -1,370 +0,0 @@
|
|||||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"html/template"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin/render"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Version is Framework's version
|
|
||||||
const Version = "v1.0rc2"
|
|
||||||
|
|
||||||
var default404Body = []byte("404 page not found")
|
|
||||||
var default405Body = []byte("405 method not allowed")
|
|
||||||
|
|
||||||
type HandlerFunc func(*Context)
|
|
||||||
type HandlersChain []HandlerFunc
|
|
||||||
|
|
||||||
// Last returns the last handler in the chain. ie. the last handler is the main own.
|
|
||||||
func (c HandlersChain) Last() HandlerFunc {
|
|
||||||
length := len(c)
|
|
||||||
if length > 0 {
|
|
||||||
return c[length-1]
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type (
|
|
||||||
RoutesInfo []RouteInfo
|
|
||||||
RouteInfo struct {
|
|
||||||
Method string
|
|
||||||
Path string
|
|
||||||
Handler string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Engine is the framework's instance, it contains the muxer, middleware and configuration settings.
|
|
||||||
// Create an instance of Engine, by using New() or Default()
|
|
||||||
Engine struct {
|
|
||||||
RouterGroup
|
|
||||||
HTMLRender render.HTMLRender
|
|
||||||
allNoRoute HandlersChain
|
|
||||||
allNoMethod HandlersChain
|
|
||||||
noRoute HandlersChain
|
|
||||||
noMethod HandlersChain
|
|
||||||
pool sync.Pool
|
|
||||||
trees methodTrees
|
|
||||||
|
|
||||||
// Enables automatic redirection if the current route can't be matched but a
|
|
||||||
// handler for the path with (without) the trailing slash exists.
|
|
||||||
// For example if /foo/ is requested but a route only exists for /foo, the
|
|
||||||
// client is redirected to /foo with http status code 301 for GET requests
|
|
||||||
// and 307 for all other request methods.
|
|
||||||
RedirectTrailingSlash bool
|
|
||||||
|
|
||||||
// If enabled, the router tries to fix the current request path, if no
|
|
||||||
// handle is registered for it.
|
|
||||||
// First superfluous path elements like ../ or // are removed.
|
|
||||||
// Afterwards the router does a case-insensitive lookup of the cleaned path.
|
|
||||||
// If a handle can be found for this route, the router makes a redirection
|
|
||||||
// to the corrected path with status code 301 for GET requests and 307 for
|
|
||||||
// all other request methods.
|
|
||||||
// For example /FOO and /..//Foo could be redirected to /foo.
|
|
||||||
// RedirectTrailingSlash is independent of this option.
|
|
||||||
RedirectFixedPath bool
|
|
||||||
|
|
||||||
// If enabled, the router checks if another method is allowed for the
|
|
||||||
// current route, if the current request can not be routed.
|
|
||||||
// If this is the case, the request is answered with 'Method Not Allowed'
|
|
||||||
// and HTTP status code 405.
|
|
||||||
// If no other Method is allowed, the request is delegated to the NotFound
|
|
||||||
// handler.
|
|
||||||
HandleMethodNotAllowed bool
|
|
||||||
ForwardedByClientIP bool
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
var _ IRouter = &Engine{}
|
|
||||||
|
|
||||||
// New returns a new blank Engine instance without any middleware attached.
|
|
||||||
// By default the configuration is:
|
|
||||||
// - RedirectTrailingSlash: true
|
|
||||||
// - RedirectFixedPath: false
|
|
||||||
// - HandleMethodNotAllowed: false
|
|
||||||
// - ForwardedByClientIP: true
|
|
||||||
func New() *Engine {
|
|
||||||
debugPrintWARNINGNew()
|
|
||||||
engine := &Engine{
|
|
||||||
RouterGroup: RouterGroup{
|
|
||||||
Handlers: nil,
|
|
||||||
basePath: "/",
|
|
||||||
root: true,
|
|
||||||
},
|
|
||||||
RedirectTrailingSlash: true,
|
|
||||||
RedirectFixedPath: false,
|
|
||||||
HandleMethodNotAllowed: false,
|
|
||||||
ForwardedByClientIP: true,
|
|
||||||
trees: make(methodTrees, 0, 9),
|
|
||||||
}
|
|
||||||
engine.RouterGroup.engine = engine
|
|
||||||
engine.pool.New = func() interface{} {
|
|
||||||
return engine.allocateContext()
|
|
||||||
}
|
|
||||||
return engine
|
|
||||||
}
|
|
||||||
|
|
||||||
// Default returns an Engine instance with the Logger and Recovery middleware already attached.
|
|
||||||
func Default() *Engine {
|
|
||||||
engine := New()
|
|
||||||
engine.Use(Logger(), Recovery())
|
|
||||||
return engine
|
|
||||||
}
|
|
||||||
|
|
||||||
func (engine *Engine) allocateContext() *Context {
|
|
||||||
return &Context{engine: engine}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (engine *Engine) LoadHTMLGlob(pattern string) {
|
|
||||||
if IsDebugging() {
|
|
||||||
debugPrintLoadTemplate(template.Must(template.ParseGlob(pattern)))
|
|
||||||
engine.HTMLRender = render.HTMLDebug{Glob: pattern}
|
|
||||||
} else {
|
|
||||||
templ := template.Must(template.ParseGlob(pattern))
|
|
||||||
engine.SetHTMLTemplate(templ)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (engine *Engine) LoadHTMLFiles(files ...string) {
|
|
||||||
if IsDebugging() {
|
|
||||||
engine.HTMLRender = render.HTMLDebug{Files: files}
|
|
||||||
} else {
|
|
||||||
templ := template.Must(template.ParseFiles(files...))
|
|
||||||
engine.SetHTMLTemplate(templ)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
|
|
||||||
if len(engine.trees) > 0 {
|
|
||||||
debugPrintWARNINGSetHTMLTemplate()
|
|
||||||
}
|
|
||||||
engine.HTMLRender = render.HTMLProduction{Template: templ}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NoRoute adds handlers for NoRoute. It return a 404 code by default.
|
|
||||||
func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
|
|
||||||
engine.noRoute = handlers
|
|
||||||
engine.rebuild404Handlers()
|
|
||||||
}
|
|
||||||
|
|
||||||
// NoMethod sets the handlers called when... TODO
|
|
||||||
func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
|
|
||||||
engine.noMethod = handlers
|
|
||||||
engine.rebuild405Handlers()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use attachs a global middleware to the router. ie. the middleware attached though Use() will be
|
|
||||||
// included in the handlers chain for every single request. Even 404, 405, static files...
|
|
||||||
// For example, this is the right place for a logger or error management middleware.
|
|
||||||
func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {
|
|
||||||
engine.RouterGroup.Use(middleware...)
|
|
||||||
engine.rebuild404Handlers()
|
|
||||||
engine.rebuild405Handlers()
|
|
||||||
return engine
|
|
||||||
}
|
|
||||||
|
|
||||||
func (engine *Engine) rebuild404Handlers() {
|
|
||||||
engine.allNoRoute = engine.combineHandlers(engine.noRoute)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (engine *Engine) rebuild405Handlers() {
|
|
||||||
engine.allNoMethod = engine.combineHandlers(engine.noMethod)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {
|
|
||||||
assert1(path[0] == '/', "path must begin with '/'")
|
|
||||||
assert1(len(method) > 0, "HTTP method can not be empty")
|
|
||||||
assert1(len(handlers) > 0, "there must be at least one handler")
|
|
||||||
|
|
||||||
debugPrintRoute(method, path, handlers)
|
|
||||||
root := engine.trees.get(method)
|
|
||||||
if root == nil {
|
|
||||||
root = new(node)
|
|
||||||
engine.trees = append(engine.trees, methodTree{method: method, root: root})
|
|
||||||
}
|
|
||||||
root.addRoute(path, handlers)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Routes returns a slice of registered routes, including some useful information, such as:
|
|
||||||
// the http method, path and the handler name.
|
|
||||||
func (engine *Engine) Routes() (routes RoutesInfo) {
|
|
||||||
for _, tree := range engine.trees {
|
|
||||||
routes = iterate("", tree.method, routes, tree.root)
|
|
||||||
}
|
|
||||||
return routes
|
|
||||||
}
|
|
||||||
|
|
||||||
func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo {
|
|
||||||
path += root.path
|
|
||||||
if len(root.handlers) > 0 {
|
|
||||||
routes = append(routes, RouteInfo{
|
|
||||||
Method: method,
|
|
||||||
Path: path,
|
|
||||||
Handler: nameOfFunction(root.handlers.Last()),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
for _, child := range root.children {
|
|
||||||
routes = iterate(path, method, routes, child)
|
|
||||||
}
|
|
||||||
return routes
|
|
||||||
}
|
|
||||||
|
|
||||||
// Run attaches the router to a http.Server and starts listening and serving HTTP requests.
|
|
||||||
// It is a shortcut for http.ListenAndServe(addr, router)
|
|
||||||
// Note: this method will block the calling goroutine indefinitely unless an error happens.
|
|
||||||
func (engine *Engine) Run(addr ...string) (err error) {
|
|
||||||
defer func() { debugPrintError(err) }()
|
|
||||||
|
|
||||||
address := resolveAddress(addr)
|
|
||||||
debugPrint("Listening and serving HTTP on %s\n", address)
|
|
||||||
err = http.ListenAndServe(address, engine)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.
|
|
||||||
// It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)
|
|
||||||
// Note: this method will block the calling goroutine indefinitely unless an error happens.
|
|
||||||
func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error) {
|
|
||||||
debugPrint("Listening and serving HTTPS on %s\n", addr)
|
|
||||||
defer func() { debugPrintError(err) }()
|
|
||||||
|
|
||||||
err = http.ListenAndServeTLS(addr, certFile, keyFile, engine)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests
|
|
||||||
// through the specified unix socket (ie. a file).
|
|
||||||
// Note: this method will block the calling goroutine indefinitely unless an error happens.
|
|
||||||
func (engine *Engine) RunUnix(file string) (err error) {
|
|
||||||
debugPrint("Listening and serving HTTP on unix:/%s", file)
|
|
||||||
defer func() { debugPrintError(err) }()
|
|
||||||
|
|
||||||
os.Remove(file)
|
|
||||||
listener, err := net.Listen("unix", file)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer listener.Close()
|
|
||||||
err = http.Serve(listener, engine)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Conforms to the http.Handler interface.
|
|
||||||
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
||||||
c := engine.pool.Get().(*Context)
|
|
||||||
c.writermem.reset(w)
|
|
||||||
c.Request = req
|
|
||||||
c.reset()
|
|
||||||
|
|
||||||
engine.handleHTTPRequest(c)
|
|
||||||
|
|
||||||
engine.pool.Put(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (engine *Engine) handleHTTPRequest(context *Context) {
|
|
||||||
httpMethod := context.Request.Method
|
|
||||||
path := context.Request.URL.Path
|
|
||||||
|
|
||||||
// Find root of the tree for the given HTTP method
|
|
||||||
t := engine.trees
|
|
||||||
for i, tl := 0, len(t); i < tl; i++ {
|
|
||||||
if t[i].method == httpMethod {
|
|
||||||
root := t[i].root
|
|
||||||
// Find route in tree
|
|
||||||
handlers, params, tsr := root.getValue(path, context.Params)
|
|
||||||
if handlers != nil {
|
|
||||||
context.handlers = handlers
|
|
||||||
context.Params = params
|
|
||||||
context.Next()
|
|
||||||
context.writermem.WriteHeaderNow()
|
|
||||||
return
|
|
||||||
|
|
||||||
} else if httpMethod != "CONNECT" && path != "/" {
|
|
||||||
if tsr && engine.RedirectTrailingSlash {
|
|
||||||
redirectTrailingSlash(context)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if engine.RedirectFixedPath && redirectFixedPath(context, root, engine.RedirectFixedPath) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: unit test
|
|
||||||
if engine.HandleMethodNotAllowed {
|
|
||||||
for _, tree := range engine.trees {
|
|
||||||
if tree.method != httpMethod {
|
|
||||||
if handlers, _, _ := tree.root.getValue(path, nil); handlers != nil {
|
|
||||||
context.handlers = engine.allNoMethod
|
|
||||||
serveError(context, 405, default405Body)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
context.handlers = engine.allNoRoute
|
|
||||||
serveError(context, 404, default404Body)
|
|
||||||
}
|
|
||||||
|
|
||||||
var mimePlain = []string{MIMEPlain}
|
|
||||||
|
|
||||||
func serveError(c *Context, code int, defaultMessage []byte) {
|
|
||||||
c.writermem.status = code
|
|
||||||
c.Next()
|
|
||||||
if !c.writermem.Written() {
|
|
||||||
if c.writermem.Status() == code {
|
|
||||||
c.writermem.Header()["Content-Type"] = mimePlain
|
|
||||||
c.Writer.Write(defaultMessage)
|
|
||||||
} else {
|
|
||||||
c.writermem.WriteHeaderNow()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func redirectTrailingSlash(c *Context) {
|
|
||||||
req := c.Request
|
|
||||||
path := req.URL.Path
|
|
||||||
code := 301 // Permanent redirect, request with GET method
|
|
||||||
if req.Method != "GET" {
|
|
||||||
code = 307
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(path) > 1 && path[len(path)-1] == '/' {
|
|
||||||
req.URL.Path = path[:len(path)-1]
|
|
||||||
} else {
|
|
||||||
req.URL.Path = path + "/"
|
|
||||||
}
|
|
||||||
debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
|
|
||||||
http.Redirect(c.Writer, req, req.URL.String(), code)
|
|
||||||
c.writermem.WriteHeaderNow()
|
|
||||||
}
|
|
||||||
|
|
||||||
func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool {
|
|
||||||
req := c.Request
|
|
||||||
path := req.URL.Path
|
|
||||||
|
|
||||||
fixedPath, found := root.findCaseInsensitivePath(
|
|
||||||
cleanPath(path),
|
|
||||||
trailingSlash,
|
|
||||||
)
|
|
||||||
if found {
|
|
||||||
code := 301 // Permanent redirect, request with GET method
|
|
||||||
if req.Method != "GET" {
|
|
||||||
code = 307
|
|
||||||
}
|
|
||||||
req.URL.Path = string(fixedPath)
|
|
||||||
debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
|
|
||||||
http.Redirect(c.Writer, req, req.URL.String(), code)
|
|
||||||
c.writermem.WriteHeaderNow()
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
-135
@@ -1,135 +0,0 @@
|
|||||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/mattn/go-isatty"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
|
|
||||||
white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
|
|
||||||
yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
|
|
||||||
red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
|
|
||||||
blue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109})
|
|
||||||
magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109})
|
|
||||||
cyan = string([]byte{27, 91, 57, 55, 59, 52, 54, 109})
|
|
||||||
reset = string([]byte{27, 91, 48, 109})
|
|
||||||
)
|
|
||||||
|
|
||||||
func ErrorLogger() HandlerFunc {
|
|
||||||
return ErrorLoggerT(ErrorTypeAny)
|
|
||||||
}
|
|
||||||
|
|
||||||
func ErrorLoggerT(typ ErrorType) HandlerFunc {
|
|
||||||
return func(c *Context) {
|
|
||||||
c.Next()
|
|
||||||
errors := c.Errors.ByType(typ)
|
|
||||||
if len(errors) > 0 {
|
|
||||||
c.JSON(-1, errors)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Logger instances a Logger middleware that will write the logs to gin.DefaultWriter
|
|
||||||
// By default gin.DefaultWriter = os.Stdout
|
|
||||||
func Logger() HandlerFunc {
|
|
||||||
return LoggerWithWriter(DefaultWriter)
|
|
||||||
}
|
|
||||||
|
|
||||||
// LoggerWithWriter instance a Logger middleware with the specified writter buffer.
|
|
||||||
// Example: os.Stdout, a file opened in write mode, a socket...
|
|
||||||
func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc {
|
|
||||||
isTerm := true
|
|
||||||
|
|
||||||
if w, ok := out.(*os.File); !ok || !isatty.IsTerminal(w.Fd()) {
|
|
||||||
isTerm = false
|
|
||||||
}
|
|
||||||
|
|
||||||
var skip map[string]struct{}
|
|
||||||
|
|
||||||
if length := len(notlogged); length > 0 {
|
|
||||||
skip = make(map[string]struct{}, length)
|
|
||||||
|
|
||||||
for _, path := range notlogged {
|
|
||||||
skip[path] = struct{}{}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return func(c *Context) {
|
|
||||||
// Start timer
|
|
||||||
start := time.Now()
|
|
||||||
path := c.Request.URL.Path
|
|
||||||
|
|
||||||
// Process request
|
|
||||||
c.Next()
|
|
||||||
|
|
||||||
// Log only when path is not being skipped
|
|
||||||
if _, ok := skip[path]; !ok {
|
|
||||||
// Stop timer
|
|
||||||
end := time.Now()
|
|
||||||
latency := end.Sub(start)
|
|
||||||
|
|
||||||
clientIP := c.ClientIP()
|
|
||||||
method := c.Request.Method
|
|
||||||
statusCode := c.Writer.Status()
|
|
||||||
var statusColor, methodColor string
|
|
||||||
if isTerm {
|
|
||||||
statusColor = colorForStatus(statusCode)
|
|
||||||
methodColor = colorForMethod(method)
|
|
||||||
}
|
|
||||||
comment := c.Errors.ByType(ErrorTypePrivate).String()
|
|
||||||
|
|
||||||
fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %s |%s %s %-7s %s\n%s",
|
|
||||||
end.Format("2006/01/02 - 15:04:05"),
|
|
||||||
statusColor, statusCode, reset,
|
|
||||||
latency,
|
|
||||||
clientIP,
|
|
||||||
methodColor, reset, method,
|
|
||||||
path,
|
|
||||||
comment,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func colorForStatus(code int) string {
|
|
||||||
switch {
|
|
||||||
case code >= 200 && code < 300:
|
|
||||||
return green
|
|
||||||
case code >= 300 && code < 400:
|
|
||||||
return white
|
|
||||||
case code >= 400 && code < 500:
|
|
||||||
return yellow
|
|
||||||
default:
|
|
||||||
return red
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func colorForMethod(method string) string {
|
|
||||||
switch method {
|
|
||||||
case "GET":
|
|
||||||
return blue
|
|
||||||
case "POST":
|
|
||||||
return cyan
|
|
||||||
case "PUT":
|
|
||||||
return yellow
|
|
||||||
case "DELETE":
|
|
||||||
return red
|
|
||||||
case "PATCH":
|
|
||||||
return green
|
|
||||||
case "HEAD":
|
|
||||||
return magenta
|
|
||||||
case "OPTIONS":
|
|
||||||
return white
|
|
||||||
default:
|
|
||||||
return reset
|
|
||||||
}
|
|
||||||
}
|
|
||||||
BIN
Binary file not shown.
|
Before Width: | Height: | Size: 12 KiB |
-69
@@ -1,69 +0,0 @@
|
|||||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin/binding"
|
|
||||||
)
|
|
||||||
|
|
||||||
const ENV_GIN_MODE = "GIN_MODE"
|
|
||||||
|
|
||||||
const (
|
|
||||||
DebugMode string = "debug"
|
|
||||||
ReleaseMode string = "release"
|
|
||||||
TestMode string = "test"
|
|
||||||
)
|
|
||||||
const (
|
|
||||||
debugCode = iota
|
|
||||||
releaseCode
|
|
||||||
testCode
|
|
||||||
)
|
|
||||||
|
|
||||||
// DefaultWriter is the default io.Writer used the Gin for debug output and
|
|
||||||
// middleware output like Logger() or Recovery().
|
|
||||||
// Note that both Logger and Recovery provides custom ways to configure their
|
|
||||||
// output io.Writer.
|
|
||||||
// To support coloring in Windows use:
|
|
||||||
// import "github.com/mattn/go-colorable"
|
|
||||||
// gin.DefaultWriter = colorable.NewColorableStdout()
|
|
||||||
var DefaultWriter io.Writer = os.Stdout
|
|
||||||
var DefaultErrorWriter io.Writer = os.Stderr
|
|
||||||
|
|
||||||
var ginMode = debugCode
|
|
||||||
var modeName = DebugMode
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
mode := os.Getenv(ENV_GIN_MODE)
|
|
||||||
if len(mode) == 0 {
|
|
||||||
SetMode(DebugMode)
|
|
||||||
} else {
|
|
||||||
SetMode(mode)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetMode(value string) {
|
|
||||||
switch value {
|
|
||||||
case DebugMode:
|
|
||||||
ginMode = debugCode
|
|
||||||
case ReleaseMode:
|
|
||||||
ginMode = releaseCode
|
|
||||||
case TestMode:
|
|
||||||
ginMode = testCode
|
|
||||||
default:
|
|
||||||
panic("gin mode unknown: " + value)
|
|
||||||
}
|
|
||||||
modeName = value
|
|
||||||
}
|
|
||||||
|
|
||||||
func DisableBindValidation() {
|
|
||||||
binding.Validator = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func Mode() string {
|
|
||||||
return modeName
|
|
||||||
}
|
|
||||||
-123
@@ -1,123 +0,0 @@
|
|||||||
// Copyright 2013 Julien Schmidt. All rights reserved.
|
|
||||||
// Based on the path package, Copyright 2009 The Go Authors.
|
|
||||||
// Use of this source code is governed by a BSD-style license that can be found
|
|
||||||
// in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
// CleanPath is the URL version of path.Clean, it returns a canonical URL path
|
|
||||||
// for p, eliminating . and .. elements.
|
|
||||||
//
|
|
||||||
// The following rules are applied iteratively until no further processing can
|
|
||||||
// be done:
|
|
||||||
// 1. Replace multiple slashes with a single slash.
|
|
||||||
// 2. Eliminate each . path name element (the current directory).
|
|
||||||
// 3. Eliminate each inner .. path name element (the parent directory)
|
|
||||||
// along with the non-.. element that precedes it.
|
|
||||||
// 4. Eliminate .. elements that begin a rooted path:
|
|
||||||
// that is, replace "/.." by "/" at the beginning of a path.
|
|
||||||
//
|
|
||||||
// If the result of this process is an empty string, "/" is returned
|
|
||||||
func cleanPath(p string) string {
|
|
||||||
// Turn empty string into "/"
|
|
||||||
if p == "" {
|
|
||||||
return "/"
|
|
||||||
}
|
|
||||||
|
|
||||||
n := len(p)
|
|
||||||
var buf []byte
|
|
||||||
|
|
||||||
// Invariants:
|
|
||||||
// reading from path; r is index of next byte to process.
|
|
||||||
// writing to buf; w is index of next byte to write.
|
|
||||||
|
|
||||||
// path must start with '/'
|
|
||||||
r := 1
|
|
||||||
w := 1
|
|
||||||
|
|
||||||
if p[0] != '/' {
|
|
||||||
r = 0
|
|
||||||
buf = make([]byte, n+1)
|
|
||||||
buf[0] = '/'
|
|
||||||
}
|
|
||||||
|
|
||||||
trailing := n > 2 && p[n-1] == '/'
|
|
||||||
|
|
||||||
// A bit more clunky without a 'lazybuf' like the path package, but the loop
|
|
||||||
// gets completely inlined (bufApp). So in contrast to the path package this
|
|
||||||
// loop has no expensive function calls (except 1x make)
|
|
||||||
|
|
||||||
for r < n {
|
|
||||||
switch {
|
|
||||||
case p[r] == '/':
|
|
||||||
// empty path element, trailing slash is added after the end
|
|
||||||
r++
|
|
||||||
|
|
||||||
case p[r] == '.' && r+1 == n:
|
|
||||||
trailing = true
|
|
||||||
r++
|
|
||||||
|
|
||||||
case p[r] == '.' && p[r+1] == '/':
|
|
||||||
// . element
|
|
||||||
r++
|
|
||||||
|
|
||||||
case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):
|
|
||||||
// .. element: remove to last /
|
|
||||||
r += 2
|
|
||||||
|
|
||||||
if w > 1 {
|
|
||||||
// can backtrack
|
|
||||||
w--
|
|
||||||
|
|
||||||
if buf == nil {
|
|
||||||
for w > 1 && p[w] != '/' {
|
|
||||||
w--
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for w > 1 && buf[w] != '/' {
|
|
||||||
w--
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
// real path element.
|
|
||||||
// add slash if needed
|
|
||||||
if w > 1 {
|
|
||||||
bufApp(&buf, p, w, '/')
|
|
||||||
w++
|
|
||||||
}
|
|
||||||
|
|
||||||
// copy element
|
|
||||||
for r < n && p[r] != '/' {
|
|
||||||
bufApp(&buf, p, w, p[r])
|
|
||||||
w++
|
|
||||||
r++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// re-append trailing slash
|
|
||||||
if trailing && w > 1 {
|
|
||||||
bufApp(&buf, p, w, '/')
|
|
||||||
w++
|
|
||||||
}
|
|
||||||
|
|
||||||
if buf == nil {
|
|
||||||
return p[:w]
|
|
||||||
}
|
|
||||||
return string(buf[:w])
|
|
||||||
}
|
|
||||||
|
|
||||||
// internal helper to lazily create a buffer if necessary
|
|
||||||
func bufApp(buf *[]byte, s string, w int, c byte) {
|
|
||||||
if *buf == nil {
|
|
||||||
if s[w] == c {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
*buf = make([]byte, len(s))
|
|
||||||
copy(*buf, s[:w])
|
|
||||||
}
|
|
||||||
(*buf)[w] = c
|
|
||||||
}
|
|
||||||
-108
@@ -1,108 +0,0 @@
|
|||||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"io/ioutil"
|
|
||||||
"log"
|
|
||||||
"net/http/httputil"
|
|
||||||
"runtime"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
dunno = []byte("???")
|
|
||||||
centerDot = []byte("·")
|
|
||||||
dot = []byte(".")
|
|
||||||
slash = []byte("/")
|
|
||||||
)
|
|
||||||
|
|
||||||
// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
|
|
||||||
func Recovery() HandlerFunc {
|
|
||||||
return RecoveryWithWriter(DefaultErrorWriter)
|
|
||||||
}
|
|
||||||
|
|
||||||
func RecoveryWithWriter(out io.Writer) HandlerFunc {
|
|
||||||
var logger *log.Logger
|
|
||||||
if out != nil {
|
|
||||||
logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags)
|
|
||||||
}
|
|
||||||
return func(c *Context) {
|
|
||||||
defer func() {
|
|
||||||
if err := recover(); err != nil {
|
|
||||||
if logger != nil {
|
|
||||||
stack := stack(3)
|
|
||||||
httprequest, _ := httputil.DumpRequest(c.Request, false)
|
|
||||||
logger.Printf("[Recovery] panic recovered:\n%s\n%s\n%s%s", string(httprequest), err, stack, reset)
|
|
||||||
}
|
|
||||||
c.AbortWithStatus(500)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
c.Next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// stack returns a nicely formated stack frame, skipping skip frames
|
|
||||||
func stack(skip int) []byte {
|
|
||||||
buf := new(bytes.Buffer) // the returned data
|
|
||||||
// As we loop, we open files and read them. These variables record the currently
|
|
||||||
// loaded file.
|
|
||||||
var lines [][]byte
|
|
||||||
var lastFile string
|
|
||||||
for i := skip; ; i++ { // Skip the expected number of frames
|
|
||||||
pc, file, line, ok := runtime.Caller(i)
|
|
||||||
if !ok {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
// Print this much at least. If we can't find the source, it won't show.
|
|
||||||
fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
|
|
||||||
if file != lastFile {
|
|
||||||
data, err := ioutil.ReadFile(file)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
lines = bytes.Split(data, []byte{'\n'})
|
|
||||||
lastFile = file
|
|
||||||
}
|
|
||||||
fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))
|
|
||||||
}
|
|
||||||
return buf.Bytes()
|
|
||||||
}
|
|
||||||
|
|
||||||
// source returns a space-trimmed slice of the n'th line.
|
|
||||||
func source(lines [][]byte, n int) []byte {
|
|
||||||
n-- // in stack trace, lines are 1-indexed but our array is 0-indexed
|
|
||||||
if n < 0 || n >= len(lines) {
|
|
||||||
return dunno
|
|
||||||
}
|
|
||||||
return bytes.TrimSpace(lines[n])
|
|
||||||
}
|
|
||||||
|
|
||||||
// function returns, if possible, the name of the function containing the PC.
|
|
||||||
func function(pc uintptr) []byte {
|
|
||||||
fn := runtime.FuncForPC(pc)
|
|
||||||
if fn == nil {
|
|
||||||
return dunno
|
|
||||||
}
|
|
||||||
name := []byte(fn.Name())
|
|
||||||
// The name includes the path name to the package, which is unnecessary
|
|
||||||
// since the file name is already included. Plus, it has center dots.
|
|
||||||
// That is, we see
|
|
||||||
// runtime/debug.*T·ptrmethod
|
|
||||||
// and want
|
|
||||||
// *T.ptrmethod
|
|
||||||
// Also the package path might contains dot (e.g. code.google.com/...),
|
|
||||||
// so first eliminate the path prefix
|
|
||||||
if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 {
|
|
||||||
name = name[lastslash+1:]
|
|
||||||
}
|
|
||||||
if period := bytes.Index(name, dot); period >= 0 {
|
|
||||||
name = name[period+1:]
|
|
||||||
}
|
|
||||||
name = bytes.Replace(name, centerDot, dot, -1)
|
|
||||||
return name
|
|
||||||
}
|
|
||||||
-116
@@ -1,116 +0,0 @@
|
|||||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
noWritten = -1
|
|
||||||
defaultStatus = 200
|
|
||||||
)
|
|
||||||
|
|
||||||
type (
|
|
||||||
ResponseWriter interface {
|
|
||||||
http.ResponseWriter
|
|
||||||
http.Hijacker
|
|
||||||
http.Flusher
|
|
||||||
http.CloseNotifier
|
|
||||||
|
|
||||||
// Returns the HTTP response status code of the current request.
|
|
||||||
Status() int
|
|
||||||
|
|
||||||
// Returns the number of bytes already written into the response http body.
|
|
||||||
// See Written()
|
|
||||||
Size() int
|
|
||||||
|
|
||||||
// Writes the string into the response body.
|
|
||||||
WriteString(string) (int, error)
|
|
||||||
|
|
||||||
// Returns true if the response body was already written.
|
|
||||||
Written() bool
|
|
||||||
|
|
||||||
// Forces to write the http header (status code + headers).
|
|
||||||
WriteHeaderNow()
|
|
||||||
}
|
|
||||||
|
|
||||||
responseWriter struct {
|
|
||||||
http.ResponseWriter
|
|
||||||
size int
|
|
||||||
status int
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
var _ ResponseWriter = &responseWriter{}
|
|
||||||
|
|
||||||
func (w *responseWriter) reset(writer http.ResponseWriter) {
|
|
||||||
w.ResponseWriter = writer
|
|
||||||
w.size = noWritten
|
|
||||||
w.status = defaultStatus
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *responseWriter) WriteHeader(code int) {
|
|
||||||
if code > 0 && w.status != code {
|
|
||||||
if w.Written() {
|
|
||||||
debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code)
|
|
||||||
}
|
|
||||||
w.status = code
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *responseWriter) WriteHeaderNow() {
|
|
||||||
if !w.Written() {
|
|
||||||
w.size = 0
|
|
||||||
w.ResponseWriter.WriteHeader(w.status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *responseWriter) Write(data []byte) (n int, err error) {
|
|
||||||
w.WriteHeaderNow()
|
|
||||||
n, err = w.ResponseWriter.Write(data)
|
|
||||||
w.size += n
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *responseWriter) WriteString(s string) (n int, err error) {
|
|
||||||
w.WriteHeaderNow()
|
|
||||||
n, err = io.WriteString(w.ResponseWriter, s)
|
|
||||||
w.size += n
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *responseWriter) Status() int {
|
|
||||||
return w.status
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *responseWriter) Size() int {
|
|
||||||
return w.size
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *responseWriter) Written() bool {
|
|
||||||
return w.size != noWritten
|
|
||||||
}
|
|
||||||
|
|
||||||
// Implements the http.Hijacker interface
|
|
||||||
func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
|
||||||
if w.size < 0 {
|
|
||||||
w.size = 0
|
|
||||||
}
|
|
||||||
return w.ResponseWriter.(http.Hijacker).Hijack()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Implements the http.CloseNotify interface
|
|
||||||
func (w *responseWriter) CloseNotify() <-chan bool {
|
|
||||||
return w.ResponseWriter.(http.CloseNotifier).CloseNotify()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Implements the http.Flush interface
|
|
||||||
func (w *responseWriter) Flush() {
|
|
||||||
w.ResponseWriter.(http.Flusher).Flush()
|
|
||||||
}
|
|
||||||
-215
@@ -1,215 +0,0 @@
|
|||||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"path"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
type (
|
|
||||||
IRouter interface {
|
|
||||||
IRoutes
|
|
||||||
Group(string, ...HandlerFunc) *RouterGroup
|
|
||||||
}
|
|
||||||
|
|
||||||
IRoutes interface {
|
|
||||||
Use(...HandlerFunc) IRoutes
|
|
||||||
|
|
||||||
Handle(string, string, ...HandlerFunc) IRoutes
|
|
||||||
Any(string, ...HandlerFunc) IRoutes
|
|
||||||
GET(string, ...HandlerFunc) IRoutes
|
|
||||||
POST(string, ...HandlerFunc) IRoutes
|
|
||||||
DELETE(string, ...HandlerFunc) IRoutes
|
|
||||||
PATCH(string, ...HandlerFunc) IRoutes
|
|
||||||
PUT(string, ...HandlerFunc) IRoutes
|
|
||||||
OPTIONS(string, ...HandlerFunc) IRoutes
|
|
||||||
HEAD(string, ...HandlerFunc) IRoutes
|
|
||||||
|
|
||||||
StaticFile(string, string) IRoutes
|
|
||||||
Static(string, string) IRoutes
|
|
||||||
StaticFS(string, http.FileSystem) IRoutes
|
|
||||||
}
|
|
||||||
|
|
||||||
// RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix
|
|
||||||
// and an array of handlers (middleware)
|
|
||||||
RouterGroup struct {
|
|
||||||
Handlers HandlersChain
|
|
||||||
basePath string
|
|
||||||
engine *Engine
|
|
||||||
root bool
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
var _ IRouter = &RouterGroup{}
|
|
||||||
|
|
||||||
// Use adds middleware to the group, see example code in github.
|
|
||||||
func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes {
|
|
||||||
group.Handlers = append(group.Handlers, middleware...)
|
|
||||||
return group.returnObj()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix.
|
|
||||||
// For example, all the routes that use a common middlware for authorization could be grouped.
|
|
||||||
func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {
|
|
||||||
return &RouterGroup{
|
|
||||||
Handlers: group.combineHandlers(handlers),
|
|
||||||
basePath: group.calculateAbsolutePath(relativePath),
|
|
||||||
engine: group.engine,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (group *RouterGroup) BasePath() string {
|
|
||||||
return group.basePath
|
|
||||||
}
|
|
||||||
|
|
||||||
func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {
|
|
||||||
absolutePath := group.calculateAbsolutePath(relativePath)
|
|
||||||
handlers = group.combineHandlers(handlers)
|
|
||||||
group.engine.addRoute(httpMethod, absolutePath, handlers)
|
|
||||||
return group.returnObj()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle registers a new request handle and middleware with the given path and method.
|
|
||||||
// The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes.
|
|
||||||
// See the example code in github.
|
|
||||||
//
|
|
||||||
// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
|
|
||||||
// functions can be used.
|
|
||||||
//
|
|
||||||
// This function is intended for bulk loading and to allow the usage of less
|
|
||||||
// frequently used, non-standardized or custom methods (e.g. for internal
|
|
||||||
// communication with a proxy).
|
|
||||||
func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes {
|
|
||||||
if matches, err := regexp.MatchString("^[A-Z]+$", httpMethod); !matches || err != nil {
|
|
||||||
panic("http method " + httpMethod + " is not valid")
|
|
||||||
}
|
|
||||||
return group.handle(httpMethod, relativePath, handlers)
|
|
||||||
}
|
|
||||||
|
|
||||||
// POST is a shortcut for router.Handle("POST", path, handle)
|
|
||||||
func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes {
|
|
||||||
return group.handle("POST", relativePath, handlers)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GET is a shortcut for router.Handle("GET", path, handle)
|
|
||||||
func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {
|
|
||||||
return group.handle("GET", relativePath, handlers)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DELETE is a shortcut for router.Handle("DELETE", path, handle)
|
|
||||||
func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes {
|
|
||||||
return group.handle("DELETE", relativePath, handlers)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PATCH is a shortcut for router.Handle("PATCH", path, handle)
|
|
||||||
func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes {
|
|
||||||
return group.handle("PATCH", relativePath, handlers)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PUT is a shortcut for router.Handle("PUT", path, handle)
|
|
||||||
func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes {
|
|
||||||
return group.handle("PUT", relativePath, handlers)
|
|
||||||
}
|
|
||||||
|
|
||||||
// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
|
|
||||||
func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes {
|
|
||||||
return group.handle("OPTIONS", relativePath, handlers)
|
|
||||||
}
|
|
||||||
|
|
||||||
// HEAD is a shortcut for router.Handle("HEAD", path, handle)
|
|
||||||
func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes {
|
|
||||||
return group.handle("HEAD", relativePath, handlers)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Any registers a route that matches all the HTTP methods.
|
|
||||||
// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE
|
|
||||||
func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {
|
|
||||||
group.handle("GET", relativePath, handlers)
|
|
||||||
group.handle("POST", relativePath, handlers)
|
|
||||||
group.handle("PUT", relativePath, handlers)
|
|
||||||
group.handle("PATCH", relativePath, handlers)
|
|
||||||
group.handle("HEAD", relativePath, handlers)
|
|
||||||
group.handle("OPTIONS", relativePath, handlers)
|
|
||||||
group.handle("DELETE", relativePath, handlers)
|
|
||||||
group.handle("CONNECT", relativePath, handlers)
|
|
||||||
group.handle("TRACE", relativePath, handlers)
|
|
||||||
return group.returnObj()
|
|
||||||
}
|
|
||||||
|
|
||||||
// StaticFile registers a single route in order to server a single file of the local filesystem.
|
|
||||||
// router.StaticFile("favicon.ico", "./resources/favicon.ico")
|
|
||||||
func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes {
|
|
||||||
if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {
|
|
||||||
panic("URL parameters can not be used when serving a static file")
|
|
||||||
}
|
|
||||||
handler := func(c *Context) {
|
|
||||||
c.File(filepath)
|
|
||||||
}
|
|
||||||
group.GET(relativePath, handler)
|
|
||||||
group.HEAD(relativePath, handler)
|
|
||||||
return group.returnObj()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Static serves files from the given file system root.
|
|
||||||
// Internally a http.FileServer is used, therefore http.NotFound is used instead
|
|
||||||
// of the Router's NotFound handler.
|
|
||||||
// To use the operating system's file system implementation,
|
|
||||||
// use :
|
|
||||||
// router.Static("/static", "/var/www")
|
|
||||||
func (group *RouterGroup) Static(relativePath, root string) IRoutes {
|
|
||||||
return group.StaticFS(relativePath, Dir(root, false))
|
|
||||||
}
|
|
||||||
|
|
||||||
// StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead.
|
|
||||||
// Gin by default user: gin.Dir()
|
|
||||||
func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes {
|
|
||||||
if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {
|
|
||||||
panic("URL parameters can not be used when serving a static folder")
|
|
||||||
}
|
|
||||||
handler := group.createStaticHandler(relativePath, fs)
|
|
||||||
urlPattern := path.Join(relativePath, "/*filepath")
|
|
||||||
|
|
||||||
// Register GET and HEAD handlers
|
|
||||||
group.GET(urlPattern, handler)
|
|
||||||
group.HEAD(urlPattern, handler)
|
|
||||||
return group.returnObj()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc {
|
|
||||||
absolutePath := group.calculateAbsolutePath(relativePath)
|
|
||||||
fileServer := http.StripPrefix(absolutePath, http.FileServer(fs))
|
|
||||||
_, nolisting := fs.(*onlyfilesFS)
|
|
||||||
return func(c *Context) {
|
|
||||||
if nolisting {
|
|
||||||
c.Writer.WriteHeader(404)
|
|
||||||
}
|
|
||||||
fileServer.ServeHTTP(c.Writer, c.Request)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain {
|
|
||||||
finalSize := len(group.Handlers) + len(handlers)
|
|
||||||
if finalSize >= int(abortIndex) {
|
|
||||||
panic("too many handlers")
|
|
||||||
}
|
|
||||||
mergedHandlers := make(HandlersChain, finalSize)
|
|
||||||
copy(mergedHandlers, group.Handlers)
|
|
||||||
copy(mergedHandlers[len(group.Handlers):], handlers)
|
|
||||||
return mergedHandlers
|
|
||||||
}
|
|
||||||
|
|
||||||
func (group *RouterGroup) calculateAbsolutePath(relativePath string) string {
|
|
||||||
return joinPaths(group.basePath, relativePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (group *RouterGroup) returnObj() IRoutes {
|
|
||||||
if group.root {
|
|
||||||
return group.engine
|
|
||||||
}
|
|
||||||
return group
|
|
||||||
}
|
|
||||||
-605
@@ -1,605 +0,0 @@
|
|||||||
// Copyright 2013 Julien Schmidt. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style license that can be found
|
|
||||||
// in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
"unicode"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Param is a single URL parameter, consisting of a key and a value.
|
|
||||||
type Param struct {
|
|
||||||
Key string
|
|
||||||
Value string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Params is a Param-slice, as returned by the router.
|
|
||||||
// The slice is ordered, the first URL parameter is also the first slice value.
|
|
||||||
// It is therefore safe to read values by the index.
|
|
||||||
type Params []Param
|
|
||||||
|
|
||||||
// Get returns the value of the first Param which key matches the given name.
|
|
||||||
// If no matching Param is found, an empty string is returned.
|
|
||||||
func (ps Params) Get(name string) (string, bool) {
|
|
||||||
for _, entry := range ps {
|
|
||||||
if entry.Key == name {
|
|
||||||
return entry.Value, true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
|
|
||||||
// ByName returns the value of the first Param which key matches the given name.
|
|
||||||
// If no matching Param is found, an empty string is returned.
|
|
||||||
func (ps Params) ByName(name string) (va string) {
|
|
||||||
va, _ = ps.Get(name)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
type methodTree struct {
|
|
||||||
method string
|
|
||||||
root *node
|
|
||||||
}
|
|
||||||
|
|
||||||
type methodTrees []methodTree
|
|
||||||
|
|
||||||
func (trees methodTrees) get(method string) *node {
|
|
||||||
for _, tree := range trees {
|
|
||||||
if tree.method == method {
|
|
||||||
return tree.root
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func min(a, b int) int {
|
|
||||||
if a <= b {
|
|
||||||
return a
|
|
||||||
}
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
func countParams(path string) uint8 {
|
|
||||||
var n uint
|
|
||||||
for i := 0; i < len(path); i++ {
|
|
||||||
if path[i] != ':' && path[i] != '*' {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
n++
|
|
||||||
}
|
|
||||||
if n >= 255 {
|
|
||||||
return 255
|
|
||||||
}
|
|
||||||
return uint8(n)
|
|
||||||
}
|
|
||||||
|
|
||||||
type nodeType uint8
|
|
||||||
|
|
||||||
const (
|
|
||||||
static nodeType = iota // default
|
|
||||||
root
|
|
||||||
param
|
|
||||||
catchAll
|
|
||||||
)
|
|
||||||
|
|
||||||
type node struct {
|
|
||||||
path string
|
|
||||||
wildChild bool
|
|
||||||
nType nodeType
|
|
||||||
maxParams uint8
|
|
||||||
indices string
|
|
||||||
children []*node
|
|
||||||
handlers HandlersChain
|
|
||||||
priority uint32
|
|
||||||
}
|
|
||||||
|
|
||||||
// increments priority of the given child and reorders if necessary
|
|
||||||
func (n *node) incrementChildPrio(pos int) int {
|
|
||||||
n.children[pos].priority++
|
|
||||||
prio := n.children[pos].priority
|
|
||||||
|
|
||||||
// adjust position (move to front)
|
|
||||||
newPos := pos
|
|
||||||
for newPos > 0 && n.children[newPos-1].priority < prio {
|
|
||||||
// swap node positions
|
|
||||||
tmpN := n.children[newPos-1]
|
|
||||||
n.children[newPos-1] = n.children[newPos]
|
|
||||||
n.children[newPos] = tmpN
|
|
||||||
|
|
||||||
newPos--
|
|
||||||
}
|
|
||||||
|
|
||||||
// build new index char string
|
|
||||||
if newPos != pos {
|
|
||||||
n.indices = n.indices[:newPos] + // unchanged prefix, might be empty
|
|
||||||
n.indices[pos:pos+1] + // the index char we move
|
|
||||||
n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos'
|
|
||||||
}
|
|
||||||
|
|
||||||
return newPos
|
|
||||||
}
|
|
||||||
|
|
||||||
// addRoute adds a node with the given handle to the path.
|
|
||||||
// Not concurrency-safe!
|
|
||||||
func (n *node) addRoute(path string, handlers HandlersChain) {
|
|
||||||
fullPath := path
|
|
||||||
n.priority++
|
|
||||||
numParams := countParams(path)
|
|
||||||
|
|
||||||
// non-empty tree
|
|
||||||
if len(n.path) > 0 || len(n.children) > 0 {
|
|
||||||
walk:
|
|
||||||
for {
|
|
||||||
// Update maxParams of the current node
|
|
||||||
if numParams > n.maxParams {
|
|
||||||
n.maxParams = numParams
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find the longest common prefix.
|
|
||||||
// This also implies that the common prefix contains no ':' or '*'
|
|
||||||
// since the existing key can't contain those chars.
|
|
||||||
i := 0
|
|
||||||
max := min(len(path), len(n.path))
|
|
||||||
for i < max && path[i] == n.path[i] {
|
|
||||||
i++
|
|
||||||
}
|
|
||||||
|
|
||||||
// Split edge
|
|
||||||
if i < len(n.path) {
|
|
||||||
child := node{
|
|
||||||
path: n.path[i:],
|
|
||||||
wildChild: n.wildChild,
|
|
||||||
indices: n.indices,
|
|
||||||
children: n.children,
|
|
||||||
handlers: n.handlers,
|
|
||||||
priority: n.priority - 1,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update maxParams (max of all children)
|
|
||||||
for i := range child.children {
|
|
||||||
if child.children[i].maxParams > child.maxParams {
|
|
||||||
child.maxParams = child.children[i].maxParams
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
n.children = []*node{&child}
|
|
||||||
// []byte for proper unicode char conversion, see #65
|
|
||||||
n.indices = string([]byte{n.path[i]})
|
|
||||||
n.path = path[:i]
|
|
||||||
n.handlers = nil
|
|
||||||
n.wildChild = false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Make new node a child of this node
|
|
||||||
if i < len(path) {
|
|
||||||
path = path[i:]
|
|
||||||
|
|
||||||
if n.wildChild {
|
|
||||||
n = n.children[0]
|
|
||||||
n.priority++
|
|
||||||
|
|
||||||
// Update maxParams of the child node
|
|
||||||
if numParams > n.maxParams {
|
|
||||||
n.maxParams = numParams
|
|
||||||
}
|
|
||||||
numParams--
|
|
||||||
|
|
||||||
// Check if the wildcard matches
|
|
||||||
if len(path) >= len(n.path) && n.path == path[:len(n.path)] {
|
|
||||||
// check for longer wildcard, e.g. :name and :names
|
|
||||||
if len(n.path) >= len(path) || path[len(n.path)] == '/' {
|
|
||||||
continue walk
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
panic("path segment '" + path +
|
|
||||||
"' conflicts with existing wildcard '" + n.path +
|
|
||||||
"' in path '" + fullPath + "'")
|
|
||||||
}
|
|
||||||
|
|
||||||
c := path[0]
|
|
||||||
|
|
||||||
// slash after param
|
|
||||||
if n.nType == param && c == '/' && len(n.children) == 1 {
|
|
||||||
n = n.children[0]
|
|
||||||
n.priority++
|
|
||||||
continue walk
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if a child with the next path byte exists
|
|
||||||
for i := 0; i < len(n.indices); i++ {
|
|
||||||
if c == n.indices[i] {
|
|
||||||
i = n.incrementChildPrio(i)
|
|
||||||
n = n.children[i]
|
|
||||||
continue walk
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Otherwise insert it
|
|
||||||
if c != ':' && c != '*' {
|
|
||||||
// []byte for proper unicode char conversion, see #65
|
|
||||||
n.indices += string([]byte{c})
|
|
||||||
child := &node{
|
|
||||||
maxParams: numParams,
|
|
||||||
}
|
|
||||||
n.children = append(n.children, child)
|
|
||||||
n.incrementChildPrio(len(n.indices) - 1)
|
|
||||||
n = child
|
|
||||||
}
|
|
||||||
n.insertChild(numParams, path, fullPath, handlers)
|
|
||||||
return
|
|
||||||
|
|
||||||
} else if i == len(path) { // Make node a (in-path) leaf
|
|
||||||
if n.handlers != nil {
|
|
||||||
panic("handlers are already registered for path ''" + fullPath + "'")
|
|
||||||
}
|
|
||||||
n.handlers = handlers
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} else { // Empty tree
|
|
||||||
n.insertChild(numParams, path, fullPath, handlers)
|
|
||||||
n.nType = root
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *node) insertChild(numParams uint8, path string, fullPath string, handlers HandlersChain) {
|
|
||||||
var offset int // already handled bytes of the path
|
|
||||||
|
|
||||||
// find prefix until first wildcard (beginning with ':'' or '*'')
|
|
||||||
for i, max := 0, len(path); numParams > 0; i++ {
|
|
||||||
c := path[i]
|
|
||||||
if c != ':' && c != '*' {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// find wildcard end (either '/' or path end)
|
|
||||||
end := i + 1
|
|
||||||
for end < max && path[end] != '/' {
|
|
||||||
switch path[end] {
|
|
||||||
// the wildcard name must not contain ':' and '*'
|
|
||||||
case ':', '*':
|
|
||||||
panic("only one wildcard per path segment is allowed, has: '" +
|
|
||||||
path[i:] + "' in path '" + fullPath + "'")
|
|
||||||
default:
|
|
||||||
end++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// check if this Node existing children which would be
|
|
||||||
// unreachable if we insert the wildcard here
|
|
||||||
if len(n.children) > 0 {
|
|
||||||
panic("wildcard route '" + path[i:end] +
|
|
||||||
"' conflicts with existing children in path '" + fullPath + "'")
|
|
||||||
}
|
|
||||||
|
|
||||||
// check if the wildcard has a name
|
|
||||||
if end-i < 2 {
|
|
||||||
panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")
|
|
||||||
}
|
|
||||||
|
|
||||||
if c == ':' { // param
|
|
||||||
// split path at the beginning of the wildcard
|
|
||||||
if i > 0 {
|
|
||||||
n.path = path[offset:i]
|
|
||||||
offset = i
|
|
||||||
}
|
|
||||||
|
|
||||||
child := &node{
|
|
||||||
nType: param,
|
|
||||||
maxParams: numParams,
|
|
||||||
}
|
|
||||||
n.children = []*node{child}
|
|
||||||
n.wildChild = true
|
|
||||||
n = child
|
|
||||||
n.priority++
|
|
||||||
numParams--
|
|
||||||
|
|
||||||
// if the path doesn't end with the wildcard, then there
|
|
||||||
// will be another non-wildcard subpath starting with '/'
|
|
||||||
if end < max {
|
|
||||||
n.path = path[offset:end]
|
|
||||||
offset = end
|
|
||||||
|
|
||||||
child := &node{
|
|
||||||
maxParams: numParams,
|
|
||||||
priority: 1,
|
|
||||||
}
|
|
||||||
n.children = []*node{child}
|
|
||||||
n = child
|
|
||||||
}
|
|
||||||
|
|
||||||
} else { // catchAll
|
|
||||||
if end != max || numParams > 1 {
|
|
||||||
panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
|
|
||||||
panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'")
|
|
||||||
}
|
|
||||||
|
|
||||||
// currently fixed width 1 for '/'
|
|
||||||
i--
|
|
||||||
if path[i] != '/' {
|
|
||||||
panic("no / before catch-all in path '" + fullPath + "'")
|
|
||||||
}
|
|
||||||
|
|
||||||
n.path = path[offset:i]
|
|
||||||
|
|
||||||
// first node: catchAll node with empty path
|
|
||||||
child := &node{
|
|
||||||
wildChild: true,
|
|
||||||
nType: catchAll,
|
|
||||||
maxParams: 1,
|
|
||||||
}
|
|
||||||
n.children = []*node{child}
|
|
||||||
n.indices = string(path[i])
|
|
||||||
n = child
|
|
||||||
n.priority++
|
|
||||||
|
|
||||||
// second node: node holding the variable
|
|
||||||
child = &node{
|
|
||||||
path: path[i:],
|
|
||||||
nType: catchAll,
|
|
||||||
maxParams: 1,
|
|
||||||
handlers: handlers,
|
|
||||||
priority: 1,
|
|
||||||
}
|
|
||||||
n.children = []*node{child}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// insert remaining path part and handle to the leaf
|
|
||||||
n.path = path[offset:]
|
|
||||||
n.handlers = handlers
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the handle registered with the given path (key). The values of
|
|
||||||
// wildcards are saved to a map.
|
|
||||||
// If no handle can be found, a TSR (trailing slash redirect) recommendation is
|
|
||||||
// made if a handle exists with an extra (without the) trailing slash for the
|
|
||||||
// given path.
|
|
||||||
func (n *node) getValue(path string, po Params) (handlers HandlersChain, p Params, tsr bool) {
|
|
||||||
p = po
|
|
||||||
walk: // Outer loop for walking the tree
|
|
||||||
for {
|
|
||||||
if len(path) > len(n.path) {
|
|
||||||
if path[:len(n.path)] == n.path {
|
|
||||||
path = path[len(n.path):]
|
|
||||||
// If this node does not have a wildcard (param or catchAll)
|
|
||||||
// child, we can just look up the next child node and continue
|
|
||||||
// to walk down the tree
|
|
||||||
if !n.wildChild {
|
|
||||||
c := path[0]
|
|
||||||
for i := 0; i < len(n.indices); i++ {
|
|
||||||
if c == n.indices[i] {
|
|
||||||
n = n.children[i]
|
|
||||||
continue walk
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nothing found.
|
|
||||||
// We can recommend to redirect to the same URL without a
|
|
||||||
// trailing slash if a leaf exists for that path.
|
|
||||||
tsr = (path == "/" && n.handlers != nil)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// handle wildcard child
|
|
||||||
n = n.children[0]
|
|
||||||
switch n.nType {
|
|
||||||
case param:
|
|
||||||
// find param end (either '/' or path end)
|
|
||||||
end := 0
|
|
||||||
for end < len(path) && path[end] != '/' {
|
|
||||||
end++
|
|
||||||
}
|
|
||||||
|
|
||||||
// save param value
|
|
||||||
if cap(p) < int(n.maxParams) {
|
|
||||||
p = make(Params, 0, n.maxParams)
|
|
||||||
}
|
|
||||||
i := len(p)
|
|
||||||
p = p[:i+1] // expand slice within preallocated capacity
|
|
||||||
p[i].Key = n.path[1:]
|
|
||||||
p[i].Value = path[:end]
|
|
||||||
|
|
||||||
// we need to go deeper!
|
|
||||||
if end < len(path) {
|
|
||||||
if len(n.children) > 0 {
|
|
||||||
path = path[end:]
|
|
||||||
n = n.children[0]
|
|
||||||
continue walk
|
|
||||||
}
|
|
||||||
|
|
||||||
// ... but we can't
|
|
||||||
tsr = (len(path) == end+1)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if handlers = n.handlers; handlers != nil {
|
|
||||||
return
|
|
||||||
} else if len(n.children) == 1 {
|
|
||||||
// No handle found. Check if a handle for this path + a
|
|
||||||
// trailing slash exists for TSR recommendation
|
|
||||||
n = n.children[0]
|
|
||||||
tsr = (n.path == "/" && n.handlers != nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
|
|
||||||
case catchAll:
|
|
||||||
// save param value
|
|
||||||
if cap(p) < int(n.maxParams) {
|
|
||||||
p = make(Params, 0, n.maxParams)
|
|
||||||
}
|
|
||||||
i := len(p)
|
|
||||||
p = p[:i+1] // expand slice within preallocated capacity
|
|
||||||
p[i].Key = n.path[2:]
|
|
||||||
p[i].Value = path
|
|
||||||
|
|
||||||
handlers = n.handlers
|
|
||||||
return
|
|
||||||
|
|
||||||
default:
|
|
||||||
panic("invalid node type")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if path == n.path {
|
|
||||||
// We should have reached the node containing the handle.
|
|
||||||
// Check if this node has a handle registered.
|
|
||||||
if handlers = n.handlers; handlers != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if path == "/" && n.wildChild && n.nType != root {
|
|
||||||
tsr = true
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// No handle found. Check if a handle for this path + a
|
|
||||||
// trailing slash exists for trailing slash recommendation
|
|
||||||
for i := 0; i < len(n.indices); i++ {
|
|
||||||
if n.indices[i] == '/' {
|
|
||||||
n = n.children[i]
|
|
||||||
tsr = (len(n.path) == 1 && n.handlers != nil) ||
|
|
||||||
(n.nType == catchAll && n.children[0].handlers != nil)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nothing found. We can recommend to redirect to the same URL with an
|
|
||||||
// extra trailing slash if a leaf exists for that path
|
|
||||||
tsr = (path == "/") ||
|
|
||||||
(len(n.path) == len(path)+1 && n.path[len(path)] == '/' &&
|
|
||||||
path == n.path[:len(n.path)-1] && n.handlers != nil)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Makes a case-insensitive lookup of the given path and tries to find a handler.
|
|
||||||
// It can optionally also fix trailing slashes.
|
|
||||||
// It returns the case-corrected path and a bool indicating whether the lookup
|
|
||||||
// was successful.
|
|
||||||
func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) {
|
|
||||||
ciPath = make([]byte, 0, len(path)+1) // preallocate enough memory
|
|
||||||
|
|
||||||
// Outer loop for walking the tree
|
|
||||||
for len(path) >= len(n.path) && strings.ToLower(path[:len(n.path)]) == strings.ToLower(n.path) {
|
|
||||||
path = path[len(n.path):]
|
|
||||||
ciPath = append(ciPath, n.path...)
|
|
||||||
|
|
||||||
if len(path) > 0 {
|
|
||||||
// If this node does not have a wildcard (param or catchAll) child,
|
|
||||||
// we can just look up the next child node and continue to walk down
|
|
||||||
// the tree
|
|
||||||
if !n.wildChild {
|
|
||||||
r := unicode.ToLower(rune(path[0]))
|
|
||||||
for i, index := range n.indices {
|
|
||||||
// must use recursive approach since both index and
|
|
||||||
// ToLower(index) could exist. We must check both.
|
|
||||||
if r == unicode.ToLower(index) {
|
|
||||||
out, found := n.children[i].findCaseInsensitivePath(path, fixTrailingSlash)
|
|
||||||
if found {
|
|
||||||
return append(ciPath, out...), true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nothing found. We can recommend to redirect to the same URL
|
|
||||||
// without a trailing slash if a leaf exists for that path
|
|
||||||
found = (fixTrailingSlash && path == "/" && n.handlers != nil)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
n = n.children[0]
|
|
||||||
switch n.nType {
|
|
||||||
case param:
|
|
||||||
// find param end (either '/' or path end)
|
|
||||||
k := 0
|
|
||||||
for k < len(path) && path[k] != '/' {
|
|
||||||
k++
|
|
||||||
}
|
|
||||||
|
|
||||||
// add param value to case insensitive path
|
|
||||||
ciPath = append(ciPath, path[:k]...)
|
|
||||||
|
|
||||||
// we need to go deeper!
|
|
||||||
if k < len(path) {
|
|
||||||
if len(n.children) > 0 {
|
|
||||||
path = path[k:]
|
|
||||||
n = n.children[0]
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// ... but we can't
|
|
||||||
if fixTrailingSlash && len(path) == k+1 {
|
|
||||||
return ciPath, true
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if n.handlers != nil {
|
|
||||||
return ciPath, true
|
|
||||||
} else if fixTrailingSlash && len(n.children) == 1 {
|
|
||||||
// No handle found. Check if a handle for this path + a
|
|
||||||
// trailing slash exists
|
|
||||||
n = n.children[0]
|
|
||||||
if n.path == "/" && n.handlers != nil {
|
|
||||||
return append(ciPath, '/'), true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return
|
|
||||||
|
|
||||||
case catchAll:
|
|
||||||
return append(ciPath, path...), true
|
|
||||||
|
|
||||||
default:
|
|
||||||
panic("invalid node type")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// We should have reached the node containing the handle.
|
|
||||||
// Check if this node has a handle registered.
|
|
||||||
if n.handlers != nil {
|
|
||||||
return ciPath, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// No handle found.
|
|
||||||
// Try to fix the path by adding a trailing slash
|
|
||||||
if fixTrailingSlash {
|
|
||||||
for i := 0; i < len(n.indices); i++ {
|
|
||||||
if n.indices[i] == '/' {
|
|
||||||
n = n.children[i]
|
|
||||||
if (len(n.path) == 1 && n.handlers != nil) ||
|
|
||||||
(n.nType == catchAll && n.children[0].handlers != nil) {
|
|
||||||
return append(ciPath, '/'), true
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nothing found.
|
|
||||||
// Try to fix the path by adding / removing a trailing slash
|
|
||||||
if fixTrailingSlash {
|
|
||||||
if path == "/" {
|
|
||||||
return ciPath, true
|
|
||||||
}
|
|
||||||
if len(path)+1 == len(n.path) && n.path[len(path)] == '/' &&
|
|
||||||
strings.ToLower(path) == strings.ToLower(n.path[:len(path)]) &&
|
|
||||||
n.handlers != nil {
|
|
||||||
return append(ciPath, n.path...), true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
-154
@@ -1,154 +0,0 @@
|
|||||||
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
|
||||||
// Use of this source code is governed by a MIT style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package gin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/xml"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"path"
|
|
||||||
"reflect"
|
|
||||||
"runtime"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
const BindKey = "_gin-gonic/gin/bindkey"
|
|
||||||
|
|
||||||
func Bind(val interface{}) HandlerFunc {
|
|
||||||
value := reflect.ValueOf(val)
|
|
||||||
if value.Kind() == reflect.Ptr {
|
|
||||||
panic(`Bind struct can not be a pointer. Example:
|
|
||||||
Use: gin.Bind(Struct{}) instead of gin.Bind(&Struct{})
|
|
||||||
`)
|
|
||||||
}
|
|
||||||
typ := value.Type()
|
|
||||||
|
|
||||||
return func(c *Context) {
|
|
||||||
obj := reflect.New(typ).Interface()
|
|
||||||
if c.Bind(obj) == nil {
|
|
||||||
c.Set(BindKey, obj)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WrapF(f http.HandlerFunc) HandlerFunc {
|
|
||||||
return func(c *Context) {
|
|
||||||
f(c.Writer, c.Request)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WrapH(h http.Handler) HandlerFunc {
|
|
||||||
return func(c *Context) {
|
|
||||||
h.ServeHTTP(c.Writer, c.Request)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type H map[string]interface{}
|
|
||||||
|
|
||||||
// MarshalXML allows type H to be used with xml.Marshal
|
|
||||||
func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
|
|
||||||
start.Name = xml.Name{
|
|
||||||
Space: "",
|
|
||||||
Local: "map",
|
|
||||||
}
|
|
||||||
if err := e.EncodeToken(start); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
for key, value := range h {
|
|
||||||
elem := xml.StartElement{
|
|
||||||
Name: xml.Name{Space: "", Local: key},
|
|
||||||
Attr: []xml.Attr{},
|
|
||||||
}
|
|
||||||
if err := e.EncodeElement(value, elem); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := e.EncodeToken(xml.EndElement{Name: start.Name}); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func assert1(guard bool, text string) {
|
|
||||||
if !guard {
|
|
||||||
panic(text)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func filterFlags(content string) string {
|
|
||||||
for i, char := range content {
|
|
||||||
if char == ' ' || char == ';' {
|
|
||||||
return content[:i]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return content
|
|
||||||
}
|
|
||||||
|
|
||||||
func chooseData(custom, wildcard interface{}) interface{} {
|
|
||||||
if custom == nil {
|
|
||||||
if wildcard == nil {
|
|
||||||
panic("negotiation config is invalid")
|
|
||||||
}
|
|
||||||
return wildcard
|
|
||||||
}
|
|
||||||
return custom
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseAccept(acceptHeader string) []string {
|
|
||||||
parts := strings.Split(acceptHeader, ",")
|
|
||||||
out := make([]string, 0, len(parts))
|
|
||||||
for _, part := range parts {
|
|
||||||
index := strings.IndexByte(part, ';')
|
|
||||||
if index >= 0 {
|
|
||||||
part = part[0:index]
|
|
||||||
}
|
|
||||||
part = strings.TrimSpace(part)
|
|
||||||
if len(part) > 0 {
|
|
||||||
out = append(out, part)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
func lastChar(str string) uint8 {
|
|
||||||
size := len(str)
|
|
||||||
if size == 0 {
|
|
||||||
panic("The length of the string can't be 0")
|
|
||||||
}
|
|
||||||
return str[size-1]
|
|
||||||
}
|
|
||||||
|
|
||||||
func nameOfFunction(f interface{}) string {
|
|
||||||
return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func joinPaths(absolutePath, relativePath string) string {
|
|
||||||
if len(relativePath) == 0 {
|
|
||||||
return absolutePath
|
|
||||||
}
|
|
||||||
|
|
||||||
finalPath := path.Join(absolutePath, relativePath)
|
|
||||||
appendSlash := lastChar(relativePath) == '/' && lastChar(finalPath) != '/'
|
|
||||||
if appendSlash {
|
|
||||||
return finalPath + "/"
|
|
||||||
}
|
|
||||||
return finalPath
|
|
||||||
}
|
|
||||||
|
|
||||||
func resolveAddress(addr []string) string {
|
|
||||||
switch len(addr) {
|
|
||||||
case 0:
|
|
||||||
if port := os.Getenv("PORT"); len(port) > 0 {
|
|
||||||
debugPrint("Environment variable PORT=\"%s\"", port)
|
|
||||||
return ":" + port
|
|
||||||
}
|
|
||||||
debugPrint("Environment variable PORT is undefined. Using port :8080 by default")
|
|
||||||
return ":8080"
|
|
||||||
case 1:
|
|
||||||
return addr[0]
|
|
||||||
default:
|
|
||||||
panic("too much parameters")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-1
@@ -1 +0,0 @@
|
|||||||
box: wercker/default
|
|
||||||
Vendored
-21
@@ -1,21 +0,0 @@
|
|||||||
// Copyright 2013 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.
|
|
||||||
|
|
||||||
package log_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ExampleLogger() {
|
|
||||||
var buf bytes.Buffer
|
|
||||||
logger := log.New(&buf, "logger: ", log.Lshortfile)
|
|
||||||
logger.Print("Hello, log file!")
|
|
||||||
|
|
||||||
fmt.Print(&buf)
|
|
||||||
// Output:
|
|
||||||
// logger: example_test.go:16: Hello, log file!
|
|
||||||
}
|
|
||||||
Vendored
-348
@@ -1,348 +0,0 @@
|
|||||||
// Copyright 2009 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.
|
|
||||||
|
|
||||||
// Package log implements a simple logging package. It defines a type, Logger,
|
|
||||||
// with methods for formatting output. It also has a predefined 'standard'
|
|
||||||
// Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and
|
|
||||||
// Panic[f|ln], which are easier to use than creating a Logger manually.
|
|
||||||
// That logger writes to standard error and prints the date and time
|
|
||||||
// of each logged message.
|
|
||||||
// Every log message is output on a separate line: if the message being
|
|
||||||
// printed does not end in a newline, the logger will add one.
|
|
||||||
// The Fatal functions call os.Exit(1) after writing the log message.
|
|
||||||
// The Panic functions call panic after writing the log message.
|
|
||||||
package log
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"runtime"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// These flags define which text to prefix to each log entry generated by the Logger.
|
|
||||||
const (
|
|
||||||
// Bits or'ed together to control what's printed.
|
|
||||||
// There is no control over the order they appear (the order listed
|
|
||||||
// here) or the format they present (as described in the comments).
|
|
||||||
// The prefix is followed by a colon only when Llongfile or Lshortfile
|
|
||||||
// is specified.
|
|
||||||
// For example, flags Ldate | Ltime (or LstdFlags) produce,
|
|
||||||
// 2009/01/23 01:23:23 message
|
|
||||||
// while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,
|
|
||||||
// 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
|
|
||||||
Ldate = 1 << iota // the date in the local time zone: 2009/01/23
|
|
||||||
Ltime // the time in the local time zone: 01:23:23
|
|
||||||
Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime.
|
|
||||||
Llongfile // full file name and line number: /a/b/c/d.go:23
|
|
||||||
Lshortfile // final file name element and line number: d.go:23. overrides Llongfile
|
|
||||||
LUTC // if Ldate or Ltime is set, use UTC rather than the local time zone
|
|
||||||
LstdFlags = Ldate | Ltime // initial values for the standard logger
|
|
||||||
)
|
|
||||||
|
|
||||||
// A Logger represents an active logging object that generates lines of
|
|
||||||
// output to an io.Writer. Each logging operation makes a single call to
|
|
||||||
// the Writer's Write method. A Logger can be used simultaneously from
|
|
||||||
// multiple goroutines; it guarantees to serialize access to the Writer.
|
|
||||||
type Logger struct {
|
|
||||||
mu sync.Mutex // ensures atomic writes; protects the following fields
|
|
||||||
prefix string // prefix to write at beginning of each line
|
|
||||||
flag int // properties
|
|
||||||
out io.Writer // destination for output
|
|
||||||
buf []byte // for accumulating text to write
|
|
||||||
}
|
|
||||||
|
|
||||||
// New creates a new Logger. The out variable sets the
|
|
||||||
// destination to which log data will be written.
|
|
||||||
// The prefix appears at the beginning of each generated log line.
|
|
||||||
// The flag argument defines the logging properties.
|
|
||||||
func New(out io.Writer, prefix string, flag int) *Logger {
|
|
||||||
return &Logger{out: out, prefix: prefix, flag: flag}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetOutput sets the output destination for the logger.
|
|
||||||
func (l *Logger) SetOutput(w io.Writer) {
|
|
||||||
l.mu.Lock()
|
|
||||||
defer l.mu.Unlock()
|
|
||||||
l.out = w
|
|
||||||
}
|
|
||||||
|
|
||||||
var std = New(os.Stderr, "", LstdFlags)
|
|
||||||
|
|
||||||
// Cheap integer to fixed-width decimal ASCII. Give a negative width to avoid zero-padding.
|
|
||||||
func itoa(buf *[]byte, i int, wid int) {
|
|
||||||
// Assemble decimal in reverse order.
|
|
||||||
var b [20]byte
|
|
||||||
bp := len(b) - 1
|
|
||||||
for i >= 10 || wid > 1 {
|
|
||||||
wid--
|
|
||||||
q := i / 10
|
|
||||||
b[bp] = byte('0' + i - q*10)
|
|
||||||
bp--
|
|
||||||
i = q
|
|
||||||
}
|
|
||||||
// i < 10
|
|
||||||
b[bp] = byte('0' + i)
|
|
||||||
*buf = append(*buf, b[bp:]...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Logger) formatHeader(buf *[]byte, t time.Time, file string, line int) {
|
|
||||||
*buf = append(*buf, l.prefix...)
|
|
||||||
if l.flag&LUTC != 0 {
|
|
||||||
t = t.UTC()
|
|
||||||
}
|
|
||||||
if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {
|
|
||||||
if l.flag&Ldate != 0 {
|
|
||||||
year, month, day := t.Date()
|
|
||||||
itoa(buf, year, 4)
|
|
||||||
*buf = append(*buf, '/')
|
|
||||||
itoa(buf, int(month), 2)
|
|
||||||
*buf = append(*buf, '/')
|
|
||||||
itoa(buf, day, 2)
|
|
||||||
*buf = append(*buf, ' ')
|
|
||||||
}
|
|
||||||
if l.flag&(Ltime|Lmicroseconds) != 0 {
|
|
||||||
hour, min, sec := t.Clock()
|
|
||||||
itoa(buf, hour, 2)
|
|
||||||
*buf = append(*buf, ':')
|
|
||||||
itoa(buf, min, 2)
|
|
||||||
*buf = append(*buf, ':')
|
|
||||||
itoa(buf, sec, 2)
|
|
||||||
if l.flag&Lmicroseconds != 0 {
|
|
||||||
*buf = append(*buf, '.')
|
|
||||||
itoa(buf, t.Nanosecond()/1e3, 6)
|
|
||||||
}
|
|
||||||
*buf = append(*buf, ' ')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if l.flag&(Lshortfile|Llongfile) != 0 {
|
|
||||||
if l.flag&Lshortfile != 0 {
|
|
||||||
short := file
|
|
||||||
for i := len(file) - 1; i > 0; i-- {
|
|
||||||
if file[i] == '/' {
|
|
||||||
short = file[i+1:]
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
file = short
|
|
||||||
}
|
|
||||||
*buf = append(*buf, file...)
|
|
||||||
*buf = append(*buf, ':')
|
|
||||||
itoa(buf, line, -1)
|
|
||||||
*buf = append(*buf, ": "...)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Output writes the output for a logging event. The string s contains
|
|
||||||
// the text to print after the prefix specified by the flags of the
|
|
||||||
// Logger. A newline is appended if the last character of s is not
|
|
||||||
// already a newline. Calldepth is used to recover the PC and is
|
|
||||||
// provided for generality, although at the moment on all pre-defined
|
|
||||||
// paths it will be 2.
|
|
||||||
func (l *Logger) Output(calldepth int, s string) error {
|
|
||||||
now := time.Now() // get this early.
|
|
||||||
var file string
|
|
||||||
var line int
|
|
||||||
l.mu.Lock()
|
|
||||||
defer l.mu.Unlock()
|
|
||||||
if l.flag&(Lshortfile|Llongfile) != 0 {
|
|
||||||
// release lock while getting caller info - it's expensive.
|
|
||||||
l.mu.Unlock()
|
|
||||||
var ok bool
|
|
||||||
_, file, line, ok = runtime.Caller(calldepth)
|
|
||||||
if !ok {
|
|
||||||
file = "???"
|
|
||||||
line = 0
|
|
||||||
}
|
|
||||||
l.mu.Lock()
|
|
||||||
}
|
|
||||||
l.buf = l.buf[:0]
|
|
||||||
l.formatHeader(&l.buf, now, file, line)
|
|
||||||
l.buf = append(l.buf, s...)
|
|
||||||
if len(s) == 0 || s[len(s)-1] != '\n' {
|
|
||||||
l.buf = append(l.buf, '\n')
|
|
||||||
}
|
|
||||||
_, err := l.out.Write(l.buf)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Printf calls l.Output to print to the logger.
|
|
||||||
// Arguments are handled in the manner of fmt.Printf.
|
|
||||||
func (l *Logger) Printf(format string, v ...interface{}) {
|
|
||||||
l.Output(2, fmt.Sprintf(format, v...))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Print calls l.Output to print to the logger.
|
|
||||||
// Arguments are handled in the manner of fmt.Print.
|
|
||||||
func (l *Logger) Print(v ...interface{}) { l.Output(2, fmt.Sprint(v...)) }
|
|
||||||
|
|
||||||
// Println calls l.Output to print to the logger.
|
|
||||||
// Arguments are handled in the manner of fmt.Println.
|
|
||||||
func (l *Logger) Println(v ...interface{}) { l.Output(2, fmt.Sprintln(v...)) }
|
|
||||||
|
|
||||||
// Fatal is equivalent to l.Print() followed by a call to os.Exit(1).
|
|
||||||
func (l *Logger) Fatal(v ...interface{}) {
|
|
||||||
l.Output(2, fmt.Sprint(v...))
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1).
|
|
||||||
func (l *Logger) Fatalf(format string, v ...interface{}) {
|
|
||||||
l.Output(2, fmt.Sprintf(format, v...))
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fatalln is equivalent to l.Println() followed by a call to os.Exit(1).
|
|
||||||
func (l *Logger) Fatalln(v ...interface{}) {
|
|
||||||
l.Output(2, fmt.Sprintln(v...))
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Panic is equivalent to l.Print() followed by a call to panic().
|
|
||||||
func (l *Logger) Panic(v ...interface{}) {
|
|
||||||
s := fmt.Sprint(v...)
|
|
||||||
l.Output(2, s)
|
|
||||||
panic(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Panicf is equivalent to l.Printf() followed by a call to panic().
|
|
||||||
func (l *Logger) Panicf(format string, v ...interface{}) {
|
|
||||||
s := fmt.Sprintf(format, v...)
|
|
||||||
l.Output(2, s)
|
|
||||||
panic(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Panicln is equivalent to l.Println() followed by a call to panic().
|
|
||||||
func (l *Logger) Panicln(v ...interface{}) {
|
|
||||||
s := fmt.Sprintln(v...)
|
|
||||||
l.Output(2, s)
|
|
||||||
panic(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Flags returns the output flags for the logger.
|
|
||||||
func (l *Logger) Flags() int {
|
|
||||||
l.mu.Lock()
|
|
||||||
defer l.mu.Unlock()
|
|
||||||
return l.flag
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetFlags sets the output flags for the logger.
|
|
||||||
func (l *Logger) SetFlags(flag int) {
|
|
||||||
l.mu.Lock()
|
|
||||||
defer l.mu.Unlock()
|
|
||||||
l.flag = flag
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prefix returns the output prefix for the logger.
|
|
||||||
func (l *Logger) Prefix() string {
|
|
||||||
l.mu.Lock()
|
|
||||||
defer l.mu.Unlock()
|
|
||||||
return l.prefix
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetPrefix sets the output prefix for the logger.
|
|
||||||
func (l *Logger) SetPrefix(prefix string) {
|
|
||||||
l.mu.Lock()
|
|
||||||
defer l.mu.Unlock()
|
|
||||||
l.prefix = prefix
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetOutput sets the output destination for the standard logger.
|
|
||||||
func SetOutput(w io.Writer) {
|
|
||||||
std.mu.Lock()
|
|
||||||
defer std.mu.Unlock()
|
|
||||||
std.out = w
|
|
||||||
}
|
|
||||||
|
|
||||||
// Flags returns the output flags for the standard logger.
|
|
||||||
func Flags() int {
|
|
||||||
return std.Flags()
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetFlags sets the output flags for the standard logger.
|
|
||||||
func SetFlags(flag int) {
|
|
||||||
std.SetFlags(flag)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prefix returns the output prefix for the standard logger.
|
|
||||||
func Prefix() string {
|
|
||||||
return std.Prefix()
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetPrefix sets the output prefix for the standard logger.
|
|
||||||
func SetPrefix(prefix string) {
|
|
||||||
std.SetPrefix(prefix)
|
|
||||||
}
|
|
||||||
|
|
||||||
// These functions write to the standard logger.
|
|
||||||
|
|
||||||
// Print calls Output to print to the standard logger.
|
|
||||||
// Arguments are handled in the manner of fmt.Print.
|
|
||||||
func Print(v ...interface{}) {
|
|
||||||
std.Output(2, fmt.Sprint(v...))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Printf calls Output to print to the standard logger.
|
|
||||||
// Arguments are handled in the manner of fmt.Printf.
|
|
||||||
func Printf(format string, v ...interface{}) {
|
|
||||||
std.Output(2, fmt.Sprintf(format, v...))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Println calls Output to print to the standard logger.
|
|
||||||
// Arguments are handled in the manner of fmt.Println.
|
|
||||||
func Println(v ...interface{}) {
|
|
||||||
std.Output(2, fmt.Sprintln(v...))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fatal is equivalent to Print() followed by a call to os.Exit(1).
|
|
||||||
func Fatal(v ...interface{}) {
|
|
||||||
std.Output(2, fmt.Sprint(v...))
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fatalf is equivalent to Printf() followed by a call to os.Exit(1).
|
|
||||||
func Fatalf(format string, v ...interface{}) {
|
|
||||||
std.Output(2, fmt.Sprintf(format, v...))
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fatalln is equivalent to Println() followed by a call to os.Exit(1).
|
|
||||||
func Fatalln(v ...interface{}) {
|
|
||||||
std.Output(2, fmt.Sprintln(v...))
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Panic is equivalent to Print() followed by a call to panic().
|
|
||||||
func Panic(v ...interface{}) {
|
|
||||||
s := fmt.Sprint(v...)
|
|
||||||
std.Output(2, s)
|
|
||||||
panic(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Panicf is equivalent to Printf() followed by a call to panic().
|
|
||||||
func Panicf(format string, v ...interface{}) {
|
|
||||||
s := fmt.Sprintf(format, v...)
|
|
||||||
std.Output(2, s)
|
|
||||||
panic(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Panicln is equivalent to Println() followed by a call to panic().
|
|
||||||
func Panicln(v ...interface{}) {
|
|
||||||
s := fmt.Sprintln(v...)
|
|
||||||
std.Output(2, s)
|
|
||||||
panic(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Output writes the output for a logging event. The string s contains
|
|
||||||
// the text to print after the prefix specified by the flags of the
|
|
||||||
// Logger. A newline is appended if the last character of s is not
|
|
||||||
// already a newline. Calldepth is the count of the number of
|
|
||||||
// frames to skip when computing the file name and line number
|
|
||||||
// if Llongfile or Lshortfile is set; a value of 1 will print the details
|
|
||||||
// for the caller of Output.
|
|
||||||
func Output(calldepth int, s string) error {
|
|
||||||
return std.Output(calldepth+1, s) // +1 for this frame.
|
|
||||||
}
|
|
||||||
Vendored
-184
@@ -1,184 +0,0 @@
|
|||||||
// Copyright 2009 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.
|
|
||||||
|
|
||||||
package log
|
|
||||||
|
|
||||||
// These tests are too simple.
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
Rdate = `[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]`
|
|
||||||
Rtime = `[0-9][0-9]:[0-9][0-9]:[0-9][0-9]`
|
|
||||||
Rmicroseconds = `\.[0-9][0-9][0-9][0-9][0-9][0-9]`
|
|
||||||
Rline = `(57|59):` // must update if the calls to l.Printf / l.Print below move
|
|
||||||
Rlongfile = `.*/[A-Za-z0-9_\-]+\.go:` + Rline
|
|
||||||
Rshortfile = `[A-Za-z0-9_\-]+\.go:` + Rline
|
|
||||||
)
|
|
||||||
|
|
||||||
type tester struct {
|
|
||||||
flag int
|
|
||||||
prefix string
|
|
||||||
pattern string // regexp that log output must match; we add ^ and expected_text$ always
|
|
||||||
}
|
|
||||||
|
|
||||||
var tests = []tester{
|
|
||||||
// individual pieces:
|
|
||||||
{0, "", ""},
|
|
||||||
{0, "XXX", "XXX"},
|
|
||||||
{Ldate, "", Rdate + " "},
|
|
||||||
{Ltime, "", Rtime + " "},
|
|
||||||
{Ltime | Lmicroseconds, "", Rtime + Rmicroseconds + " "},
|
|
||||||
{Lmicroseconds, "", Rtime + Rmicroseconds + " "}, // microsec implies time
|
|
||||||
{Llongfile, "", Rlongfile + " "},
|
|
||||||
{Lshortfile, "", Rshortfile + " "},
|
|
||||||
{Llongfile | Lshortfile, "", Rshortfile + " "}, // shortfile overrides longfile
|
|
||||||
// everything at once:
|
|
||||||
{Ldate | Ltime | Lmicroseconds | Llongfile, "XXX", "XXX" + Rdate + " " + Rtime + Rmicroseconds + " " + Rlongfile + " "},
|
|
||||||
{Ldate | Ltime | Lmicroseconds | Lshortfile, "XXX", "XXX" + Rdate + " " + Rtime + Rmicroseconds + " " + Rshortfile + " "},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test using Println("hello", 23, "world") or using Printf("hello %d world", 23)
|
|
||||||
func testPrint(t *testing.T, flag int, prefix string, pattern string, useFormat bool) {
|
|
||||||
buf := new(bytes.Buffer)
|
|
||||||
SetOutput(buf)
|
|
||||||
SetFlags(flag)
|
|
||||||
SetPrefix(prefix)
|
|
||||||
if useFormat {
|
|
||||||
Printf("hello %d world", 23)
|
|
||||||
} else {
|
|
||||||
Println("hello", 23, "world")
|
|
||||||
}
|
|
||||||
line := buf.String()
|
|
||||||
line = line[0 : len(line)-1]
|
|
||||||
pattern = "^" + pattern + "hello 23 world$"
|
|
||||||
matched, err4 := regexp.MatchString(pattern, line)
|
|
||||||
if err4 != nil {
|
|
||||||
t.Fatal("pattern did not compile:", err4)
|
|
||||||
}
|
|
||||||
if !matched {
|
|
||||||
t.Errorf("log output should match %q is %q", pattern, line)
|
|
||||||
}
|
|
||||||
SetOutput(os.Stderr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAll(t *testing.T) {
|
|
||||||
for _, testcase := range tests {
|
|
||||||
testPrint(t, testcase.flag, testcase.prefix, testcase.pattern, false)
|
|
||||||
testPrint(t, testcase.flag, testcase.prefix, testcase.pattern, true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestOutput(t *testing.T) {
|
|
||||||
const testString = "test"
|
|
||||||
var b bytes.Buffer
|
|
||||||
l := New(&b, "", 0)
|
|
||||||
l.Println(testString)
|
|
||||||
if expect := testString + "\n"; b.String() != expect {
|
|
||||||
t.Errorf("log output should match %q is %q", expect, b.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFlagAndPrefixSetting(t *testing.T) {
|
|
||||||
var b bytes.Buffer
|
|
||||||
l := New(&b, "Test:", LstdFlags)
|
|
||||||
f := l.Flags()
|
|
||||||
if f != LstdFlags {
|
|
||||||
t.Errorf("Flags 1: expected %x got %x", LstdFlags, f)
|
|
||||||
}
|
|
||||||
l.SetFlags(f | Lmicroseconds)
|
|
||||||
f = l.Flags()
|
|
||||||
if f != LstdFlags|Lmicroseconds {
|
|
||||||
t.Errorf("Flags 2: expected %x got %x", LstdFlags|Lmicroseconds, f)
|
|
||||||
}
|
|
||||||
p := l.Prefix()
|
|
||||||
if p != "Test:" {
|
|
||||||
t.Errorf(`Prefix: expected "Test:" got %q`, p)
|
|
||||||
}
|
|
||||||
l.SetPrefix("Reality:")
|
|
||||||
p = l.Prefix()
|
|
||||||
if p != "Reality:" {
|
|
||||||
t.Errorf(`Prefix: expected "Reality:" got %q`, p)
|
|
||||||
}
|
|
||||||
// Verify a log message looks right, with our prefix and microseconds present.
|
|
||||||
l.Print("hello")
|
|
||||||
pattern := "^Reality:" + Rdate + " " + Rtime + Rmicroseconds + " hello\n"
|
|
||||||
matched, err := regexp.Match(pattern, b.Bytes())
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pattern %q did not compile: %s", pattern, err)
|
|
||||||
}
|
|
||||||
if !matched {
|
|
||||||
t.Error("message did not match pattern")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestUTCFlag(t *testing.T) {
|
|
||||||
var b bytes.Buffer
|
|
||||||
l := New(&b, "Test:", LstdFlags)
|
|
||||||
l.SetFlags(Ldate | Ltime | LUTC)
|
|
||||||
// Verify a log message looks right in the right time zone. Quantize to the second only.
|
|
||||||
now := time.Now().UTC()
|
|
||||||
l.Print("hello")
|
|
||||||
want := fmt.Sprintf("Test:%d/%.2d/%.2d %.2d:%.2d:%.2d hello\n",
|
|
||||||
now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
|
|
||||||
got := b.String()
|
|
||||||
if got == want {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// It's possible we crossed a second boundary between getting now and logging,
|
|
||||||
// so add a second and try again. This should very nearly always work.
|
|
||||||
now = now.Add(time.Second)
|
|
||||||
want = fmt.Sprintf("Test:%d/%.2d/%.2d %.2d:%.2d:%.2d hello\n",
|
|
||||||
now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
|
|
||||||
if got == want {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
t.Errorf("got %q; want %q", got, want)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEmptyPrintCreatesLine(t *testing.T) {
|
|
||||||
var b bytes.Buffer
|
|
||||||
l := New(&b, "Header:", LstdFlags)
|
|
||||||
l.Print()
|
|
||||||
l.Println("non-empty")
|
|
||||||
output := b.String()
|
|
||||||
if n := strings.Count(output, "Header"); n != 2 {
|
|
||||||
t.Errorf("expected 2 headers, got %d", n)
|
|
||||||
}
|
|
||||||
if n := strings.Count(output, "\n"); n != 2 {
|
|
||||||
t.Errorf("expected 2 lines, got %d", n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkItoa(b *testing.B) {
|
|
||||||
dst := make([]byte, 0, 64)
|
|
||||||
for i := 0; i < b.N; i++ {
|
|
||||||
dst = dst[0:0]
|
|
||||||
itoa(&dst, 2015, 4) // year
|
|
||||||
itoa(&dst, 1, 2) // month
|
|
||||||
itoa(&dst, 30, 2) // day
|
|
||||||
itoa(&dst, 12, 2) // hour
|
|
||||||
itoa(&dst, 56, 2) // minute
|
|
||||||
itoa(&dst, 0, 2) // second
|
|
||||||
itoa(&dst, 987654, 6) // microsecond
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkPrintln(b *testing.B) {
|
|
||||||
const testString = "test"
|
|
||||||
var buf bytes.Buffer
|
|
||||||
l := New(&buf, "", LstdFlags)
|
|
||||||
for i := 0; i < b.N; i++ {
|
|
||||||
buf.Reset()
|
|
||||||
l.Println(testString)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Vendored
-24
@@ -1,24 +0,0 @@
|
|||||||
{
|
|
||||||
"comment": "",
|
|
||||||
"ignore": "test",
|
|
||||||
"package": [
|
|
||||||
{
|
|
||||||
"checksumSHA1": "yRNw/uu/4N7XHVe1PHtKPl6xtDg=",
|
|
||||||
"path": "github.com/Sirupsen/logrus",
|
|
||||||
"revision": "d26492970760ca5d33129d2d799e34be5c4782eb",
|
|
||||||
"revisionTime": "2016-11-03T21:40:07Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"checksumSHA1": "hT+7DPyl8tQ96kUXW3Sr5o0Pcj0=",
|
|
||||||
"path": "gopkg.in/gin-gonic/gin.v1",
|
|
||||||
"revision": "e2212d40c62a98b388a5eb48ecbdcf88534688ba",
|
|
||||||
"revisionTime": "2016-12-04T22:13:08Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"checksumSHA1": "TT9JLp2pZ0u9jpGLA9PW0nM2Xt8=",
|
|
||||||
"path": "log",
|
|
||||||
"revision": ""
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"rootPath": "github.com/wahyd4/say-it-backend"
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user