The Huge Refactoring.

This commit is contained in:
Stanislav Nikitin 2019-03-07 07:56:50 +05:00
parent 0bf20cd2c9
commit 19a3a5004c
No known key found for this signature in database
GPG Key ID: 106900B32F8192EE
101 changed files with 1538 additions and 6164 deletions

24
Gopkg.lock generated
View File

@ -154,15 +154,7 @@
version = "v2.1.0"
[[projects]]
branch = "master"
digest = "1:14fd70f7be0e0296ca808e124d0103a7d932b90468109deb9d02014493f717db"
name = "github.com/pztrn/flagger"
packages = ["."]
pruneopts = "UT"
revision = "1330c5f1b64f253b0505ee4a2417fb8be856b87d"
[[projects]]
digest = "1:9c23180b628a5d254cc7e2c0169013895991ca306b2b183661b25ddaec9dc709"
digest = "1:9be615b2a72fc4a99e623c6776cce3afe3451741c34ea1805ea4a9b58604b9df"
name = "github.com/rs/zerolog"
packages = [
".",
@ -170,8 +162,8 @@
"internal/json",
]
pruneopts = "UT"
revision = "05eafee0eb17d0150591a8f30f0fa592cc9b7471"
version = "v1.6.0"
revision = "6d6350a51143b5c0d0a6a3b736ee2b41315f7269"
version = "v1.12.0"
[[projects]]
branch = "master"
@ -189,6 +181,14 @@
pruneopts = "UT"
revision = "dcecefd839c4193db0d35b88ec65b4c12d360ab0"
[[projects]]
branch = "master"
digest = "1:517b2d010ccd8f6780dacab5ed4d3f9cc8d07e740ecf13da00cd8924d5ca530a"
name = "gitlab.com/pztrn/flagger"
packages = ["."]
pruneopts = "UT"
revision = "d429d7149cc92b7eaa7c98ab3d80b6d5c2e44046"
[[projects]]
branch = "master"
digest = "1:99d34d34b70959a2a8c4a6112dd795c26ab3d546db932a613d1aa13311d83b40"
@ -246,8 +246,8 @@
"github.com/labstack/echo/middleware",
"github.com/lib/pq",
"github.com/pressly/goose",
"github.com/pztrn/flagger",
"github.com/rs/zerolog",
"gitlab.com/pztrn/flagger",
"golang.org/x/crypto/scrypt",
"golang.org/x/net/webdav",
"gopkg.in/yaml.v2",

View File

@ -1,53 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package api
import (
// other
"github.com/labstack/echo"
)
// Logs Echo requests.
func echoReqLog(ec echo.Context, next echo.HandlerFunc) error {
c.Logger.Info().
Str("IP", ec.RealIP()).
Str("Host", ec.Request().Host).
Str("Method", ec.Request().Method).
Str("Path", ec.Request().URL.Path).
Str("UA", ec.Request().UserAgent()).
Msg("HTTP request")
next(ec)
return nil
}
// Wrapper around previous function.
func echoReqLogger() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return echoReqLog(c, next)
}
}
}

View File

@ -1,70 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package api
import (
// local
"gitlab.com/pztrn/fastpastebin/api/http"
"gitlab.com/pztrn/fastpastebin/api/json"
"gitlab.com/pztrn/fastpastebin/context"
// other
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
var (
c *context.Context
e *echo.Echo
)
// New initializes variables for api package.
func New(cc *context.Context) {
c = cc
}
// InitializeAPI initializes HTTP API and starts web server.
func InitializeAPI() {
c.Logger.Info().Msg("Initializing HTTP server...")
e = echo.New()
e.Use(echoReqLogger())
e.Use(middleware.Recover())
e.DisableHTTP2 = true
e.HideBanner = true
e.HidePort = true
c.RegisterEcho(e)
http.New(c)
json.New(c)
listenAddress := c.Config.HTTP.Address + ":" + c.Config.HTTP.Port
go func() {
e.Logger.Fatal(e.Start(listenAddress))
}()
c.Logger.Info().Msgf("Started HTTP server at %s", listenAddress)
}

View File

@ -1,51 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package http
import (
// local
"gitlab.com/pztrn/fastpastebin/api/http/static"
"gitlab.com/pztrn/fastpastebin/context"
// other
"github.com/labstack/echo"
)
var (
c *context.Context
)
// New initializes basic HTTP API, which shows only index page and serves
// static files.
func New(cc *context.Context) {
c = cc
c.Logger.Info().Msg("Initializing HTTP API...")
// Static files.
c.Echo.GET("/static/*", echo.WrapHandler(static.Handler))
// Index.
c.Echo.GET("/", indexGet)
}

View File

@ -1,56 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package http
import (
// stdlib
"net/http"
// local
"gitlab.com/pztrn/fastpastebin/captcha"
"gitlab.com/pztrn/fastpastebin/templater"
// other
"github.com/alecthomas/chroma/lexers"
"github.com/labstack/echo"
)
// Index of this site.
func indexGet(ec echo.Context) error {
// Generate list of available languages to highlight.
availableLexers := lexers.Names(false)
var availableLexersSelectOpts = "<option value='text'>Text</option><option value='autodetect'>Auto detect</option><option disabled>-----</option>"
for i := range availableLexers {
availableLexersSelectOpts += "<option value='" + availableLexers[i] + "'>" + availableLexers[i] + "</option>"
}
// Captcha.
captchaString := captcha.NewCaptcha()
htmlData := templater.GetTemplate(ec, "index.html", map[string]string{"lexers": availableLexersSelectOpts, "captchaString": captchaString})
return ec.HTML(http.StatusOK, htmlData)
}

View File

@ -1,179 +0,0 @@
// Code generated by fileb0x at "2018-12-01 04:46:22.247092221 +0500 +05 m=+0.054271917" from config file "fileb0x.yml" DO NOT EDIT.
// modification hash(732d4e9de83e8a637869d0401ab04cb1.522a9cc525fa984df98098d4c3992752)
package static
import (
"bytes"
"context"
"io"
"net/http"
"os"
"path"
"golang.org/x/net/webdav"
)
var (
// CTX is a context for webdav vfs
CTX = context.Background()
// FS is a virtual memory file system
FS = webdav.NewMemFS()
// Handler is used to server files through a http handler
Handler *webdav.Handler
// HTTP is the http file system
HTTP http.FileSystem = new(HTTPFS)
)
// HTTPFS implements http.FileSystem
type HTTPFS struct {}
func init() {
err := CTX.Err()
if err != nil {
panic(err)
}
err = FS.Mkdir(CTX, "static/", 0777)
if err != nil && err != os.ErrExist {
panic(err)
}
err = FS.Mkdir(CTX, "static/css/", 0777)
if err != nil && err != os.ErrExist {
panic(err)
}
err = FS.Mkdir(CTX, "static/js/", 0777)
if err != nil && err != os.ErrExist {
panic(err)
}
Handler = &webdav.Handler{
FileSystem: FS,
LockSystem: webdav.NewMemLS(),
}
}
// Open a file
func (hfs *HTTPFS) Open(path string) (http.File, error) {
f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
return f, nil
}
// ReadFile is adapTed from ioutil
func ReadFile(path string) ([]byte, error) {
f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
buf := bytes.NewBuffer(make([]byte, 0, bytes.MinRead))
// If the buffer overflows, we will get bytes.ErrTooLarge.
// Return that as an error. Any other panic remains.
defer func() {
e := recover()
if e == nil {
return
}
if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
err = panicErr
} else {
panic(e)
}
}()
_, err = buf.ReadFrom(f)
return buf.Bytes(), err
}
// WriteFile is adapTed from ioutil
func WriteFile(filename string, data []byte, perm os.FileMode) error {
f, err := FS.OpenFile(CTX, filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
n, err := f.Write(data)
if err == nil && n < len(data) {
err = io.ErrShortWrite
}
if err1 := f.Close(); err == nil {
err = err1
}
return err
}
// WalkDirs looks for files in the given dir and returns a list of files in it
// usage for all files in the b0x: WalkDirs("", false)
func WalkDirs(name string, includeDirsInList bool, files ...string) ([]string, error) {
f, err := FS.OpenFile(CTX, name, os.O_RDONLY, 0)
if err != nil {
return nil, err
}
fileInfos, err := f.Readdir(0)
if err != nil {
return nil, err
}
err = f.Close()
if err != nil {
return nil, err
}
for _, info := range fileInfos {
filename := path.Join(name, info.Name())
if includeDirsInList || !info.IsDir() {
files = append(files, filename)
}
if info.IsDir() {
files, err = WalkDirs(filename, includeDirsInList, files...)
if err != nil {
return nil, err
}
}
}
return files, nil
}

View File

@ -1,35 +0,0 @@
// Code generaTed by fileb0x at "2018-12-01 04:46:22.250138933 +0500 +05 m=+0.057318730" from config file "fileb0x.yml" DO NOT EDIT.
// modified(2018-05-26 13:29:04 +0500 +05)
// original path: assets/error.html
package static
import (
"os"
)
// FileErrorHTML is "/error.html"
var FileErrorHTML = []byte("\x3c\x73\x65\x63\x74\x69\x6f\x6e\x20\x63\x6c\x61\x73\x73\x3d\x22\x73\x65\x63\x74\x69\x6f\x6e\x22\x3e\x0a\x20\x20\x20\x20\x3c\x64\x69\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x62\x6f\x78\x20\x68\x61\x73\x2d\x62\x61\x63\x6b\x67\x72\x6f\x75\x6e\x64\x2d\x77\x61\x72\x6e\x69\x6e\x67\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x70\x3e\x7b\x65\x72\x72\x6f\x72\x7d\x3c\x2f\x70\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x64\x69\x76\x3e\x0a\x3c\x2f\x73\x65\x63\x74\x69\x6f\x6e\x3e")
func init() {
f, err := FS.OpenFile(CTX, "/error.html", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FileErrorHTML)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

View File

@ -1,35 +0,0 @@
// Code generaTed by fileb0x at "2018-12-01 04:46:22.250826763 +0500 +05 m=+0.058006583" from config file "fileb0x.yml" DO NOT EDIT.
// modified(2018-12-01 04:46:07.097824889 +0500 +05)
// original path: assets/footer.html
package static
import (
"os"
)
// FileFooterHTML is "/footer.html"
var FileFooterHTML = []byte("\x3c\x64\x69\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x63\x6f\x6e\x74\x61\x69\x6e\x65\x72\x22\x3e\x0a\x20\x20\x20\x20\x3c\x64\x69\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x63\x6f\x6e\x74\x65\x6e\x74\x20\x68\x61\x73\x2d\x74\x65\x78\x74\x2d\x63\x65\x6e\x74\x65\x72\x65\x64\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x70\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x73\x74\x72\x6f\x6e\x67\x3e\x46\x61\x73\x74\x20\x70\x61\x73\x74\x65\x20\x62\x69\x6e\x3c\x2f\x73\x74\x72\x6f\x6e\x67\x3e\x20\x76\x65\x72\x73\x69\x6f\x6e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x73\x74\x72\x6f\x6e\x67\x3e\x7b\x76\x65\x72\x73\x69\x6f\x6e\x7d\x3c\x2f\x73\x74\x72\x6f\x6e\x67\x3e\x20\x62\x79\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x61\x20\x68\x72\x65\x66\x3d\x22\x68\x74\x74\x70\x73\x3a\x2f\x2f\x70\x7a\x74\x72\x6e\x2e\x6e\x61\x6d\x65\x22\x3e\x53\x74\x61\x6e\x69\x73\x6c\x61\x76\x20\x4e\x2e\x20\x61\x6b\x61\x20\x70\x7a\x74\x72\x6e\x3c\x2f\x61\x3e\x2e\x20\x54\x68\x65\x20\x73\x6f\x75\x72\x63\x65\x20\x63\x6f\x64\x65\x20\x69\x73\x20\x6c\x69\x63\x65\x6e\x73\x65\x64\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x61\x20\x68\x72\x65\x66\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x6f\x70\x65\x6e\x73\x6f\x75\x72\x63\x65\x2e\x6f\x72\x67\x2f\x6c\x69\x63\x65\x6e\x73\x65\x73\x2f\x6d\x69\x74\x2d\x6c\x69\x63\x65\x6e\x73\x65\x2e\x70\x68\x70\x22\x3e\x4d\x49\x54\x3c\x2f\x61\x3e\x2e\x20\x47\x65\x74\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x61\x20\x68\x72\x65\x66\x3d\x22\x68\x74\x74\x70\x73\x3a\x2f\x2f\x67\x69\x74\x6c\x61\x62\x2e\x63\x6f\x6d\x2f\x70\x7a\x74\x72\x6e\x2f\x66\x61\x73\x74\x70\x61\x73\x74\x65\x62\x69\x6e\x22\x3e\x73\x6f\x75\x72\x63\x65\x20\x6f\x72\x20\x62\x69\x6e\x61\x72\x79\x20\x72\x65\x6c\x65\x61\x73\x65\x73\x20\x68\x65\x72\x65\x3c\x2f\x61\x3e\x21\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x70\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x64\x69\x76\x3e\x0a\x3c\x2f\x64\x69\x76\x3e")
func init() {
f, err := FS.OpenFile(CTX, "/footer.html", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FileFooterHTML)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,35 +0,0 @@
// Code generaTed by fileb0x at "2018-12-01 04:46:22.257261412 +0500 +05 m=+0.064441445" from config file "fileb0x.yml" DO NOT EDIT.
// modified(2018-05-26 12:41:36 +0500 +05)
// original path: assets/main.html
package static
import (
"os"
)
// FileMainHTML is "/main.html"
var FileMainHTML = []byte("\x3c\x21\x44\x4f\x43\x54\x59\x50\x45\x20\x68\x74\x6d\x6c\x3e\x0a\x3c\x68\x74\x6d\x6c\x3e\x0a\x0a\x3c\x68\x65\x61\x64\x3e\x0a\x20\x20\x20\x20\x3c\x6d\x65\x74\x61\x20\x63\x68\x61\x72\x73\x65\x74\x3d\x22\x75\x74\x66\x2d\x38\x22\x3e\x0a\x20\x20\x20\x20\x3c\x6d\x65\x74\x61\x20\x6e\x61\x6d\x65\x3d\x22\x76\x69\x65\x77\x70\x6f\x72\x74\x22\x20\x63\x6f\x6e\x74\x65\x6e\x74\x3d\x22\x77\x69\x64\x74\x68\x3d\x64\x65\x76\x69\x63\x65\x2d\x77\x69\x64\x74\x68\x2c\x20\x69\x6e\x69\x74\x69\x61\x6c\x2d\x73\x63\x61\x6c\x65\x3d\x31\x22\x3e\x0a\x20\x20\x20\x20\x3c\x74\x69\x74\x6c\x65\x3e\x46\x61\x73\x74\x20\x50\x61\x73\x74\x65\x20\x42\x69\x6e\x3c\x2f\x74\x69\x74\x6c\x65\x3e\x0a\x20\x20\x20\x20\x3c\x6c\x69\x6e\x6b\x20\x72\x65\x6c\x3d\x22\x73\x74\x79\x6c\x65\x73\x68\x65\x65\x74\x22\x20\x68\x72\x65\x66\x3d\x22\x2f\x73\x74\x61\x74\x69\x63\x2f\x63\x73\x73\x2f\x62\x75\x6c\x6d\x61\x2d\x30\x2e\x37\x2e\x30\x2e\x6d\x69\x6e\x2e\x63\x73\x73\x22\x3e\x0a\x20\x20\x20\x20\x3c\x6c\x69\x6e\x6b\x20\x72\x65\x6c\x3d\x22\x73\x74\x79\x6c\x65\x73\x68\x65\x65\x74\x22\x20\x68\x72\x65\x66\x3d\x22\x2f\x73\x74\x61\x74\x69\x63\x2f\x63\x73\x73\x2f\x62\x75\x6c\x6d\x61\x2d\x74\x6f\x6f\x6c\x74\x69\x70\x2d\x31\x2e\x30\x2e\x34\x2e\x6d\x69\x6e\x2e\x63\x73\x73\x22\x3e\x0a\x20\x20\x20\x20\x3c\x6c\x69\x6e\x6b\x20\x72\x65\x6c\x3d\x22\x73\x74\x79\x6c\x65\x73\x68\x65\x65\x74\x22\x20\x68\x72\x65\x66\x3d\x22\x2f\x73\x74\x61\x74\x69\x63\x2f\x63\x73\x73\x2f\x73\x74\x79\x6c\x65\x2e\x63\x73\x73\x22\x3e\x0a\x3c\x2f\x68\x65\x61\x64\x3e\x0a\x0a\x3c\x62\x6f\x64\x79\x3e\x0a\x20\x20\x20\x20\x7b\x6e\x61\x76\x69\x67\x61\x74\x69\x6f\x6e\x7d\x20\x7b\x64\x6f\x63\x75\x6d\x65\x6e\x74\x42\x6f\x64\x79\x7d\x0a\x3c\x2f\x62\x6f\x64\x79\x3e\x0a\x3c\x66\x6f\x6f\x74\x65\x72\x20\x63\x6c\x61\x73\x73\x3d\x22\x66\x6f\x6f\x74\x65\x72\x22\x3e\x0a\x20\x20\x20\x20\x7b\x66\x6f\x6f\x74\x65\x72\x7d\x0a\x3c\x2f\x66\x6f\x6f\x74\x65\x72\x3e\x0a\x0a\x3c\x2f\x68\x74\x6d\x6c\x3e")
func init() {
f, err := FS.OpenFile(CTX, "/main.html", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FileMainHTML)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

View File

@ -1,35 +0,0 @@
// Code generaTed by fileb0x at "2018-12-01 04:46:22.255667749 +0500 +05 m=+0.062847729" from config file "fileb0x.yml" DO NOT EDIT.
// modified(2018-05-26 13:57:14 +0500 +05)
// original path: assets/navigation.html
package static
import (
"os"
)
// FileNavigationHTML is "/navigation.html"
var FileNavigationHTML = []byte("\x3c\x6e\x61\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x6e\x61\x76\x62\x61\x72\x20\x69\x73\x2d\x64\x61\x72\x6b\x22\x3e\x0a\x20\x20\x20\x20\x3c\x64\x69\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x6e\x61\x76\x62\x61\x72\x2d\x62\x72\x61\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x61\x20\x63\x6c\x61\x73\x73\x3d\x22\x6e\x61\x76\x62\x61\x72\x2d\x69\x74\x65\x6d\x22\x20\x68\x72\x65\x66\x3d\x22\x2f\x22\x3e\x46\x61\x73\x74\x20\x50\x61\x73\x74\x65\x20\x42\x69\x6e\x3c\x2f\x61\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x61\x20\x63\x6c\x61\x73\x73\x3d\x22\x6e\x61\x76\x62\x61\x72\x2d\x69\x74\x65\x6d\x22\x20\x68\x72\x65\x66\x3d\x22\x2f\x70\x61\x73\x74\x65\x73\x2f\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x50\x61\x73\x74\x65\x73\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x61\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x64\x69\x76\x3e\x0a\x0a\x20\x20\x20\x20\x3c\x64\x69\x76\x20\x69\x64\x3d\x22\x6e\x61\x76\x62\x61\x72\x49\x74\x65\x6d\x73\x22\x20\x63\x6c\x61\x73\x73\x3d\x22\x6e\x61\x76\x62\x61\x72\x2d\x6d\x65\x6e\x75\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x69\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x6e\x61\x76\x62\x61\x72\x2d\x73\x74\x61\x72\x74\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x64\x69\x76\x3e\x0a\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x69\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x6e\x61\x76\x62\x61\x72\x2d\x65\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x64\x69\x76\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x64\x69\x76\x3e\x0a\x3c\x2f\x6e\x61\x76\x3e")
func init() {
f, err := FS.OpenFile(CTX, "/navigation.html", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FileNavigationHTML)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

View File

@ -1,35 +0,0 @@
// Code generaTed by fileb0x at "2018-05-01 00:41:18.339400139 +0500 +05 m=+0.041230393" from config file "fileb0x.yml" DO NOT EDIT.
// modified(2018-05-01 00:32:51 +0500 +05)
// original path: assets/pagination.html
package static
import (
"os"
)
// FilePaginationHTML is "/pagination.html"
var FilePaginationHTML = []byte("\x3c\x73\x65\x63\x74\x69\x6f\x6e\x20\x63\x6c\x61\x73\x73\x3d\x22\x73\x65\x63\x74\x69\x6f\x6e\x22\x3e\x0a\x20\x20\x20\x20\x3c\x6e\x61\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x70\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x20\x69\x73\x2d\x63\x65\x6e\x74\x65\x72\x65\x64\x22\x20\x72\x6f\x6c\x65\x3d\x22\x6e\x61\x76\x69\x67\x61\x74\x69\x6f\x6e\x22\x20\x61\x72\x69\x61\x2d\x6c\x61\x62\x65\x6c\x3d\x22\x70\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x61\x20\x63\x6c\x61\x73\x73\x3d\x22\x70\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x2d\x70\x72\x65\x76\x69\x6f\x75\x73\x22\x20\x68\x72\x65\x66\x3d\x22\x7b\x70\x72\x65\x76\x69\x6f\x75\x73\x50\x61\x67\x65\x4c\x69\x6e\x6b\x7d\x22\x3e\x50\x72\x65\x76\x69\x6f\x75\x73\x20\x70\x61\x67\x65\x3c\x2f\x61\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x75\x6c\x20\x63\x6c\x61\x73\x73\x3d\x22\x70\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x2d\x6c\x69\x73\x74\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x7b\x70\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x4c\x69\x6e\x6b\x73\x7d\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x75\x6c\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x61\x20\x63\x6c\x61\x73\x73\x3d\x22\x70\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x2d\x6e\x65\x78\x74\x22\x20\x68\x72\x65\x66\x3d\x22\x7b\x6e\x65\x78\x74\x50\x61\x67\x65\x4c\x69\x6e\x6b\x7d\x22\x3e\x4e\x65\x78\x74\x20\x70\x61\x67\x65\x3c\x2f\x61\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x6e\x61\x76\x3e\x0a\x3c\x2f\x73\x65\x63\x74\x69\x6f\x6e\x3e")
func init() {
f, err := FS.OpenFile(CTX, "/pagination.html", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FilePaginationHTML)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

View File

@ -1,35 +0,0 @@
// Code generaTed by fileb0x at "2018-12-01 04:46:22.251496438 +0500 +05 m=+0.058676280" from config file "fileb0x.yml" DO NOT EDIT.
// modified(2018-04-30 23:39:44 +0500 +05)
// original path: assets/pagination_ellipsis.html
package static
import (
"os"
)
// FilePaginationEllipsisHTML is "/pagination_ellipsis.html"
var FilePaginationEllipsisHTML = []byte("\x3c\x6c\x69\x3e\x0a\x20\x20\x20\x20\x3c\x73\x70\x61\x6e\x20\x63\x6c\x61\x73\x73\x3d\x22\x70\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x2d\x65\x6c\x6c\x69\x70\x73\x69\x73\x22\x3e\x26\x68\x65\x6c\x6c\x69\x70\x3b\x3c\x2f\x73\x70\x61\x6e\x3e\x0a\x3c\x2f\x6c\x69\x3e")
func init() {
f, err := FS.OpenFile(CTX, "/pagination_ellipsis.html", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FilePaginationEllipsisHTML)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

View File

@ -1,35 +0,0 @@
// Code generaTed by fileb0x at "2018-05-01 00:26:24.973087795 +0500 +05 m=+0.032533011" from config file "fileb0x.yml" DO NOT EDIT.
// modified(2018-04-30 23:54:11 +0500 +05)
// original path: assets/pagination_link.html
package static
import (
"os"
)
// FilePaginationLinkHTML is "/pagination_link.html"
var FilePaginationLinkHTML = []byte("\x3c\x6c\x69\x3e\x0a\x20\x20\x20\x20\x3c\x61\x20\x63\x6c\x61\x73\x73\x3d\x22\x70\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x2d\x6c\x69\x6e\x6b\x22\x20\x61\x72\x69\x61\x2d\x6c\x61\x62\x65\x6c\x3d\x22\x47\x6f\x20\x74\x6f\x20\x70\x61\x67\x65\x20\x7b\x70\x61\x67\x65\x4e\x75\x6d\x7d\x22\x20\x68\x72\x65\x66\x3d\x22\x7b\x70\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x4c\x69\x6e\x6b\x7d\x22\x3e\x7b\x70\x61\x67\x65\x4e\x75\x6d\x7d\x3c\x2f\x61\x3e\x0a\x3c\x2f\x6c\x69\x3e")
func init() {
f, err := FS.OpenFile(CTX, "/pagination_link.html", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FilePaginationLinkHTML)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

View File

@ -1,35 +0,0 @@
// Code generaTed by fileb0x at "2018-05-01 00:26:24.971847954 +0500 +05 m=+0.031293214" from config file "fileb0x.yml" DO NOT EDIT.
// modified(2018-04-30 23:54:14 +0500 +05)
// original path: assets/pagination_link_current.html
package static
import (
"os"
)
// FilePaginationLinkCurrentHTML is "/pagination_link_current.html"
var FilePaginationLinkCurrentHTML = []byte("\x3c\x6c\x69\x3e\x0a\x20\x20\x20\x20\x3c\x61\x20\x63\x6c\x61\x73\x73\x3d\x22\x70\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x2d\x6c\x69\x6e\x6b\x20\x69\x73\x2d\x63\x75\x72\x72\x65\x6e\x74\x22\x20\x61\x72\x69\x61\x2d\x6c\x61\x62\x65\x6c\x3d\x22\x50\x61\x67\x65\x20\x7b\x70\x61\x67\x65\x4e\x75\x6d\x7d\x22\x20\x61\x72\x69\x61\x2d\x63\x75\x72\x72\x65\x6e\x74\x3d\x22\x70\x61\x67\x65\x22\x3e\x7b\x70\x61\x67\x65\x4e\x75\x6d\x7d\x3c\x2f\x61\x3e\x0a\x3c\x2f\x6c\x69\x3e")
func init() {
f, err := FS.OpenFile(CTX, "/pagination_link_current.html", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FilePaginationLinkCurrentHTML)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,35 +0,0 @@
// Code generaTed by fileb0x at "2018-12-01 04:46:22.254997768 +0500 +05 m=+0.062177726" from config file "fileb0x.yml" DO NOT EDIT.
// modified(2018-05-26 13:24:18 +0500 +05)
// original path: assets/paste.html
package static
import (
"os"
)
// FilePasteHTML is "/paste.html"
var FilePasteHTML = []byte("\x3c\x73\x65\x63\x74\x69\x6f\x6e\x20\x63\x6c\x61\x73\x73\x3d\x22\x73\x65\x63\x74\x69\x6f\x6e\x22\x3e\x0a\x20\x20\x20\x20\x3c\x64\x69\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x63\x6f\x6e\x74\x65\x6e\x74\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x61\x62\x6c\x65\x20\x63\x6c\x61\x73\x73\x3d\x22\x74\x61\x62\x6c\x65\x20\x69\x73\x2d\x62\x6f\x72\x64\x65\x72\x65\x64\x20\x69\x73\x2d\x73\x74\x72\x69\x70\x65\x64\x20\x69\x73\x2d\x6e\x61\x72\x72\x6f\x77\x20\x69\x73\x2d\x68\x6f\x76\x65\x72\x61\x62\x6c\x65\x20\x69\x73\x2d\x66\x75\x6c\x6c\x77\x69\x64\x74\x68\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x68\x65\x61\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x72\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x68\x3e\x23\x3c\x2f\x74\x68\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x68\x3e\x54\x69\x74\x6c\x65\x3c\x2f\x74\x68\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x68\x3e\x4c\x61\x6e\x67\x75\x61\x67\x65\x3c\x2f\x74\x68\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x68\x3e\x50\x61\x73\x74\x65\x64\x20\x6f\x6e\x3c\x2f\x74\x68\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x68\x3e\x57\x69\x6c\x6c\x20\x65\x78\x70\x69\x72\x65\x20\x6f\x6e\x3c\x2f\x74\x68\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x68\x3e\x50\x61\x73\x74\x65\x20\x74\x79\x70\x65\x3c\x2f\x74\x68\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x74\x72\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x74\x68\x65\x61\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x62\x6f\x64\x79\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x72\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x64\x3e\x7b\x70\x61\x73\x74\x65\x49\x44\x7d\x3c\x2f\x74\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x64\x3e\x7b\x70\x61\x73\x74\x65\x54\x69\x74\x6c\x65\x7d\x3c\x2f\x74\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x64\x3e\x7b\x70\x61\x73\x74\x65\x4c\x61\x6e\x67\x75\x61\x67\x65\x7d\x3c\x2f\x74\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x64\x3e\x7b\x70\x61\x73\x74\x65\x44\x61\x74\x65\x7d\x3c\x2f\x74\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x64\x3e\x7b\x70\x61\x73\x74\x65\x45\x78\x70\x69\x72\x61\x74\x69\x6f\x6e\x7d\x3c\x2f\x74\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x64\x3e\x7b\x70\x61\x73\x74\x65\x54\x79\x70\x65\x7d\x3c\x2f\x74\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x74\x72\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x72\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x64\x20\x63\x6f\x6c\x73\x70\x61\x6e\x3d\x22\x36\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x61\x20\x63\x6c\x61\x73\x73\x3d\x22\x62\x75\x74\x74\x6f\x6e\x22\x20\x68\x72\x65\x66\x3d\x22\x2f\x70\x61\x73\x74\x65\x2f\x7b\x70\x61\x73\x74\x65\x49\x44\x7d\x2f\x7b\x70\x61\x73\x74\x65\x54\x73\x7d\x72\x61\x77\x22\x3e\x56\x69\x65\x77\x20\x72\x61\x77\x3c\x2f\x61\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x74\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x74\x72\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x74\x62\x6f\x64\x79\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x74\x61\x62\x6c\x65\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x64\x69\x76\x3e\x0a\x3c\x2f\x73\x65\x63\x74\x69\x6f\x6e\x3e\x0a\x3c\x64\x69\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x70\x61\x73\x74\x65\x2d\x64\x61\x74\x61\x22\x3e\x0a\x20\x20\x20\x20\x7b\x70\x61\x73\x74\x65\x64\x61\x74\x61\x7d\x0a\x3c\x2f\x64\x69\x76\x3e")
func init() {
f, err := FS.OpenFile(CTX, "/paste.html", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FilePasteHTML)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

View File

@ -1,35 +0,0 @@
// Code generaTed by fileb0x at "2018-12-01 04:46:22.253783177 +0500 +05 m=+0.060963095" from config file "fileb0x.yml" DO NOT EDIT.
// modified(2018-05-26 13:41:01 +0500 +05)
// original path: assets/pastelist_list.html
package static
import (
"os"
)
// FilePastelistListHTML is "/pastelist_list.html"
var FilePastelistListHTML = []byte("\x3c\x73\x65\x63\x74\x69\x6f\x6e\x20\x63\x6c\x61\x73\x73\x3d\x22\x73\x65\x63\x74\x69\x6f\x6e\x22\x3e\x0a\x20\x20\x20\x20\x3c\x64\x69\x76\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x7b\x70\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x7d\x0a\x20\x20\x20\x20\x3c\x2f\x64\x69\x76\x3e\x0a\x20\x20\x20\x20\x3c\x64\x69\x76\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x7b\x70\x61\x73\x74\x65\x73\x7d\x0a\x20\x20\x20\x20\x3c\x2f\x64\x69\x76\x3e\x0a\x20\x20\x20\x20\x3c\x64\x69\x76\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x7b\x70\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x7d\x0a\x20\x20\x20\x20\x3c\x2f\x64\x69\x76\x3e\x0a\x3c\x2f\x73\x65\x63\x74\x69\x6f\x6e\x3e")
func init() {
f, err := FS.OpenFile(CTX, "/pastelist_list.html", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FilePastelistListHTML)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

View File

@ -1,35 +0,0 @@
// Code generaTed by fileb0x at "2018-05-01 18:35:23.706057355 +0500 +05 m=+0.051352478" from config file "fileb0x.yml" DO NOT EDIT.
// modified(2018-05-01 18:35:21 +0500 +05)
// original path: assets/pastelist_paste.html
package static
import (
"os"
)
// FilePastelistPasteHTML is "/pastelist_paste.html"
var FilePastelistPasteHTML = []byte("\x3c\x64\x69\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x63\x6f\x6e\x74\x65\x6e\x74\x22\x3e\x0a\x20\x20\x20\x20\x3c\x64\x69\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x63\x61\x72\x64\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x68\x65\x61\x64\x65\x72\x20\x63\x6c\x61\x73\x73\x3d\x22\x63\x61\x72\x64\x2d\x68\x65\x61\x64\x65\x72\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x70\x20\x63\x6c\x61\x73\x73\x3d\x22\x63\x61\x72\x64\x2d\x68\x65\x61\x64\x65\x72\x2d\x74\x69\x74\x6c\x65\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x50\x61\x73\x74\x65\x20\x23\x7b\x70\x61\x73\x74\x65\x49\x44\x7d\x2c\x20\x70\x6f\x73\x74\x65\x64\x20\x6f\x6e\x20\x7b\x70\x61\x73\x74\x65\x44\x61\x74\x65\x7d\x20\x61\x6e\x64\x20\x74\x69\x74\x6c\x65\x64\x20\x61\x73\x20\x22\x7b\x70\x61\x73\x74\x65\x54\x69\x74\x6c\x65\x7d\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x70\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x68\x65\x61\x64\x65\x72\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x69\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x63\x61\x72\x64\x2d\x63\x6f\x6e\x74\x65\x6e\x74\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x69\x76\x20\x63\x6c\x61\x73\x73\x3d\x22\x63\x6f\x6e\x74\x65\x6e\x74\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x70\x72\x65\x3e\x7b\x70\x61\x73\x74\x65\x44\x61\x74\x61\x7d\x3c\x2f\x70\x72\x65\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x64\x69\x76\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x64\x69\x76\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x66\x6f\x6f\x74\x65\x72\x20\x63\x6c\x61\x73\x73\x3d\x22\x63\x61\x72\x64\x2d\x66\x6f\x6f\x74\x65\x72\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x61\x20\x68\x72\x65\x66\x3d\x22\x2f\x70\x61\x73\x74\x65\x2f\x7b\x70\x61\x73\x74\x65\x49\x44\x7d\x22\x20\x63\x6c\x61\x73\x73\x3d\x22\x63\x61\x72\x64\x2d\x66\x6f\x6f\x74\x65\x72\x2d\x69\x74\x65\x6d\x20\x62\x75\x74\x74\x6f\x6e\x20\x69\x73\x2d\x73\x75\x63\x63\x65\x73\x73\x20\x69\x73\x2d\x72\x61\x64\x69\x75\x73\x6c\x65\x73\x73\x22\x3e\x56\x69\x65\x77\x3c\x2f\x61\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x66\x6f\x6f\x74\x65\x72\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x64\x69\x76\x3e\x0a\x3c\x2f\x64\x69\x76\x3e")
func init() {
f, err := FS.OpenFile(CTX, "/pastelist_paste.html", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FilePastelistPasteHTML)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,35 +0,0 @@
// Code generaTed by fileb0x at "2018-12-01 04:46:22.253116711 +0500 +05 m=+0.060296607" from config file "fileb0x.yml" DO NOT EDIT.
// modified(2018-05-01 17:43:40 +0500 +05)
// original path: assets/css/style.css
package static
import (
"os"
)
// FileStaticCSSStyleCSS is "static/css/style.css"
var FileStaticCSSStyleCSS = []byte("\x23\x70\x61\x73\x74\x65\x2d\x63\x6f\x6e\x74\x65\x6e\x74\x73\x20\x7b\x0a\x20\x20\x20\x20\x66\x6f\x6e\x74\x2d\x66\x61\x6d\x69\x6c\x79\x3a\x20\x6d\x6f\x6e\x6f\x73\x70\x61\x63\x65\x3b\x0a\x20\x20\x20\x20\x66\x6f\x6e\x74\x2d\x73\x69\x7a\x65\x3a\x20\x30\x2e\x39\x72\x65\x6d\x3b\x0a\x20\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3a\x20\x39\x30\x76\x68\x3b\x0a\x7d\x0a\x0a\x2e\x70\x61\x73\x74\x65\x2d\x64\x61\x74\x61\x20\x7b\x0a\x20\x20\x20\x20\x66\x6f\x6e\x74\x2d\x73\x69\x7a\x65\x3a\x20\x30\x2e\x39\x72\x65\x6d\x3b\x0a\x7d")
func init() {
f, err := FS.OpenFile(CTX, "static/css/style.css", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
panic(err)
}
_, err = f.Write(FileStaticCSSStyleCSS)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,40 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package json
import (
// local
"gitlab.com/pztrn/fastpastebin/context"
)
var (
c *context.Context
)
// New initializes basic JSON API.
func New(cc *context.Context) {
c = cc
c.Logger.Info().Msg("Initializing JSON API...")
}

View File

@ -1,59 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package captcha
import (
// local
"gitlab.com/pztrn/fastpastebin/context"
// other
"github.com/dchest/captcha"
"github.com/labstack/echo"
)
var (
c *context.Context
)
// New initializes captcha package and adds neccessary HTTP and API
// endpoints.
func New(cc *context.Context) {
c = cc
// New paste.
c.Echo.GET("/captcha/:id.png", echo.WrapHandler(captcha.Server(captcha.StdWidth, captcha.StdHeight)))
}
// NewCaptcha creates new captcha string.
func NewCaptcha() string {
s := captcha.New()
c.Logger.Debug().Msgf("Created new captcha string: %s", s)
return s
}
// Verify verifies captchas.
func Verify(captchaString string, captchaSolution string) bool {
return captcha.VerifyString(captchaString, captchaSolution)
}

View File

@ -31,12 +31,12 @@ import (
"syscall"
// local
"gitlab.com/pztrn/fastpastebin/api"
"gitlab.com/pztrn/fastpastebin/captcha"
"gitlab.com/pztrn/fastpastebin/context"
"gitlab.com/pztrn/fastpastebin/database"
"gitlab.com/pztrn/fastpastebin/pastes"
"gitlab.com/pztrn/fastpastebin/templater"
"gitlab.com/pztrn/fastpastebin/domains/indexpage"
"gitlab.com/pztrn/fastpastebin/domains/pastes"
"gitlab.com/pztrn/fastpastebin/internal/captcha"
"gitlab.com/pztrn/fastpastebin/internal/context"
"gitlab.com/pztrn/fastpastebin/internal/database"
"gitlab.com/pztrn/fastpastebin/internal/templater"
)
func main() {
@ -53,13 +53,14 @@ func main() {
// Continue loading.
c.LoadConfiguration()
c.InitializePost()
database.New(c)
c.Database.Initialize()
templater.Initialize(c)
api.New(c)
api.InitializeAPI()
captcha.New(c)
indexpage.New(c)
pastes.New(c)
// CTRL+C handler.

View File

@ -1,36 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package config
// ConfigDatabase describes database configuration.
type ConfigDatabase struct {
Type string `yaml:"type"`
Path string `yaml:"path"`
Address string `yaml:"address"`
Port string `yaml:"port"`
Username string `yaml:"username"`
Password string `yaml:"password"`
Database string `yaml:"database"`
}

View File

@ -1,32 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package config
// ConfigHTTP describes HTTP server configuration.
type ConfigHTTP struct {
Address string `yaml:"address"`
Port string `yaml:"port"`
AllowInsecure bool `yaml:"allow_insecure"`
}

View File

@ -1,32 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package config
// ConfigLogging describes logger configuration.
type ConfigLogging struct {
LogToFile bool `yaml:"log_to_file"`
FileName string `yaml:"filename"`
LogLevel string `yaml:"loglevel"`
}

View File

@ -1,30 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package config
// ConfigPastes describes pastes subsystem configuration.
type ConfigPastes struct {
Pagination int `yaml:"pagination"`
}

View File

@ -1,33 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package config
// ConfigStruct describes whole configuration.
type ConfigStruct struct {
Database ConfigDatabase `yaml:"database"`
Logging ConfigLogging `yaml:"logging"`
HTTP ConfigHTTP `yaml:"http"`
Pastes ConfigPastes `yaml:"pastes"`
}

View File

@ -1,151 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package context
import (
// stdlib
"io/ioutil"
"os"
"path/filepath"
// local
"gitlab.com/pztrn/fastpastebin/config"
"gitlab.com/pztrn/fastpastebin/database/interface"
// other
"github.com/labstack/echo"
"github.com/pztrn/flagger"
"github.com/rs/zerolog"
"gopkg.in/yaml.v2"
)
// Context is a some sort of singleton. Basically it's a structure that
// initialized once and then passed to all parts of application. It
// contains everything every part of application need, like configuration
// access, logger, etc.
type Context struct {
Config *config.ConfigStruct
Database databaseinterface.Interface
Echo *echo.Echo
Flagger *flagger.Flagger
Logger zerolog.Logger
}
// Initialize initializes context.
func (c *Context) Initialize() {
c.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger()
c.Flagger = flagger.New(nil)
c.Flagger.Initialize()
c.Flagger.AddFlag(&flagger.Flag{
Name: "config",
Description: "Configuration file path. Can be overridded with FASTPASTEBIN_CONFIG environment variable (this is what used in tests).",
Type: "string",
DefaultValue: "NO_CONFIG",
})
}
// LoadConfiguration loads configuration and executes right after Flagger
// have parsed CLI flags, because it depends on "-config" defined in
// Initialize().
func (c *Context) LoadConfiguration() {
c.Logger.Info().Msg("Loading configuration...")
var configPath = ""
// We're accepting configuration path from "-config" CLI parameter
// and FASTPASTEBIN_CONFIG environment variable. Later have higher
// weight and can override "-config" value.
configPathFromCLI, err := c.Flagger.GetStringValue("config")
configPathFromEnv, configPathFromEnvFound := os.LookupEnv("FASTPASTEBIN_CONFIG")
if err != nil && configPathFromEnvFound || err == nil && configPathFromEnvFound {
configPath = configPathFromEnv
} else if err != nil && !configPathFromEnvFound || err == nil && configPathFromCLI == "NO_CONFIG" {
c.Logger.Panic().Msg("Configuration file path wasn't passed via '-config' or 'FASTPASTEBIN_CONFIG' environment variable. Cannot continue.")
} else if err == nil && !configPathFromEnvFound {
configPath = configPathFromCLI
}
// Normalize file path.
normalizedConfigPath, err1 := filepath.Abs(configPath)
if err1 != nil {
c.Logger.Fatal().Msgf("Failed to normalize path to configuration file: %s", err1.Error())
}
c.Logger.Debug().Msgf("Configuration file path: %s", configPath)
c.Config = &config.ConfigStruct{}
// Read configuration file.
fileData, err2 := ioutil.ReadFile(normalizedConfigPath)
if err2 != nil {
c.Logger.Panic().Msgf("Failed to read configuration file: %s", err2.Error())
}
// Parse it into structure.
err3 := yaml.Unmarshal(fileData, c.Config)
if err3 != nil {
c.Logger.Panic().Msgf("Failed to parse configuration file: %s", err3.Error())
}
// Yay! See what it gets!
c.Logger.Debug().Msgf("Parsed configuration: %+v", c.Config)
// Set log level.
c.Logger.Info().Msgf("Setting logger level: %s", c.Config.Logging.LogLevel)
switch c.Config.Logging.LogLevel {
case "DEBUG":
zerolog.SetGlobalLevel(zerolog.DebugLevel)
case "INFO":
zerolog.SetGlobalLevel(zerolog.InfoLevel)
case "WARN":
zerolog.SetGlobalLevel(zerolog.WarnLevel)
case "ERROR":
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
case "FATAL":
zerolog.SetGlobalLevel(zerolog.FatalLevel)
case "PANIC":
zerolog.SetGlobalLevel(zerolog.PanicLevel)
}
}
// RegisterDatabaseInterface registers database interface for later use.
func (c *Context) RegisterDatabaseInterface(di databaseinterface.Interface) {
c.Database = di
}
// RegisterEcho registers Echo instance for later usage.
func (c *Context) RegisterEcho(e *echo.Echo) {
c.Echo = e
}
// Shutdown shutdowns entire application.
func (c *Context) Shutdown() {
c.Logger.Info().Msg("Shutting down Fast Pastebin...")
c.Database.Shutdown()
}

View File

@ -1,35 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package context
const (
// Version .
Version = "0.2.1"
)
// New creates new context.
func New() *Context {
return &Context{}
}

View File

@ -1,93 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package database
import (
// stdlib
"database/sql"
// local
"gitlab.com/pztrn/fastpastebin/database/dialects/flatfiles"
"gitlab.com/pztrn/fastpastebin/database/dialects/interface"
"gitlab.com/pztrn/fastpastebin/database/dialects/mysql"
"gitlab.com/pztrn/fastpastebin/database/dialects/postgresql"
"gitlab.com/pztrn/fastpastebin/pastes/model"
// other
_ "github.com/go-sql-driver/mysql"
)
// Database represents control structure for database connection.
type Database struct {
db dialectinterface.Interface
}
func (db *Database) GetDatabaseConnection() *sql.DB {
if db.db != nil {
return db.db.GetDatabaseConnection()
}
return nil
}
func (db *Database) GetPaste(pasteID int) (*pastesmodel.Paste, error) {
return db.db.GetPaste(pasteID)
}
func (db *Database) GetPagedPastes(page int) ([]pastesmodel.Paste, error) {
return db.db.GetPagedPastes(page)
}
func (db *Database) GetPastesPages() int {
return db.db.GetPastesPages()
}
// Initialize initializes connection to database.
func (db *Database) Initialize() {
c.Logger.Info().Msg("Initializing database connection...")
if c.Config.Database.Type == "mysql" {
mysql.New(c)
} else if c.Config.Database.Type == "flatfiles" {
flatfiles.New(c)
} else if c.Config.Database.Type == "postgresql" {
postgresql.New(c)
} else {
c.Logger.Fatal().Msgf("Unknown database type: %s", c.Config.Database.Type)
}
}
func (db *Database) RegisterDialect(di dialectinterface.Interface) {
db.db = di
db.db.Initialize()
}
func (db *Database) SavePaste(p *pastesmodel.Paste) (int64, error) {
return db.db.SavePaste(p)
}
func (db *Database) Shutdown() {
db.db.Shutdown()
}

View File

@ -1,42 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package flatfiles
import (
// local
"gitlab.com/pztrn/fastpastebin/context"
"gitlab.com/pztrn/fastpastebin/database/dialects/interface"
)
var (
c *context.Context
f *FlatFiles
)
func New(cc *context.Context) {
c = cc
f = &FlatFiles{}
c.Database.RegisterDialect(dialectinterface.Interface(Handler{}))
}

View File

@ -1,246 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package flatfiles
import (
// stdlib
"database/sql"
"encoding/json"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"strconv"
"strings"
"sync"
// local
"gitlab.com/pztrn/fastpastebin/pastes/model"
)
type FlatFiles struct {
pastesIndex []*Index
path string
writeMutex sync.Mutex
}
func (ff *FlatFiles) GetDatabaseConnection() *sql.DB {
return nil
}
func (ff *FlatFiles) GetPaste(pasteID int) (*pastesmodel.Paste, error) {
ff.writeMutex.Lock()
pastePath := filepath.Join(ff.path, "pastes", strconv.Itoa(pasteID)+".json")
c.Logger.Debug().Msgf("Trying to load paste data from '%s'...", pastePath)
pasteInBytes, err := ioutil.ReadFile(pastePath)
if err != nil {
c.Logger.Debug().Msgf("Failed to read paste from storage: %s", err.Error())
return nil, err
}
c.Logger.Debug().Msgf("Loaded %d bytes: %s", len(pasteInBytes), string(pasteInBytes))
ff.writeMutex.Unlock()
paste := &pastesmodel.Paste{}
err = json.Unmarshal(pasteInBytes, paste)
if err != nil {
c.Logger.Error().Msgf("Failed to parse paste: %s", err.Error())
return nil, err
}
return paste, nil
}
func (ff *FlatFiles) GetPagedPastes(page int) ([]pastesmodel.Paste, error) {
// Pagination.
var startPagination = 0
if page > 1 {
startPagination = (page - 1) * c.Config.Pastes.Pagination
}
c.Logger.Debug().Msgf("Pastes index: %+v", ff.pastesIndex)
// Iteration one - get only public pastes.
var publicPastes []*Index
for _, paste := range ff.pastesIndex {
if !paste.Private {
publicPastes = append(publicPastes, paste)
}
}
c.Logger.Debug().Msgf("%+v", publicPastes)
// Iteration two - get paginated pastes.
var pastesData []pastesmodel.Paste
for idx, paste := range publicPastes {
if len(pastesData) == c.Config.Pastes.Pagination {
break
}
if idx < startPagination {
c.Logger.Debug().Msgf("Paste with index %d isn't in pagination query: too low index", idx)
continue
}
if (idx-1 >= startPagination && page > 1 && idx > startPagination+((page-1)*c.Config.Pastes.Pagination)) || (idx-1 >= startPagination && page == 1 && idx > startPagination+(page*c.Config.Pastes.Pagination)) {
c.Logger.Debug().Msgf("Paste with index %d isn't in pagination query: too high index", idx)
break
}
c.Logger.Debug().Msgf("Getting paste data (ID: %d, index: %d)", paste.ID, idx)
// Get paste data.
pasteData := &pastesmodel.Paste{}
pasteRawData, err := ioutil.ReadFile(filepath.Join(ff.path, "pastes", strconv.Itoa(paste.ID)+".json"))
if err != nil {
c.Logger.Error().Msgf("Failed to read paste data: %s", err.Error())
continue
}
err = json.Unmarshal(pasteRawData, pasteData)
if err != nil {
c.Logger.Error().Msgf("Failed to parse paste data: %s", err.Error())
continue
}
pastesData = append(pastesData, (*pasteData))
}
return pastesData, nil
}
func (ff *FlatFiles) GetPastesPages() int {
// Get public pastes count.
var publicPastes []*Index
ff.writeMutex.Lock()
for _, paste := range ff.pastesIndex {
if !paste.Private {
publicPastes = append(publicPastes, paste)
}
}
ff.writeMutex.Unlock()
// Calculate pages.
pages := len(publicPastes) / c.Config.Pastes.Pagination
// Check if we have any remainder. Add 1 to pages count if so.
if len(publicPastes)%c.Config.Pastes.Pagination > 0 {
pages++
}
return pages
}
func (ff *FlatFiles) Initialize() {
c.Logger.Info().Msg("Initializing flatfiles storage...")
path := c.Config.Database.Path
// Get proper paste file path.
if strings.Contains(c.Config.Database.Path, "~") {
curUser, err := user.Current()
if err != nil {
c.Logger.Error().Msg("Failed to get current user. Will replace '~' for '/' in storage path!")
path = strings.Replace(path, "~", "/", -1)
}
path = strings.Replace(path, "~", curUser.HomeDir, -1)
}
path, _ = filepath.Abs(path)
ff.path = path
c.Logger.Debug().Msgf("Storage path is now: %s", ff.path)
// Create directory if neccessary.
if _, err := os.Stat(ff.path); err != nil {
c.Logger.Debug().Msgf("Directory '%s' does not exist, creating...", ff.path)
os.MkdirAll(ff.path, os.ModePerm)
} else {
c.Logger.Debug().Msgf("Directory '%s' already exists", ff.path)
}
// Create directory for pastes.
if _, err := os.Stat(filepath.Join(ff.path, "pastes")); err != nil {
c.Logger.Debug().Msgf("Directory '%s' does not exist, creating...", filepath.Join(ff.path, "pastes"))
os.MkdirAll(filepath.Join(ff.path, "pastes"), os.ModePerm)
} else {
c.Logger.Debug().Msgf("Directory '%s' already exists", filepath.Join(ff.path, "pastes"))
}
// Load pastes index.
ff.pastesIndex = []*Index{}
if _, err := os.Stat(filepath.Join(ff.path, "pastes", "index.json")); err != nil {
c.Logger.Warn().Msg("Pastes index file does not exist, will create new one")
} else {
indexData, err := ioutil.ReadFile(filepath.Join(ff.path, "pastes", "index.json"))
if err != nil {
c.Logger.Fatal().Msg("Failed to read contents of index file!")
}
err = json.Unmarshal(indexData, &ff.pastesIndex)
if err != nil {
c.Logger.Error().Msgf("Failed to parse index file contents from JSON into internal structure. Will create new index file. All of your previous pastes will became unavailable. Error was: %s", err.Error())
}
c.Logger.Debug().Msgf("Parsed pastes index: %+v", ff.pastesIndex)
}
}
func (ff *FlatFiles) SavePaste(p *pastesmodel.Paste) (int64, error) {
ff.writeMutex.Lock()
// Write paste data on disk.
filesOnDisk, _ := ioutil.ReadDir(filepath.Join(ff.path, "pastes"))
pasteID := len(filesOnDisk) + 1
c.Logger.Debug().Msgf("Writing paste to disk, ID will be " + strconv.Itoa(pasteID))
p.ID = pasteID
data, err := json.Marshal(p)
if err != nil {
ff.writeMutex.Unlock()
return 0, err
}
err = ioutil.WriteFile(filepath.Join(ff.path, "pastes", strconv.Itoa(pasteID)+".json"), data, 0644)
if err != nil {
ff.writeMutex.Unlock()
return 0, err
}
// Add it to cache.
indexData := &Index{}
indexData.ID = pasteID
indexData.Private = p.Private
ff.pastesIndex = append(ff.pastesIndex, indexData)
ff.writeMutex.Unlock()
return int64(pasteID), nil
}
func (ff *FlatFiles) Shutdown() {
c.Logger.Info().Msg("Saving indexes...")
indexData, err := json.Marshal(ff.pastesIndex)
if err != nil {
c.Logger.Error().Msgf("Failed to encode index data into JSON: %s", err.Error())
return
}
err = ioutil.WriteFile(filepath.Join(ff.path, "pastes", "index.json"), indexData, 0644)
if err != nil {
c.Logger.Error().Msgf("Failed to write index data to file. Pretty sure that you've lost your pastes.")
return
}
}

View File

@ -1,63 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package flatfiles
import (
// stdlib
"database/sql"
// local
"gitlab.com/pztrn/fastpastebin/pastes/model"
)
type Handler struct{}
func (dbh Handler) GetDatabaseConnection() *sql.DB {
return f.GetDatabaseConnection()
}
func (dbh Handler) GetPaste(pasteID int) (*pastesmodel.Paste, error) {
return f.GetPaste(pasteID)
}
func (dbh Handler) GetPagedPastes(page int) ([]pastesmodel.Paste, error) {
return f.GetPagedPastes(page)
}
func (dbh Handler) GetPastesPages() int {
return f.GetPastesPages()
}
func (dbh Handler) Initialize() {
f.Initialize()
}
func (dbh Handler) SavePaste(p *pastesmodel.Paste) (int64, error) {
return f.SavePaste(p)
}
func (dbh Handler) Shutdown() {
f.Shutdown()
}

View File

@ -1,31 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package flatfiles
// Index describes paste index structure for flatfiles data storage.
type Index struct {
ID int `yaml:"id"`
Private bool `json:"private"`
}

View File

@ -1,43 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package dialectinterface
import (
// stdlib
"database/sql"
// local
"gitlab.com/pztrn/fastpastebin/pastes/model"
)
type Interface interface {
GetDatabaseConnection() *sql.DB
GetPaste(pasteID int) (*pastesmodel.Paste, error)
GetPagedPastes(page int) ([]pastesmodel.Paste, error)
GetPastesPages() int
Initialize()
SavePaste(p *pastesmodel.Paste) (int64, error)
Shutdown()
}

View File

@ -1,42 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package mysql
import (
// local
"gitlab.com/pztrn/fastpastebin/context"
"gitlab.com/pztrn/fastpastebin/database/dialects/interface"
)
var (
c *context.Context
d *Database
)
func New(cc *context.Context) {
c = cc
d = &Database{}
c.Database.RegisterDialect(dialectinterface.Interface(Handler{}))
}

View File

@ -1,63 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package mysql
import (
// stdlib
"database/sql"
// local
"gitlab.com/pztrn/fastpastebin/pastes/model"
)
type Handler struct{}
func (dbh Handler) GetDatabaseConnection() *sql.DB {
return d.GetDatabaseConnection()
}
func (dbh Handler) GetPaste(pasteID int) (*pastesmodel.Paste, error) {
return d.GetPaste(pasteID)
}
func (dbh Handler) GetPagedPastes(page int) ([]pastesmodel.Paste, error) {
return d.GetPagedPastes(page)
}
func (dbh Handler) GetPastesPages() int {
return d.GetPastesPages()
}
func (dbh Handler) Initialize() {
d.Initialize()
}
func (dbh Handler) SavePaste(p *pastesmodel.Paste) (int64, error) {
return d.SavePaste(p)
}
func (dbh Handler) Shutdown() {
d.Shutdown()
}

View File

@ -1,39 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package migrations
import (
// stdlib
"database/sql"
)
func InitialUp(tx *sql.Tx) error {
_, err := tx.Exec("CREATE TABLE `pastes` (`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Paste ID', `title` text NOT NULL COMMENT 'Paste title', `data` longtext NOT NULL COMMENT 'Paste data', `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Paste creation timestamp', `keep_for` int(4) NOT NULL DEFAULT 1 COMMENT 'Keep for integer. 0 - forever.', `keep_for_unit_type` int(1) NOT NULL DEFAULT 1 COMMENT 'Keep for unit type. 1 - minutes, 2 - hours, 3 - days, 4 - months.', PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='Pastes';")
if err != nil {
return err
}
return nil
}

View File

@ -1,48 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package migrations
import (
// stdlib
"database/sql"
)
func PasteLangUp(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE `pastes` ADD `language` VARCHAR(191) NOT NULL DEFAULT 'text' COMMENT 'Paste language'")
if err != nil {
return err
}
return nil
}
func PasteLangDown(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE `pastes` DROP COLUMN `language`")
if err != nil {
return err
}
return nil
}

View File

@ -1,48 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package migrations
import (
// stdlib
"database/sql"
)
func PrivatePastesUp(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE `pastes` ADD `private` BOOL NOT NULL DEFAULT false COMMENT 'Private paste? If true - additional URL parameter (UNIX TIMESTAMP) of paste will be required to access.'")
if err != nil {
return err
}
return nil
}
func PrivatePastesDown(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE `pastes` DROP COLUMN `private`")
if err != nil {
return err
}
return nil
}

View File

@ -1,58 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package migrations
import (
// stdlib
"database/sql"
)
func PasswordedPastesUp(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE `pastes` ADD `password` varchar(64) NOT NULL DEFAULT '' COMMENT 'Password for paste (scrypted and sha256ed).'")
if err != nil {
return err
}
_, err1 := tx.Exec("ALTER TABLE `pastes` ADD `password_salt` varchar(64) NOT NULL DEFAULT '' COMMENT 'Password salt (sha256ed).'")
if err1 != nil {
return err1
}
return nil
}
func PasswordedPastesDown(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE `pastes` DROP COLUMN `password`")
if err != nil {
return err
}
_, err1 := tx.Exec("ALTER TABLE `pastes` DROP COLUMN `password_salt`")
if err1 != nil {
return err1
}
return nil
}

View File

@ -1,65 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package migrations
import (
// local
"gitlab.com/pztrn/fastpastebin/context"
// other
//"gitlab.com/jmoiron/sqlx"
"github.com/pressly/goose"
)
var (
c *context.Context
)
// New initializes migrations.
func New(cc *context.Context) {
c = cc
}
// Migrate launching migrations.
func Migrate() {
c.Logger.Info().Msg("Migrating database...")
goose.SetDialect("mysql")
goose.AddNamedMigration("1_initial.go", InitialUp, nil)
goose.AddNamedMigration("2_paste_lang.go", PasteLangUp, PasteLangDown)
goose.AddNamedMigration("3_private_pastes.go", PrivatePastesUp, PrivatePastesDown)
goose.AddNamedMigration("4_passworded_pastes.go", PasswordedPastesUp, PasswordedPastesDown)
// Add new migrations BEFORE this message.
dbConn := c.Database.GetDatabaseConnection()
if dbConn != nil {
err := goose.Up(dbConn, ".")
if err != nil {
c.Logger.Panic().Msgf("Failed to migrate database to latest version: %s", err.Error())
}
} else {
c.Logger.Warn().Msg("Current database dialect isn't supporting migrations, skipping")
}
}

View File

@ -1,175 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package mysql
import (
// stdlib
"database/sql"
"fmt"
// local
"gitlab.com/pztrn/fastpastebin/database/dialects/mysql/migrations"
"gitlab.com/pztrn/fastpastebin/pastes/model"
// other
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
// Database is a MySQL/MariaDB connection controlling structure.
type Database struct {
db *sqlx.DB
}
// Checks if queries can be run on known connection and reestablish it
// if not.
func (db *Database) check() {
_, err := db.db.Exec("SELECT 1")
if err != nil {
db.Initialize()
}
}
func (db *Database) GetDatabaseConnection() *sql.DB {
db.check()
return db.db.DB
}
// GetPaste returns a single paste by ID.
func (db *Database) GetPaste(pasteID int) (*pastesmodel.Paste, error) {
db.check()
p := &pastesmodel.Paste{}
err := db.db.Get(p, db.db.Rebind("SELECT * FROM `pastes` WHERE id=?"), pasteID)
if err != nil {
return nil, err
}
return p, nil
}
func (db *Database) GetPagedPastes(page int) ([]pastesmodel.Paste, error) {
db.check()
var pastesRaw []pastesmodel.Paste
var pastes []pastesmodel.Paste
// Pagination.
var startPagination = 0
if page > 1 {
startPagination = (page - 1) * c.Config.Pastes.Pagination
}
err := db.db.Select(&pastesRaw, db.db.Rebind("SELECT * FROM `pastes` WHERE private != true ORDER BY id DESC LIMIT ? OFFSET ?"), c.Config.Pastes.Pagination, startPagination)
if err != nil {
return nil, err
}
for i := range pastesRaw {
if !pastesRaw[i].IsExpired() {
pastes = append(pastes, pastesRaw[i])
}
}
return pastes, nil
}
func (db *Database) GetPastesPages() int {
db.check()
var pastesRaw []pastesmodel.Paste
var pastes []pastesmodel.Paste
err := db.db.Get(&pastesRaw, "SELECT * FROM `pastes` WHERE private != true")
if err != nil {
return 1
}
// Check if pastes isn't expired.
for i := range pastesRaw {
if !pastesRaw[i].IsExpired() {
pastes = append(pastes, pastesRaw[i])
}
}
// Calculate pages.
pages := len(pastes) / c.Config.Pastes.Pagination
// Check if we have any remainder. Add 1 to pages count if so.
if len(pastes)%c.Config.Pastes.Pagination > 0 {
pages++
}
return pages
}
// Initialize initializes MySQL/MariaDB connection.
func (db *Database) Initialize() {
c.Logger.Info().Msg("Initializing database connection...")
// There might be only user, without password. MySQL/MariaDB driver
// in DSN wants "user" or "user:password", "user:" is invalid.
var userpass = ""
if c.Config.Database.Password == "" {
userpass = c.Config.Database.Username
} else {
userpass = c.Config.Database.Username + ":" + c.Config.Database.Password
}
dbConnString := fmt.Sprintf("%s@tcp(%s:%s)/%s?parseTime=true&collation=utf8mb4_unicode_ci&charset=utf8mb4", userpass, c.Config.Database.Address, c.Config.Database.Port, c.Config.Database.Database)
c.Logger.Debug().Msgf("Database connection string: %s", dbConnString)
dbConn, err := sqlx.Connect("mysql", dbConnString)
if err != nil {
c.Logger.Panic().Msgf("Failed to connect to database: %s", err.Error())
}
// Force UTC for current connection.
_ = dbConn.MustExec("SET @@session.time_zone='+00:00';")
c.Logger.Info().Msg("Database connection established")
db.db = dbConn
// Perform migrations.
migrations.New(c)
migrations.Migrate()
}
func (db *Database) SavePaste(p *pastesmodel.Paste) (int64, error) {
db.check()
result, err := db.db.NamedExec("INSERT INTO `pastes` (title, data, created_at, keep_for, keep_for_unit_type, language, private, password, password_salt) VALUES (:title, :data, :created_at, :keep_for, :keep_for_unit_type, :language, :private, :password, :password_salt)", p)
if err != nil {
return 0, err
}
ID, err1 := result.LastInsertId()
if err1 != nil {
return 0, err
}
return ID, nil
}
func (db *Database) Shutdown() {
err := db.db.Close()
if err != nil {
c.Logger.Error().Msgf("Failed to close database connection: %s", err.Error())
}
}

View File

@ -1,42 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package postgresql
import (
// local
"gitlab.com/pztrn/fastpastebin/context"
"gitlab.com/pztrn/fastpastebin/database/dialects/interface"
)
var (
c *context.Context
d *Database
)
func New(cc *context.Context) {
c = cc
d = &Database{}
c.Database.RegisterDialect(dialectinterface.Interface(Handler{}))
}

View File

@ -1,63 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package postgresql
import (
// stdlib
"database/sql"
// local
"gitlab.com/pztrn/fastpastebin/pastes/model"
)
type Handler struct{}
func (dbh Handler) GetDatabaseConnection() *sql.DB {
return d.GetDatabaseConnection()
}
func (dbh Handler) GetPaste(pasteID int) (*pastesmodel.Paste, error) {
return d.GetPaste(pasteID)
}
func (dbh Handler) GetPagedPastes(page int) ([]pastesmodel.Paste, error) {
return d.GetPagedPastes(page)
}
func (dbh Handler) GetPastesPages() int {
return d.GetPastesPages()
}
func (dbh Handler) Initialize() {
d.Initialize()
}
func (dbh Handler) SavePaste(p *pastesmodel.Paste) (int64, error) {
return d.SavePaste(p)
}
func (dbh Handler) Shutdown() {
d.Shutdown()
}

View File

@ -1,56 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package migrations
import (
// stdlib
"database/sql"
)
func InitialUp(tx *sql.Tx) error {
_, err := tx.Exec(`
CREATE TABLE pastes
(
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
data TEXT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
keep_for INTEGER NOT NULL DEFAULT 1,
keep_for_unit_type SMALLINT NOT NULL DEFAULT 1
);
COMMENT ON COLUMN pastes.id IS 'Paste ID';
COMMENT ON COLUMN pastes.title IS 'Paste title';
COMMENT ON COLUMN pastes.data IS 'Paste data';
COMMENT ON COLUMN pastes.created_at IS 'Paste creation timestamp';
COMMENT ON COLUMN pastes.keep_for IS 'Keep for integer. 0 - forever.';
COMMENT ON COLUMN pastes.keep_for_unit_type IS 'Keep for unit type. 0 - forever, 1 - minutes, 2 - hours, 3 - days, 4 - months.';
`)
if err != nil {
return err
}
return nil
}

View File

@ -1,48 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package migrations
import (
// stdlib
"database/sql"
)
func PasteLangUp(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE pastes ADD COLUMN language VARCHAR(191) NOT NULL DEFAULT 'text'; COMMENT ON COLUMN pastes.language IS 'Paste language';")
if err != nil {
return err
}
return nil
}
func PasteLangDown(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE pastes DROP COLUMN language")
if err != nil {
return err
}
return nil
}

View File

@ -1,48 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package migrations
import (
// stdlib
"database/sql"
)
func PrivatePastesUp(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE pastes ADD COLUMN private BOOLEAN NOT NULL DEFAULT false; COMMENT ON COLUMN pastes.private IS 'Private paste? If true - additional URL parameter (UNIX TIMESTAMP) of paste will be required to access.';")
if err != nil {
return err
}
return nil
}
func PrivatePastesDown(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE pastes DROP COLUMN private")
if err != nil {
return err
}
return nil
}

View File

@ -1,58 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package migrations
import (
// stdlib
"database/sql"
)
func PasswordedPastesUp(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE pastes ADD COLUMN password VARCHAR(64) NOT NULL DEFAULT ''; COMMENT ON COLUMN pastes.password IS 'Password for paste (scrypted and sha256ed).';")
if err != nil {
return err
}
_, err1 := tx.Exec("ALTER TABLE pastes ADD COLUMN password_salt VARCHAR(64) NOT NULL DEFAULT ''; COMMENT ON COLUMN pastes.password_salt IS 'Password salt (sha256ed).';")
if err1 != nil {
return err1
}
return nil
}
func PasswordedPastesDown(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE pastes DROP COLUMN password")
if err != nil {
return err
}
_, err1 := tx.Exec("ALTER TABLE pastes DROP COLUMN password_salt")
if err1 != nil {
return err1
}
return nil
}

View File

@ -1,66 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package migrations
import (
// local
"gitlab.com/pztrn/fastpastebin/context"
// other
//"gitlab.com/jmoiron/sqlx"
"github.com/pressly/goose"
)
var (
c *context.Context
)
// New initializes migrations.
func New(cc *context.Context) {
c = cc
}
// Migrate launching migrations.
func Migrate() {
c.Logger.Info().Msg("Migrating database...")
goose.SetDialect("postgres")
goose.AddNamedMigration("1_initial.go", InitialUp, nil)
goose.AddNamedMigration("2_paste_lang.go", PasteLangUp, PasteLangDown)
goose.AddNamedMigration("3_private_pastes.go", PrivatePastesUp, PrivatePastesDown)
goose.AddNamedMigration("4_passworded_pastes.go", PasswordedPastesUp, PasswordedPastesDown)
// Add new migrations BEFORE this message.
dbConn := c.Database.GetDatabaseConnection()
if dbConn != nil {
err := goose.Up(dbConn, ".")
if err != nil {
c.Logger.Info().Msgf("%+v", err)
c.Logger.Panic().Msgf("Failed to migrate database to latest version: %s", err.Error())
}
} else {
c.Logger.Warn().Msg("Current database dialect isn't supporting migrations, skipping")
}
}

View File

@ -1,185 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package postgresql
import (
// stdlib
"database/sql"
"fmt"
"time"
// local
"gitlab.com/pztrn/fastpastebin/database/dialects/postgresql/migrations"
"gitlab.com/pztrn/fastpastebin/pastes/model"
// other
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
)
// Database is a PostgreSQL connection controlling structure.
type Database struct {
db *sqlx.DB
}
// Checks if queries can be run on known connection and reestablish it
// if not.
func (db *Database) check() {
_, err := db.db.Exec("SELECT 1")
if err != nil {
db.Initialize()
}
}
func (db *Database) GetDatabaseConnection() *sql.DB {
db.check()
return db.db.DB
}
// GetPaste returns a single paste by ID.
func (db *Database) GetPaste(pasteID int) (*pastesmodel.Paste, error) {
db.check()
p := &pastesmodel.Paste{}
err := db.db.Get(p, db.db.Rebind("SELECT * FROM pastes WHERE id=$1"), pasteID)
if err != nil {
return nil, err
}
// We're aware of timezone in PostgreSQL, so SELECT will return
// timestamps in server's local timezone. We should convert them.
loc, _ := time.LoadLocation("UTC")
utcCreatedAt := p.CreatedAt.In(loc)
p.CreatedAt = &utcCreatedAt
return p, nil
}
func (db *Database) GetPagedPastes(page int) ([]pastesmodel.Paste, error) {
db.check()
var pastesRaw []pastesmodel.Paste
var pastes []pastesmodel.Paste
// Pagination.
var startPagination = 0
if page > 1 {
startPagination = (page - 1) * c.Config.Pastes.Pagination
}
err := db.db.Select(&pastesRaw, db.db.Rebind("SELECT * FROM pastes WHERE private != true ORDER BY id DESC LIMIT $1 OFFSET $2"), c.Config.Pastes.Pagination, startPagination)
if err != nil {
return nil, err
}
// We're aware of timezone in PostgreSQL, so SELECT will return
// timestamps in server's local timezone. We should convert them.
loc, _ := time.LoadLocation("UTC")
for _, paste := range pastesRaw {
if !paste.IsExpired() {
utcCreatedAt := paste.CreatedAt.In(loc)
paste.CreatedAt = &utcCreatedAt
pastes = append(pastes, paste)
}
}
return pastes, nil
}
func (db *Database) GetPastesPages() int {
db.check()
var pastesRaw []pastesmodel.Paste
var pastes []pastesmodel.Paste
err := db.db.Get(&pastesRaw, "SELECT * FROM pastes WHERE private != true")
if err != nil {
return 1
}
// Check if pastes isn't expired.
for _, paste := range pastesRaw {
if !paste.IsExpired() {
pastes = append(pastes, paste)
}
}
// Calculate pages.
pages := len(pastes) / c.Config.Pastes.Pagination
// Check if we have any remainder. Add 1 to pages count if so.
if len(pastes)%c.Config.Pastes.Pagination > 0 {
pages++
}
return pages
}
// Initialize initializes MySQL/MariaDB connection.
func (db *Database) Initialize() {
c.Logger.Info().Msg("Initializing database connection...")
var userpass = ""
if c.Config.Database.Password == "" {
userpass = c.Config.Database.Username
} else {
userpass = c.Config.Database.Username + ":" + c.Config.Database.Password
}
dbConnString := fmt.Sprintf("postgres://%s@%s:%s/%s?connect_timeout=10&fallback_application_name=fastpastebin&sslmode=disable", userpass, c.Config.Database.Address, c.Config.Database.Port, c.Config.Database.Database)
c.Logger.Debug().Msgf("Database connection string: %s", dbConnString)
dbConn, err := sqlx.Connect("postgres", dbConnString)
if err != nil {
c.Logger.Panic().Msgf("Failed to connect to database: %s", err.Error())
}
c.Logger.Info().Msg("Database connection established")
db.db = dbConn
// Perform migrations.
migrations.New(c)
migrations.Migrate()
}
func (db *Database) SavePaste(p *pastesmodel.Paste) (int64, error) {
db.check()
stmt, err := db.db.PrepareNamed("INSERT INTO pastes (title, data, created_at, keep_for, keep_for_unit_type, language, private, password, password_salt) VALUES (:title, :data, :created_at, :keep_for, :keep_for_unit_type, :language, :private, :password, :password_salt) RETURNING id")
if err != nil {
return 0, err
}
var id int64
err = stmt.Get(&id, p)
if err != nil {
return 0, err
}
return id, nil
}
func (db *Database) Shutdown() {
err := db.db.Close()
if err != nil {
c.Logger.Error().Msgf("Failed to close database connection: %s", err.Error())
}
}

View File

@ -1,43 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package database
import (
// local
"gitlab.com/pztrn/fastpastebin/context"
"gitlab.com/pztrn/fastpastebin/database/interface"
)
var (
c *context.Context
d *Database
)
// New initializes database structure.
func New(cc *context.Context) {
c = cc
d = &Database{}
c.RegisterDatabaseInterface(databaseinterface.Interface(Handler{}))
}

View File

@ -1,71 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package database
import (
// stdlib
"database/sql"
// local
"gitlab.com/pztrn/fastpastebin/database/dialects/interface"
"gitlab.com/pztrn/fastpastebin/pastes/model"
)
// Handler is an interfaceable structure that proxifies calls from anyone
// to Database structure.
type Handler struct{}
func (dbh Handler) GetDatabaseConnection() *sql.DB {
return d.GetDatabaseConnection()
}
func (dbh Handler) GetPaste(pasteID int) (*pastesmodel.Paste, error) {
return d.GetPaste(pasteID)
}
func (dbh Handler) GetPagedPastes(page int) ([]pastesmodel.Paste, error) {
return d.GetPagedPastes(page)
}
func (dbh Handler) GetPastesPages() int {
return d.GetPastesPages()
}
// Initialize initializes connection to database.
func (dbh Handler) Initialize() {
d.Initialize()
}
func (dbh Handler) RegisterDialect(di dialectinterface.Interface) {
d.RegisterDialect(di)
}
func (dbh Handler) SavePaste(p *pastesmodel.Paste) (int64, error) {
return d.SavePaste(p)
}
func (dbh Handler) Shutdown() {
d.Shutdown()
}

View File

@ -1,47 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package databaseinterface
import (
// stdlib
"database/sql"
// local
"gitlab.com/pztrn/fastpastebin/database/dialects/interface"
"gitlab.com/pztrn/fastpastebin/pastes/model"
)
// Interface represents database interface which is available to all
// parts of application and registers with context.Context.
type Interface interface {
GetDatabaseConnection() *sql.DB
GetPaste(pasteID int) (*pastesmodel.Paste, error)
GetPagedPastes(page int) ([]pastesmodel.Paste, error)
GetPastesPages() int
Initialize()
RegisterDialect(dialectinterface.Interface)
SavePaste(p *pastesmodel.Paste) (int64, error)
Shutdown()
}

View File

@ -5,7 +5,7 @@
pkg: static
# destination
dest: "./api/http/static/"
dest: "./assets/static/"
# gofmt
# type: bool

View File

@ -1,93 +0,0 @@
package pagination
import (
// stdlib
"strconv"
"strings"
// local
"gitlab.com/pztrn/fastpastebin/api/http/static"
)
// CreateHTML creates pagination HTML based on passed parameters.
func CreateHTML(currentPage int, pages int, linksBase string) string {
// Load templates.
paginationHTMLRaw, err := static.ReadFile("pagination.html")
if err != nil {
return "Missing pagination.html"
}
paginationLinkRaw, err1 := static.ReadFile("pagination_link.html")
if err1 != nil {
return "Missing pagination_link.html"
}
paginationLinkCurrentRaw, err2 := static.ReadFile("pagination_link_current.html")
if err2 != nil {
return "Missing pagination_link_current.html"
}
paginationEllipsisRaw, err3 := static.ReadFile("pagination_ellipsis.html")
if err3 != nil {
return "Missing pagination_ellipsis.html"
}
// First page should always be visible.
var paginationString = ""
if currentPage == 1 {
paginationString = strings.Replace(string(paginationLinkCurrentRaw), "{pageNum}", strconv.Itoa(currentPage), -1)
} else {
paginationString = strings.Replace(string(paginationLinkRaw), "{pageNum}", "1", -1)
paginationString = strings.Replace(string(paginationString), "{paginationLink}", linksBase+"1", -1)
}
var ellipsisStartAdded = false
var ellipsisEndAdded = false
i := 2
for i <= pages {
if pages > 5 {
if currentPage-3 < i && currentPage+3 > i || i == pages {
var paginationItemRaw = string(paginationLinkRaw)
if i == currentPage {
paginationItemRaw = string(paginationLinkCurrentRaw)
}
paginationItem := strings.Replace(paginationItemRaw, "{pageNum}", strconv.Itoa(i), -1)
paginationItem = strings.Replace(paginationItem, "{paginationLink}", linksBase+strconv.Itoa(i), 1)
paginationString += paginationItem
} else {
if currentPage-3 < i && !ellipsisStartAdded {
paginationString += string(paginationEllipsisRaw)
ellipsisStartAdded = true
} else if currentPage+3 > i && !ellipsisEndAdded {
paginationString += string(paginationEllipsisRaw)
ellipsisEndAdded = true
}
}
} else {
var paginationItemRaw = string(paginationLinkRaw)
if i == currentPage {
paginationItemRaw = string(paginationLinkCurrentRaw)
}
paginationItem := strings.Replace(paginationItemRaw, "{pageNum}", strconv.Itoa(i), -1)
paginationItem = strings.Replace(paginationItem, "{paginationLink}", linksBase+strconv.Itoa(i), 1)
paginationString += paginationItem
}
i += 1
}
pagination := strings.Replace(string(paginationHTMLRaw), "{paginationLinks}", paginationString, 1)
if currentPage+1 <= pages {
pagination = strings.Replace(pagination, "{nextPageLink}", linksBase+strconv.Itoa(currentPage+1), 1)
} else {
pagination = strings.Replace(pagination, "{nextPageLink}", linksBase+strconv.Itoa(pages), 1)
}
if currentPage-1 > 1 {
pagination = strings.Replace(pagination, "{previousPageLink}", linksBase+strconv.Itoa(currentPage-1), 1)
} else {
pagination = strings.Replace(pagination, "{previousPageLink}", linksBase, 1)
}
return pagination
}

View File

@ -1,463 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package pastes
import (
// stdlib
"bytes"
"net/http"
"regexp"
"strconv"
"strings"
"time"
// local
"gitlab.com/pztrn/fastpastebin/captcha"
"gitlab.com/pztrn/fastpastebin/pagination"
"gitlab.com/pztrn/fastpastebin/pastes/model"
"gitlab.com/pztrn/fastpastebin/templater"
// other
"github.com/alecthomas/chroma"
"github.com/alecthomas/chroma/formatters"
htmlfmt "github.com/alecthomas/chroma/formatters/html"
"github.com/alecthomas/chroma/lexers"
"github.com/alecthomas/chroma/styles"
//"gitlab.com/dchest/captcha"
"github.com/labstack/echo"
)
var (
regexInts = regexp.MustCompile("[0-9]+")
)
// GET for "/paste/PASTE_ID" and "/paste/PASTE_ID/TIMESTAMP" (private pastes).
func pasteGET(ec echo.Context) error {
pasteIDRaw := ec.Param("id")
// We already get numbers from string, so we will not check strconv.Atoi()
// error.
pasteID, _ := strconv.Atoi(regexInts.FindAllString(pasteIDRaw, 1)[0])
c.Logger.Debug().Msgf("Requesting paste #%+v", pasteID)
// Get paste.
paste, err1 := c.Database.GetPaste(pasteID)
if err1 != nil {
c.Logger.Error().Msgf("Failed to get paste #%d: %s", pasteID, err1.Error())
errtpl := templater.GetErrorTemplate(ec, "Paste #"+strconv.Itoa(pasteID)+" not found")
return ec.HTML(http.StatusBadRequest, errtpl)
}
if paste.IsExpired() {
c.Logger.Error().Msgf("Paste #%d is expired", pasteID)
errtpl := templater.GetErrorTemplate(ec, "Paste #"+strconv.Itoa(pasteID)+" not found")
return ec.HTML(http.StatusBadRequest, errtpl)
}
// Check if we have a private paste and it's parameters are correct.
if paste.Private {
tsProvidedStr := ec.Param("timestamp")
tsProvided, err2 := strconv.ParseInt(tsProvidedStr, 10, 64)
if err2 != nil {
c.Logger.Error().Msgf("Invalid timestamp '%s' provided for getting private paste #%d: %s", tsProvidedStr, pasteID, err2.Error())
errtpl := templater.GetErrorTemplate(ec, "Paste #"+strconv.Itoa(pasteID)+" not found")
return ec.HTML(http.StatusBadRequest, errtpl)
}
pasteTs := paste.CreatedAt.Unix()
if tsProvided != pasteTs {
c.Logger.Error().Msgf("Incorrect timestamp '%v' provided for private paste #%d, waiting for %v", tsProvidedStr, pasteID, strconv.FormatInt(pasteTs, 10))
errtpl := templater.GetErrorTemplate(ec, "Paste #"+strconv.Itoa(pasteID)+" not found")
return ec.HTML(http.StatusBadRequest, errtpl)
}
}
if paste.Private && paste.Password != "" {
// Check if cookie for this paste is defined. This means that user
// previously successfully entered a password.
cookie, err := ec.Cookie("PASTE-" + strconv.Itoa(pasteID))
if err != nil {
// No cookie, redirect to auth page.
c.Logger.Info().Msg("Tried to access passworded paste without autorization, redirecting to auth page...")
return ec.Redirect(http.StatusMovedPermanently, "/paste/"+pasteIDRaw+"/"+ec.Param("timestamp")+"/verify")
}
// Generate cookie value to check.
cookieValue := paste.GenerateCryptedCookieValue()
if cookieValue != cookie.Value {
c.Logger.Info().Msg("Invalid cookie, redirecting to auth page...")
return ec.Redirect(http.StatusMovedPermanently, "/paste/"+pasteIDRaw+"/"+ec.Param("timestamp")+"/verify")
}
// If all okay - do nothing :)
}
// Format paste data map.
pasteData := make(map[string]string)
pasteData["pasteTitle"] = paste.Title
pasteData["pasteID"] = strconv.Itoa(paste.ID)
pasteData["pasteDate"] = paste.CreatedAt.Format("2006-01-02 @ 15:04:05") + " UTC"
pasteData["pasteLanguage"] = paste.Language
pasteExpirationString := "Never"
if paste.KeepFor != 0 && paste.KeepForUnitType != 0 {
pasteExpirationString = paste.GetExpirationTime().Format("2006-01-02 @ 15:04:05") + " UTC"
}
pasteData["pasteExpiration"] = pasteExpirationString
if paste.Private {
pasteData["pasteType"] = "<span class='has-text-danger'>Private</span>"
pasteData["pasteTs"] = strconv.FormatInt(paste.CreatedAt.Unix(), 10) + "/"
} else {
pasteData["pasteType"] = "<span class='has-text-success'>Public</span>"
pasteData["pasteTs"] = ""
}
// Highlight.
// Get lexer.
lexer := lexers.Get(paste.Language)
if lexer == nil {
lexer = lexers.Fallback
}
// Tokenize paste data.
lexered, err3 := lexer.Tokenise(nil, paste.Data)
if err3 != nil {
c.Logger.Error().Msgf("Failed to tokenize paste data: %s", err3.Error())
}
// Get style for HTML output.
style := styles.Get("monokai")
if style == nil {
style = styles.Fallback
}
// Get HTML formatter.
formatter := chroma.Formatter(htmlfmt.New(htmlfmt.WithLineNumbers(), htmlfmt.LineNumbersInTable()))
if formatter == nil {
formatter = formatters.Fallback
}
// Create buffer and format into it.
buf := new(bytes.Buffer)
err4 := formatter.Format(buf, style, lexered)
if err4 != nil {
c.Logger.Error().Msgf("Failed to format paste data: %s", err4.Error())
}
pasteData["pastedata"] = buf.String()
// Get template and format it.
pasteHTML := templater.GetTemplate(ec, "paste.html", pasteData)
return ec.HTML(http.StatusOK, pasteHTML)
}
// GET for "/paste/PASTE_ID/TIMESTAMP/verify" - a password verify page.
func pastePasswordedVerifyGet(ec echo.Context) error {
pasteIDRaw := ec.Param("id")
timestampRaw := ec.Param("timestamp")
// We already get numbers from string, so we will not check strconv.Atoi()
// error.
pasteID, _ := strconv.Atoi(regexInts.FindAllString(pasteIDRaw, 1)[0])
// Get paste.
paste, err1 := c.Database.GetPaste(pasteID)
if err1 != nil {
c.Logger.Error().Msgf("Failed to get paste #%d: %s", pasteID, err1.Error())
errtpl := templater.GetErrorTemplate(ec, "Paste #"+pasteIDRaw+" not found")
return ec.HTML(http.StatusBadRequest, errtpl)
}
// Check for auth cookie. If present - redirect to paste.
cookie, err := ec.Cookie("PASTE-" + strconv.Itoa(pasteID))
if err == nil {
// No cookie, redirect to auth page.
c.Logger.Debug().Msg("Paste cookie found, checking it...")
// Generate cookie value to check.
cookieValue := paste.GenerateCryptedCookieValue()
if cookieValue == cookie.Value {
c.Logger.Info().Msg("Valid cookie, redirecting to paste page...")
return ec.Redirect(http.StatusMovedPermanently, "/paste/"+pasteIDRaw+"/"+ec.Param("timestamp"))
}
c.Logger.Debug().Msg("Invalid cookie, showing auth page")
}
// HTML data.
htmlData := make(map[string]string)
htmlData["pasteID"] = strconv.Itoa(pasteID)
htmlData["pasteTimestamp"] = timestampRaw
verifyHTML := templater.GetTemplate(ec, "passworded_paste_verify.html", htmlData)
return ec.HTML(http.StatusOK, verifyHTML)
}
// POST for "/paste/PASTE_ID/TIMESTAMP/verify" - a password verify page.
func pastePasswordedVerifyPost(ec echo.Context) error {
pasteIDRaw := ec.Param("id")
timestampRaw := ec.Param("timestamp")
// We already get numbers from string, so we will not check strconv.Atoi()
// error.
pasteID, _ := strconv.Atoi(regexInts.FindAllString(pasteIDRaw, 1)[0])
c.Logger.Debug().Msgf("Requesting paste #%+v", pasteID)
// Get paste.
paste, err1 := c.Database.GetPaste(pasteID)
if err1 != nil {
c.Logger.Error().Msgf("Failed to get paste #%d: %s", pasteID, err1.Error())
errtpl := templater.GetErrorTemplate(ec, "Paste #"+strconv.Itoa(pasteID)+" not found")
return ec.HTML(http.StatusBadRequest, errtpl)
}
params, err2 := ec.FormParams()
if err2 != nil {
c.Logger.Debug().Msg("No form parameters passed")
errtpl := templater.GetErrorTemplate(ec, "Paste #"+strconv.Itoa(pasteID)+" not found")
return ec.HTML(http.StatusBadRequest, errtpl)
}
if paste.VerifyPassword(params["paste-password"][0]) {
// Set cookie that this paste's password is verified and paste
// can be viewed.
cookie := new(http.Cookie)
cookie.Name = "PASTE-" + strconv.Itoa(pasteID)
cookie.Value = paste.GenerateCryptedCookieValue()
cookie.Expires = time.Now().Add(24 * time.Hour)
ec.SetCookie(cookie)
return ec.Redirect(http.StatusFound, "/paste/"+strconv.Itoa(pasteID)+"/"+timestampRaw)
}
errtpl := templater.GetErrorTemplate(ec, "Invalid password. Please, try again.")
return ec.HTML(http.StatusBadRequest, string(errtpl))
}
// POST for "/paste/" which will create new paste and redirect to
// "/pastes/CREATED_PASTE_ID".
func pastePOST(ec echo.Context) error {
params, err := ec.FormParams()
if err != nil {
errtpl := templater.GetErrorTemplate(ec, "Cannot create empty paste")
return ec.HTML(http.StatusBadRequest, errtpl)
}
c.Logger.Debug().Msgf("Received parameters: %+v", params)
// Do nothing if paste contents is empty.
if len(params["paste-contents"][0]) == 0 {
c.Logger.Debug().Msg("Empty paste submitted, ignoring")
errtpl := templater.GetErrorTemplate(ec, "Empty pastes aren't allowed.")
return ec.HTML(http.StatusBadRequest, errtpl)
}
if !strings.ContainsAny(params["paste-keep-for"][0], "Mmhd") && params["paste-keep-for"][0] != "forever" {
c.Logger.Debug().Msgf("'Keep paste for' field have invalid value: %s", params["paste-keep-for"][0])
errtpl := templater.GetErrorTemplate(ec, "Invalid 'Paste should be available for' parameter passed. Please do not try to hack us ;).")
return ec.HTML(http.StatusBadRequest, errtpl)
}
// Verify captcha.
if !captcha.Verify(params["paste-captcha-id"][0], params["paste-captcha-solution"][0]) {
c.Logger.Debug().Msgf("Invalid captcha solution for captcha ID '%s': %s", params["paste-captcha-id"][0], params["paste-captcha-solution"][0])
errtpl := templater.GetErrorTemplate(ec, "Invalid captcha solution.")
return ec.HTML(http.StatusBadRequest, errtpl)
}
paste := &pastesmodel.Paste{
Title: params["paste-title"][0],
Data: params["paste-contents"][0],
Language: params["paste-language"][0],
}
// Paste creation time in UTC.
createdAt := time.Now().UTC()
paste.CreatedAt = &createdAt
// Parse "keep for" field.
// Defaulting to "forever".
keepFor := 0
keepForUnit := 0
if params["paste-keep-for"][0] != "forever" {
keepForUnitRegex := regexp.MustCompile("[Mmhd]")
keepForRaw := regexInts.FindAllString(params["paste-keep-for"][0], 1)[0]
var err error
keepFor, err = strconv.Atoi(keepForRaw)
if err != nil {
if params["paste-keep-for"][0] == "forever" {
c.Logger.Debug().Msg("Keeping paste forever!")
keepFor = 0
} else {
c.Logger.Debug().Err(err).Msg("Failed to parse 'Keep for' integer")
errtpl := templater.GetErrorTemplate(ec, "Invalid 'Paste should be available for' parameter passed. Please do not try to hack us ;).")
return ec.HTML(http.StatusBadRequest, errtpl)
}
}
keepForUnitRaw := keepForUnitRegex.FindAllString(params["paste-keep-for"][0], 1)[0]
keepForUnit = pastesmodel.PASTE_KEEPS_CORELLATION[keepForUnitRaw]
}
paste.KeepFor = keepFor
paste.KeepForUnitType = keepForUnit
// Try to autodetect if it was selected.
if params["paste-language"][0] == "autodetect" {
lexer := lexers.Analyse(params["paste-language"][0])
if lexer != nil {
paste.Language = lexer.Config().Name
} else {
paste.Language = "text"
}
}
// Private paste?
paste.Private = false
privateCheckbox, privateCheckboxFound := params["paste-private"]
pastePassword, pastePasswordFound := params["paste-password"]
if privateCheckboxFound && privateCheckbox[0] == "on" || pastePasswordFound && pastePassword[0] != "" {
paste.Private = true
}
if pastePassword[0] != "" {
paste.CreatePassword(pastePassword[0])
}
id, err2 := c.Database.SavePaste(paste)
if err2 != nil {
c.Logger.Debug().Msgf("Failed to save paste: %s", err2.Error())
errtpl := templater.GetErrorTemplate(ec, "Failed to save paste. Please, try again later.")
return ec.HTML(http.StatusBadRequest, errtpl)
}
newPasteIDAsString := strconv.FormatInt(id, 10)
c.Logger.Debug().Msgf("Paste saved, URL: /paste/" + newPasteIDAsString)
// Private pastes have it's timestamp in URL.
if paste.Private {
return ec.Redirect(http.StatusFound, "/paste/"+newPasteIDAsString+"/"+strconv.FormatInt(paste.CreatedAt.Unix(), 10))
}
return ec.Redirect(http.StatusFound, "/paste/"+newPasteIDAsString)
}
// GET for "/pastes/:id/raw", raw paste output.
func pasteRawGET(ec echo.Context) error {
pasteIDRaw := ec.Param("id")
// We already get numbers from string, so we will not check strconv.Atoi()
// error.
pasteID, _ := strconv.Atoi(regexInts.FindAllString(pasteIDRaw, 1)[0])
c.Logger.Debug().Msgf("Requesting paste #%+v", pasteID)
// Get paste.
paste, err1 := c.Database.GetPaste(pasteID)
if err1 != nil {
c.Logger.Error().Msgf("Failed to get paste #%d from database: %s", pasteID, err1.Error())
return ec.HTML(http.StatusBadRequest, "Paste #"+pasteIDRaw+" does not exist.")
}
if paste.IsExpired() {
c.Logger.Error().Msgf("Paste #%d is expired", pasteID)
return ec.HTML(http.StatusBadRequest, "Paste #"+pasteIDRaw+" does not exist.")
}
// Check if we have a private paste and it's parameters are correct.
if paste.Private {
tsProvidedStr := ec.Param("timestamp")
tsProvided, err2 := strconv.ParseInt(tsProvidedStr, 10, 64)
if err2 != nil {
c.Logger.Error().Msgf("Invalid timestamp '%s' provided for getting private paste #%d: %s", tsProvidedStr, pasteID, err2.Error())
return ec.String(http.StatusBadRequest, "Paste #"+pasteIDRaw+" not found")
}
pasteTs := paste.CreatedAt.Unix()
if tsProvided != pasteTs {
c.Logger.Error().Msgf("Incorrect timestamp '%v' provided for private paste #%d, waiting for %v", tsProvidedStr, pasteID, strconv.FormatInt(pasteTs, 10))
return ec.String(http.StatusBadRequest, "Paste #"+pasteIDRaw+" not found")
}
}
// ToDo: figure out how to handle passworded pastes here.
// Return error for now.
if paste.Password != "" {
c.Logger.Error().Msgf("Cannot render paste #%d as raw: passworded paste. Patches welcome!", pasteID)
return ec.String(http.StatusBadRequest, "Paste #"+pasteIDRaw+" not found")
}
return ec.String(http.StatusOK, paste.Data)
}
// GET for "/pastes/", a list of publicly available pastes.
func pastesGET(ec echo.Context) error {
pageFromParamRaw := ec.Param("page")
var page = 1
if pageFromParamRaw != "" {
pageRaw := regexInts.FindAllString(pageFromParamRaw, 1)[0]
page, _ = strconv.Atoi(pageRaw)
}
c.Logger.Debug().Msgf("Requested page #%d", page)
// Get pastes IDs.
pastes, err3 := c.Database.GetPagedPastes(page)
c.Logger.Debug().Msgf("Got %d pastes", len(pastes))
var pastesString = "No pastes to show."
// Show "No pastes to show" on any error for now.
if err3 != nil {
c.Logger.Error().Msgf("Failed to get pastes list from database: %s", err3.Error())
noPastesToShowTpl := templater.GetErrorTemplate(ec, "No pastes to show.")
return ec.HTML(http.StatusOK, noPastesToShowTpl)
}
if len(pastes) > 0 {
pastesString = ""
for i := range pastes {
pasteDataMap := make(map[string]string)
pasteDataMap["pasteID"] = strconv.Itoa(pastes[i].ID)
pasteDataMap["pasteTitle"] = pastes[i].Title
pasteDataMap["pasteDate"] = pastes[i].CreatedAt.Format("2006-01-02 @ 15:04:05") + " UTC"
// Get max 4 lines of each paste.
pasteDataSplitted := strings.Split(pastes[i].Data, "\n")
var pasteData = ""
if len(pasteDataSplitted) < 4 {
pasteData = pastes[i].Data
} else {
pasteData = strings.Join(pasteDataSplitted[0:4], "\n")
}
pasteDataMap["pasteData"] = pasteData
pasteTpl := templater.GetRawTemplate(ec, "pastelist_paste.html", pasteDataMap)
pastesString += pasteTpl
}
}
// Pagination.
pages := c.Database.GetPastesPages()
c.Logger.Debug().Msgf("Total pages: %d, current: %d", pages, page)
paginationHTML := pagination.CreateHTML(page, pages, "/pastes/")
pasteListTpl := templater.GetTemplate(ec, "pastelist_list.html", map[string]string{"pastes": pastesString, "pagination": paginationHTML})
return ec.HTML(http.StatusOK, string(pasteListTpl))
}

View File

@ -1,60 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package pastes
import (
// local
"gitlab.com/pztrn/fastpastebin/context"
)
var (
c *context.Context
)
// New initializes pastes package and adds neccessary HTTP and API
// endpoints.
func New(cc *context.Context) {
c = cc
// New paste.
c.Echo.POST("/paste/", pastePOST)
// Show public paste.
c.Echo.GET("/paste/:id", pasteGET)
// Show RAW representation of public paste.
c.Echo.GET("/paste/:id/raw", pasteRawGET)
// Show private paste.
c.Echo.GET("/paste/:id/:timestamp", pasteGET)
// Show RAW representation of private paste.
c.Echo.GET("/paste/:id/:timestamp/raw", pasteRawGET)
// Verify access to passworded paste.
c.Echo.GET("/paste/:id/:timestamp/verify", pastePasswordedVerifyGet)
c.Echo.POST("/paste/:id/:timestamp/verify", pastePasswordedVerifyPost)
// Pastes list.
c.Echo.GET("/pastes/", pastesGET)
c.Echo.GET("/pastes/:page", pastesGET)
}

View File

@ -1,146 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package pastesmodel
import (
// stdlib
"crypto/sha256"
"fmt"
"math/rand"
"time"
// other
"golang.org/x/crypto/scrypt"
)
const (
PASTE_KEEP_FOREVER = 0
PASTE_KEEP_FOR_MINUTES = 1
PASTE_KEEP_FOR_HOURS = 2
PASTE_KEEP_FOR_DAYS = 3
PASTE_KEEP_FOR_MONTHS = 4
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
var (
PASTE_KEEPS_CORELLATION = map[string]int{
"M": PASTE_KEEP_FOR_MINUTES,
"h": PASTE_KEEP_FOR_HOURS,
"d": PASTE_KEEP_FOR_DAYS,
"m": PASTE_KEEP_FOR_MONTHS,
"forever": PASTE_KEEP_FOREVER,
}
)
// Paste represents paste itself.
type Paste struct {
ID int `db:"id" json:"id"`
Title string `db:"title" json:"title"`
Data string `db:"data" json:"data"`
CreatedAt *time.Time `db:"created_at" json:"created_at"`
KeepFor int `db:"keep_for" json:"keep_for"`
KeepForUnitType int `db:"keep_for_unit_type" json:"keep_for_unit_type"`
Language string `db:"language" json:"language"`
Private bool `db:"private" json:"private"`
Password string `db:"password" json:"password"`
PasswordSalt string `db:"password_salt" json:"password_salt"`
}
// CreatePassword creates password for current paste.
func (p *Paste) CreatePassword(password string) error {
// Create salt - random string.
seededRand := rand.New(rand.NewSource(time.Now().UnixNano()))
saltBytes := make([]byte, 64)
for i := range saltBytes {
saltBytes[i] = charset[seededRand.Intn(len(charset))]
}
saltHashBytes := sha256.Sum256(saltBytes)
p.PasswordSalt = fmt.Sprintf("%x", saltHashBytes)
// Create crypted password and hash it.
passwordCrypted, err := scrypt.Key([]byte(password), []byte(p.PasswordSalt), 131072, 8, 1, 64)
if err != nil {
return err
}
passwordHashBytes := sha256.Sum256(passwordCrypted)
p.Password = fmt.Sprintf("%x", passwordHashBytes)
return nil
}
// GenerateCryptedCookieValue generates crypted cookie value for paste.
func (p *Paste) GenerateCryptedCookieValue() string {
cookieValueCrypted, _ := scrypt.Key([]byte(p.Password), []byte(p.PasswordSalt), 131072, 8, 1, 64)
return fmt.Sprintf("%x", sha256.Sum256(cookieValueCrypted))
}
func (p *Paste) GetExpirationTime() time.Time {
var expirationTime time.Time
switch p.KeepForUnitType {
case PASTE_KEEP_FOREVER:
expirationTime = time.Now().UTC().Add(time.Hour * 1)
case PASTE_KEEP_FOR_MINUTES:
expirationTime = p.CreatedAt.Add(time.Minute * time.Duration(p.KeepFor))
case PASTE_KEEP_FOR_HOURS:
expirationTime = p.CreatedAt.Add(time.Hour * time.Duration(p.KeepFor))
case PASTE_KEEP_FOR_DAYS:
expirationTime = p.CreatedAt.Add(time.Hour * 24 * time.Duration(p.KeepFor))
case PASTE_KEEP_FOR_MONTHS:
expirationTime = p.CreatedAt.Add(time.Hour * 24 * 30 * time.Duration(p.KeepFor))
}
return expirationTime
}
// IsExpired checks if paste is already expired (or not).
func (p *Paste) IsExpired() bool {
curTime := time.Now().UTC()
expirationTime := p.GetExpirationTime()
if curTime.Sub(expirationTime).Seconds() > 0 {
return true
}
return false
}
// VerifyPassword verifies that provided password is valid.
func (p *Paste) VerifyPassword(password string) bool {
// Create crypted password and hash it.
passwordCrypted, err := scrypt.Key([]byte(password), []byte(p.PasswordSalt), 131072, 8, 1, 64)
if err != nil {
return false
}
passwordHashBytes := sha256.Sum256(passwordCrypted)
providedPassword := fmt.Sprintf("%x", passwordHashBytes)
if providedPassword == p.Password {
return true
}
return false
}

View File

@ -1,124 +0,0 @@
// Fast Paste Bin - uberfast and easy-to-use pastebin.
//
// Copyright (c) 2018, Stanislav N. aka pztrn and Fast Paste Bin
// developers.
//
// 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.
package templater
import (
// stdlib
"net/http"
"strings"
// local
"gitlab.com/pztrn/fastpastebin/api/http/static"
"gitlab.com/pztrn/fastpastebin/context"
// other
"github.com/labstack/echo"
)
var (
c *context.Context
)
// GetErrorTemplate returns formatted error template.
// If error.html wasn't found - it will return "error.html not found"
// message as simple string.
func GetErrorTemplate(ec echo.Context, errorText string) string {
// Getting main error template.
mainhtml := GetTemplate(ec, "error.html", map[string]string{"error": errorText})
return mainhtml
}
// GetRawTemplate returns only raw template data.
func GetRawTemplate(ec echo.Context, templateName string, data map[string]string) string {
// Getting main template.
tplRaw, err := static.ReadFile(templateName)
if err != nil {
ec.String(http.StatusBadRequest, templateName+" not found.")
return ""
}
tpl := string(tplRaw)
// Replace placeholders with data from data map.
for placeholder, value := range data {
tpl = strings.Replace(tpl, "{"+placeholder+"}", value, -1)
}
return tpl
}
// GetTemplate returns formatted template that can be outputted to client.
func GetTemplate(ec echo.Context, name string, data map[string]string) string {
c.Logger.Debug().Msgf("Requested template '%s'", name)
// Getting main template.
mainhtml, err := static.ReadFile("main.html")
if err != nil {
ec.String(http.StatusBadRequest, "main.html not found.")
return ""
}
// Getting navigation.
navhtml, err1 := static.ReadFile("navigation.html")
if err1 != nil {
ec.String(http.StatusBadRequest, "navigation.html not found.")
return ""
}
// Getting footer.
footerhtml, err2 := static.ReadFile("footer.html")
if err2 != nil {
ec.String(http.StatusBadRequest, "footer.html not found.")
return ""
}
// Format main template.
tpl := strings.Replace(string(mainhtml), "{navigation}", string(navhtml), 1)
tpl = strings.Replace(tpl, "{footer}", string(footerhtml), 1)
// Version.
tpl = strings.Replace(tpl, "{version}", context.Version, 1)
// Get requested template.
reqhtml, err3 := static.ReadFile(name)
if err3 != nil {
ec.String(http.StatusBadRequest, name+" not found.")
return ""
}
// Replace documentBody.
tpl = strings.Replace(tpl, "{documentBody}", string(reqhtml), 1)
// Replace placeholders with data from data map.
for placeholder, value := range data {
tpl = strings.Replace(tpl, "{"+placeholder+"}", value, -1)
}
return tpl
}
// Initialize initializes package.
func Initialize(cc *context.Context) {
c = cc
}

View File

@ -1 +0,0 @@
*DS_Store*

View File

@ -1,3 +0,0 @@
language: go
go:
- "1.10"

View File

@ -1,7 +0,0 @@
Copyright 2017-2018, Stanislav N. aka pztrn
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.

View File

@ -1,57 +0,0 @@
[![GoDoc](https://godoc.org/github.com/pztrn/flagger?status.svg)](https://godoc.org/github.com/pztrn/flagger) [![Build Status](https://travis-ci.org/pztrn/flagger.svg?branch=master)](https://travis-ci.org/pztrn/flagger)
# Flagger
Flagger is an arbitrary CLI flags parser, like argparse in Python.
Flagger is able to parse boolean, integer and string flags.
# Installation
```
go get -u -v lab.pztrn.name/golibs/flagger
```
# Usage
Flagger requires logging interface to be passed on initialization.
See ``loggerinterface.go`` for required logging functions.
It is able to run with standart log package, in that case
initialize flagger like:
```
flgr = flagger.New(flagger.LoggerInterface(log.New(os.Stdout, "testing logger: ", log.Lshortfile)))
flgr.Initialize()
```
Adding a flag is easy, just fill ``Flag`` structure and pass to ``AddFlag()`` call:
```
flag_bool := Flag{
Name: "boolflag",
Description: "Boolean flag",
Type: "bool",
DefaultValue: true,
}
err := flgr.AddFlag(&flag_bool)
if err != nil {
...
}
```
After adding all neccessary flags you should issue ``Parse()`` call to get
them parsed:
```
flgr.Parse()
```
After parsed they can be obtained everywhere you want, like:
```
val, err := flgr.GetBoolValue("boolflag")
if err != nil {
...
}
```
For more examples take a look at ``flagger_test.go`` file or [at GoDoc](https://github.com/pztrn/flagger).

View File

@ -1,48 +0,0 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017-2018, Stanislav N. aka pztrn.
//
// 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.
package flagger
import (
// stdlib
"log"
"os"
)
var (
logger LoggerInterface
)
// New creates new Flagger instance.
// If no logger will be passed - we will use default "log" module and will
// print logs to stdout.
func New(l LoggerInterface) *Flagger {
if l == nil {
lg := log.New(os.Stdout, "Flagger: ", log.LstdFlags)
logger = LoggerInterface(lg)
} else {
logger = l
}
f := Flagger{}
return &f
}

View File

@ -1,36 +0,0 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017-2018, Stanislav N. aka pztrn.
//
// 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.
package flagger
// This structure represents addable flag for Flagger.
type Flag struct {
// Flag name. It will be accessible using this name later.
Name string
// Description for help output.
Description string
// Type can be one of "bool", "int", "string".
Type string
// This value will be reflected.
DefaultValue interface{}
}

View File

@ -1,126 +0,0 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017-2018, Stanislav N. aka pztrn.
//
// 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.
package flagger
import (
// stdlib
"errors"
"flag"
"sync"
)
// Flagger implements (kinda) extended CLI parameters parser. As it
// available from CommonContext, these flags will be available to
// whole application.
//
// It uses reflection to determine what kind of variable we should
// parse or get.
type Flagger struct {
// Flags that was added by user.
flags map[string]*Flag
flagsMutex sync.Mutex
// Flags that will be passed to flag module.
flagsBool map[string]*bool
flagsInt map[string]*int
flagsString map[string]*string
}
// Adds flag to list of flags we will pass to ``flag`` package.
func (f *Flagger) AddFlag(flag *Flag) error {
_, present := f.flags[flag.Name]
if present {
logger.Fatal("Cannot add flag '" + flag.Name + "' - already added!")
return errors.New("Cannot add flag '" + flag.Name + "' - already added!")
}
f.flags[flag.Name] = flag
return nil
}
// This function returns boolean value for flag with given name.
// Returns bool value for flag and nil as error on success
// and false bool plus error with text on error.
func (f *Flagger) GetBoolValue(name string) (bool, error) {
fl, present := f.flagsBool[name]
if !present {
return false, errors.New("No such flag: " + name)
}
return (*fl), nil
}
// This function returns integer value for flag with given name.
// Returns integer on success and 0 on error.
func (f *Flagger) GetIntValue(name string) (int, error) {
fl, present := f.flagsInt[name]
if !present {
return 0, errors.New("No such flag: " + name)
}
return (*fl), nil
}
// This function returns string value for flag with given name.
// Returns string on success or empty string on error.
func (f *Flagger) GetStringValue(name string) (string, error) {
fl, present := f.flagsString[name]
if !present {
return "", errors.New("No such flag: " + name)
}
return (*fl), nil
}
// Flagger initialization.
func (f *Flagger) Initialize() {
logger.Print("Initializing CLI parameters parser...")
f.flags = make(map[string]*Flag)
f.flagsBool = make(map[string]*bool)
f.flagsInt = make(map[string]*int)
f.flagsString = make(map[string]*string)
}
// This function adds flags from flags map to flag package and parse
// them. They can be obtained later by calling GetTYPEValue(name),
// where TYPE is one of Bool, Int, String.
func (f *Flagger) Parse() {
for name, fl := range f.flags {
if fl.Type == "bool" {
fdef := fl.DefaultValue.(bool)
f.flagsBool[name] = &fdef
flag.BoolVar(&fdef, name, fdef, fl.Description)
} else if fl.Type == "int" {
fdef := fl.DefaultValue.(int)
f.flagsInt[name] = &fdef
flag.IntVar(&fdef, name, fdef, fl.Description)
} else if fl.Type == "string" {
fdef := fl.DefaultValue.(string)
f.flagsString[name] = &fdef
flag.StringVar(&fdef, name, fdef, fl.Description)
}
}
logger.Print("Parsing CLI parameters...")
flag.Parse()
}

View File

@ -1,31 +0,0 @@
// Flagger - arbitrary CLI flags parser.
//
// Copyright (c) 2017-2018, Stanislav N. aka pztrn.
//
// 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.
package flagger
// LoggerInterface provide logging interface, so everyone can inject own
// logging handlers.
type LoggerInterface interface {
Fatal(v ...interface{})
Print(v ...interface{})
}

View File

@ -6,6 +6,7 @@
# Folders
_obj
_test
tmp
# Architecture specific extensions/prefixes
*.[568vq]

View File

@ -4,6 +4,8 @@ go:
- "1.8"
- "1.9"
- "1.10"
- "1.11"
- "1.12"
- "master"
matrix:
allow_failures:

View File

@ -8,9 +8,9 @@ Zerolog's API is designed to provide both a great developer experience and stunn
Uber's [zap](https://godoc.org/go.uber.org/zap) library pioneered this approach. Zerolog is taking this concept to the next level with a simpler to use API and even better performance.
To keep the code base and the API simple, zerolog focuses on efficient structured logging only. Pretty logging on the console is made possible using the provided (but inefficient) `zerolog.ConsoleWriter`.
To keep the code base and the API simple, zerolog focuses on efficient structured logging only. Pretty logging on the console is made possible using the provided (but inefficient) [`zerolog.ConsoleWriter`](#pretty-logging).
![](pretty.png)
![Pretty Logging Image](pretty.png)
## Who uses zerolog
@ -34,11 +34,13 @@ Find out [who uses zerolog](https://github.com/rs/zerolog/wiki/Who-uses-zerolog)
```go
go get -u github.com/rs/zerolog/log
```
## Getting Started
### Simple Logging Example
For simple logging, import the global logger package **github.com/rs/zerolog/log**
```go
package main
@ -58,8 +60,35 @@ func main() {
// Output: {"time":1516134303,"level":"debug","message":"hello world"}
```
> Note: By default log writes to `os.Stderr`
> Note: The default log level for `log.Print` is *debug*
### Contextual Logging
**zerolog** allows data to be added to log messages in the form of key:value pairs. The data added to the message adds "context" about the log event that can be critical for debugging as well as myriad other purposes. An example of this is below:
```go
package main
import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
func main() {
zerolog.TimeFieldFormat = ""
log.Debug().
Str("Scale", "833 cents").
Float64("Interval", 833.09).
Msg("Fibonacci is everywhere")
}
// Output: {"time":1524104936,"level":"debug","Scale":"833 cents","Interval":833.09,"message":"Fibonacci is everywhere"}
```
> You'll note in the above example that when adding contextual fields, the fields are strongly typed. You can find the full list of supported fields [here](#standard-types)
### Leveled Logging
#### Simple Leveled Logging Example
@ -81,13 +110,16 @@ func main() {
// Output: {"time":1516134303,"level":"info","message":"hello world"}
```
> It is very important to note that when using the **zerolog** chaining API, as shown above (`log.Info().Msg("hello world"`), the chain must have either the `Msg` or `Msgf` method call. If you forget to add either of these, the log will not occur and there is no compile time error to alert you of this.
**zerolog** allows for logging at the following levels (from highest to lowest):
- panic (`zerolog.PanicLevel`, 5)
- fatal (`zerolog.FatalLevel`, 4)
- error (`zerolog.ErrorLevel`, 3)
- warn (`zerolog.WarnLevel`, 2)
- info (`zerolog.InfoLevel`, 1)
- debug (`zerolog.DebugLevel`, 0)
* panic (`zerolog.PanicLevel`, 5)
* fatal (`zerolog.FatalLevel`, 4)
* error (`zerolog.ErrorLevel`, 3)
* warn (`zerolog.WarnLevel`, 2)
* info (`zerolog.InfoLevel`, 1)
* debug (`zerolog.DebugLevel`, 0)
You can set the Global logging level to any of these options using the `SetGlobalLevel` function in the zerolog package, passing in one of the given constants above, e.g. `zerolog.InfoLevel` would be the "info" level. Whichever level is chosen, all logs with a level greater than or equal to that level will be written. To turn off logging entirely, pass the `zerolog.Disabled` constant.
@ -127,13 +159,16 @@ func main() {
}
}
```
Info Output (no flag)
```bash
$ ./logLevelExample
{"time":1516387492,"level":"info","message":"This message appears when log level set to Debug or Info"}
```
Debug Output (debug flag set)
```bash
$ ./logLevelExample -debug
{"time":1516387573,"level":"debug","message":"This message appears only when log level set to Debug"}
@ -141,6 +176,29 @@ $ ./logLevelExample -debug
{"time":1516387573,"level":"debug","foo":"bar","message":"some debug message"}
```
#### Logging without Level or Message
You may choose to log without a specific level by using the `Log` method. You may also write without a message by setting an empty string in the `msg string` parameter of the `Msg` method. Both are demonstrated in the example below.
```go
package main
import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
func main() {
zerolog.TimeFieldFormat = ""
log.Log().
Str("foo", "bar").
Msg("")
}
// Output: {"time":1494567715,"foo":"bar"}
```
#### Logging Fatal Messages
```go
@ -168,21 +226,9 @@ func main() {
// Output: {"time":1516133263,"level":"fatal","error":"A repo man spends his life getting into tense situations","service":"myservice","message":"Cannot start myservice"}
// exit status 1
```
> NOTE: Using `Msgf` generates one allocation even when the logger is disabled.
### Contextual Logging
#### Fields can be added to log messages
```go
log.Info().
Str("foo", "bar").
Int("n", 123).
Msg("hello world")
// Output: {"level":"info","time":1494567715,"foo":"bar","n":123,"message":"hello world"}
```
### Create logger instance to manage different outputs
```go
@ -197,7 +243,7 @@ logger.Info().Str("foo", "bar").Msg("hello world")
```go
sublogger := log.With().
Str("component": "foo").
Str("component", "foo").
Logger()
sublogger.Info().Msg("hello world")
@ -206,14 +252,38 @@ sublogger.Info().Msg("hello world")
### Pretty logging
To log a human-friendly, colorized output, use `zerolog.ConsoleWriter`:
```go
if isConsole {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
}
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
log.Info().Str("foo", "bar").Msg("Hello world")
// Output: 1494567715 |INFO| Hello world foo=bar
// Output: 3:04PM INF Hello World foo=bar
```
To customize the configuration and formatting:
```go
output := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}
output.FormatLevel = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("| %-6s|", i))
}
output.FormatMessage = func(i interface{}) string {
return fmt.Sprintf("***%s****", i)
}
output.FormatFieldName = func(i interface{}) string {
return fmt.Sprintf("%s:", i)
}
output.FormatFieldValue = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("%s", i))
}
log := zerolog.New(output).With().Timestamp().Logger()
log.Info().Str("foo", "bar").Msg("Hello World")
// Output: 2006-01-02T15:04:05Z07:00 | INFO | ***Hello World**** foo:BAR
```
### Sub dictionary
@ -223,7 +293,7 @@ log.Info().
Str("foo", "bar").
Dict("dict", zerolog.Dict().
Str("bar", "baz").
Int("n", 1)
Int("n", 1),
).Msg("hello world")
// Output: {"level":"info","time":1494567715,"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"}
@ -241,29 +311,30 @@ log.Info().Msg("hello world")
// Output: {"l":"info","t":1494567715,"m":"hello world"}
```
### Log with no level nor message
```go
log.Log().Str("foo","bar").Msg("")
// Output: {"time":1494567715,"foo":"bar"}
```
### Add contextual fields to the global logger
```go
log.Logger = log.With().Str("foo", "bar").Logger()
```
### Add file and line number to log
```go
log.Logger = log.With().Caller().Logger()
log.Info().Msg("hello world")
// Output: {"level": "info", "message": "hello world", "caller": "/go/src/your_project/some_file:21"}
```
### Thread-safe, lock-free, non-blocking writer
If your writer might be slow or not thread-safe and you need your log producers to never get slowed down by a slow writer, you can use a `diode.Writer` as follow:
```go
d := diodes.NewManyToOne(1000, diodes.AlertFunc(func(missed int) {
fmt.Printf("Dropped %d messages\n", missed)
}))
w := diode.NewWriter(os.Stdout, d, 10*time.Millisecond)
wr := diode.NewWriter(os.Stdout, 1000, 10*time.Millisecond, func(missed int) {
fmt.Printf("Logger Dropped %d messages", missed)
})
log := zerolog.New(w)
log.Print("test")
```
@ -317,7 +388,7 @@ hooked.Warn().Msg("")
### Pass a sub-logger by context
```go
ctx := log.With("component", "module").Logger().WithContext(ctx)
ctx := log.With().Str("component", "module").Logger().WithContext(ctx)
log.Ctx(ctx).Info().Msg("hello world")
@ -397,7 +468,7 @@ if err := http.ListenAndServe(":8080", nil); err != nil {
Some settings can be changed and will by applied to all loggers:
* `log.Logger`: You can set this value to customize the global logger (the one used by package level methods).
* `zerolog.SetGlobalLevel`: Can raise the minimum level of all loggers. Set this to `zerolog.Disable` to disable logging altogether (quiet mode).
* `zerolog.SetGlobalLevel`: Can raise the minimum level of all loggers. Set this to `zerolog.Disabled` to disable logging altogether (quiet mode).
* `zerolog.DisableSampling`: If argument is `true`, all sampled loggers will stop sampling and issue 100% of their log events.
* `zerolog.TimestampFieldName`: Can be set to customize `Timestamp` field name.
* `zerolog.LevelFieldName`: Can be set to customize level field name.
@ -408,6 +479,7 @@ Some settings can be changed and will by applied to all loggers:
// using the Dur method.
* `DurationFieldUnit`: Sets the unit of the fields added by `Dur` (default: `time.Millisecond`).
* `DurationFieldInteger`: If set to true, `Dur` fields are formatted as integers instead of floats.
* `ErrorHandler`: Called whenever zerolog fails to write an event on its output. If not set, an error is printed on the stderr. This handler must be thread safe and non-blocking.
## Field Types
@ -430,17 +502,26 @@ Some settings can be changed and will by applied to all loggers:
## Binary Encoding
In addition to the default JSON encoding, `zerolog` can produce binary logs using the [cbor](http://cbor.io) encoding. The choice of encoding can be decided at compile time using the build tag `binary_log` as follow:
In addition to the default JSON encoding, `zerolog` can produce binary logs using [CBOR](http://cbor.io) encoding. The choice of encoding can be decided at compile time using the build tag `binary_log` as follows:
```
```bash
go build -tags binary_log .
```
To Decode binary encoded log files you can use any CBOR decoder. One has been tested to work
with zerolog library is [CSD](https://github.com/toravir/csd/).
## Related Projects
* [grpc-zerolog](https://github.com/cheapRoc/grpc-zerolog): Implementation of `grpclog.LoggerV2` interface using `zerolog`
## Benchmarks
See [logbench](http://hackemist.com/logbench/) for more comprehensive and up-to-date benchmarks.
All operations are allocation free (those numbers *include* JSON encoding):
```
```text
BenchmarkLogEmpty-8 100000000 19.1 ns/op 0 B/op 0 allocs/op
BenchmarkDisabled-8 500000000 4.07 ns/op 0 B/op 0 allocs/op
BenchmarkInfo-8 30000000 42.5 ns/op 0 B/op 0 allocs/op
@ -450,8 +531,8 @@ BenchmarkLogFields-8 10000000 184 ns/op 0 B/op 0 allocs/op
There are a few Go logging benchmarks and comparisons that include zerolog.
- [imkira/go-loggers-bench](https://github.com/imkira/go-loggers-bench)
- [uber-common/zap](https://github.com/uber-go/zap#performance)
* [imkira/go-loggers-bench](https://github.com/imkira/go-loggers-bench)
* [uber-common/zap](https://github.com/uber-go/zap#performance)
Using Uber's zap comparison benchmark:

142
vendor/github.com/rs/zerolog/array.go generated vendored
View File

@ -1,6 +1,7 @@
package zerolog
import (
"net"
"sync"
"time"
)
@ -19,6 +20,20 @@ type Array struct {
buf []byte
}
func putArray(a *Array) {
// Proper usage of a sync.Pool requires each entry to have approximately
// the same memory cost. To obtain this property when the stored type
// contains a variably-sized buffer, we add a hard limit on the maximum buffer
// to place back in the pool.
//
// See https://golang.org/issue/23199
const maxSize = 1 << 16 // 64KiB
if cap(a.buf) > maxSize {
return
}
arrayPool.Put(a)
}
// Arr creates an array to be added to an Event or Context.
func Arr() *Array {
a := arrayPool.Get().(*Array)
@ -32,145 +47,178 @@ func (*Array) MarshalZerologArray(*Array) {
}
func (a *Array) write(dst []byte) []byte {
dst = appendArrayStart(dst)
dst = enc.AppendArrayStart(dst)
if len(a.buf) > 0 {
dst = append(append(dst, a.buf...))
}
dst = appendArrayEnd(dst)
arrayPool.Put(a)
dst = enc.AppendArrayEnd(dst)
putArray(a)
return dst
}
// Object marshals an object that implement the LogObjectMarshaler
// interface and append it to the array.
// interface and append append it to the array.
func (a *Array) Object(obj LogObjectMarshaler) *Array {
e := Dict()
obj.MarshalZerologObject(e)
e.buf = appendEndMarker(e.buf)
a.buf = append(appendArrayDelim(a.buf), e.buf...)
eventPool.Put(e)
e.buf = enc.AppendEndMarker(e.buf)
a.buf = append(enc.AppendArrayDelim(a.buf), e.buf...)
putEvent(e)
return a
}
// Str append the val as a string to the array.
// Str append append the val as a string to the array.
func (a *Array) Str(val string) *Array {
a.buf = appendString(appendArrayDelim(a.buf), val)
a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), val)
return a
}
// Bytes append the val as a string to the array.
// Bytes append append the val as a string to the array.
func (a *Array) Bytes(val []byte) *Array {
a.buf = appendBytes(appendArrayDelim(a.buf), val)
a.buf = enc.AppendBytes(enc.AppendArrayDelim(a.buf), val)
return a
}
// Hex append the val as a hex string to the array.
// Hex append append the val as a hex string to the array.
func (a *Array) Hex(val []byte) *Array {
a.buf = appendHex(appendArrayDelim(a.buf), val)
a.buf = enc.AppendHex(enc.AppendArrayDelim(a.buf), val)
return a
}
// Err append the err as a string to the array.
// Err serializes and appends the err to the array.
func (a *Array) Err(err error) *Array {
a.buf = appendError(appendArrayDelim(a.buf), err)
marshaled := ErrorMarshalFunc(err)
switch m := marshaled.(type) {
case LogObjectMarshaler:
e := newEvent(nil, 0)
e.buf = e.buf[:0]
e.appendObject(m)
a.buf = append(enc.AppendArrayDelim(a.buf), e.buf...)
putEvent(e)
case error:
a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), m.Error())
case string:
a.buf = enc.AppendString(enc.AppendArrayDelim(a.buf), m)
default:
a.buf = enc.AppendInterface(enc.AppendArrayDelim(a.buf), m)
}
return a
}
// Bool append the val as a bool to the array.
// Bool append append the val as a bool to the array.
func (a *Array) Bool(b bool) *Array {
a.buf = appendBool(appendArrayDelim(a.buf), b)
a.buf = enc.AppendBool(enc.AppendArrayDelim(a.buf), b)
return a
}
// Int append i as a int to the array.
// Int append append i as a int to the array.
func (a *Array) Int(i int) *Array {
a.buf = appendInt(appendArrayDelim(a.buf), i)
a.buf = enc.AppendInt(enc.AppendArrayDelim(a.buf), i)
return a
}
// Int8 append i as a int8 to the array.
// Int8 append append i as a int8 to the array.
func (a *Array) Int8(i int8) *Array {
a.buf = appendInt8(appendArrayDelim(a.buf), i)
a.buf = enc.AppendInt8(enc.AppendArrayDelim(a.buf), i)
return a
}
// Int16 append i as a int16 to the array.
// Int16 append append i as a int16 to the array.
func (a *Array) Int16(i int16) *Array {
a.buf = appendInt16(appendArrayDelim(a.buf), i)
a.buf = enc.AppendInt16(enc.AppendArrayDelim(a.buf), i)
return a
}
// Int32 append i as a int32 to the array.
// Int32 append append i as a int32 to the array.
func (a *Array) Int32(i int32) *Array {
a.buf = appendInt32(appendArrayDelim(a.buf), i)
a.buf = enc.AppendInt32(enc.AppendArrayDelim(a.buf), i)
return a
}
// Int64 append i as a int64 to the array.
// Int64 append append i as a int64 to the array.
func (a *Array) Int64(i int64) *Array {
a.buf = appendInt64(appendArrayDelim(a.buf), i)
a.buf = enc.AppendInt64(enc.AppendArrayDelim(a.buf), i)
return a
}
// Uint append i as a uint to the array.
// Uint append append i as a uint to the array.
func (a *Array) Uint(i uint) *Array {
a.buf = appendUint(appendArrayDelim(a.buf), i)
a.buf = enc.AppendUint(enc.AppendArrayDelim(a.buf), i)
return a
}
// Uint8 append i as a uint8 to the array.
// Uint8 append append i as a uint8 to the array.
func (a *Array) Uint8(i uint8) *Array {
a.buf = appendUint8(appendArrayDelim(a.buf), i)
a.buf = enc.AppendUint8(enc.AppendArrayDelim(a.buf), i)
return a
}
// Uint16 append i as a uint16 to the array.
// Uint16 append append i as a uint16 to the array.
func (a *Array) Uint16(i uint16) *Array {
a.buf = appendUint16(appendArrayDelim(a.buf), i)
a.buf = enc.AppendUint16(enc.AppendArrayDelim(a.buf), i)
return a
}
// Uint32 append i as a uint32 to the array.
// Uint32 append append i as a uint32 to the array.
func (a *Array) Uint32(i uint32) *Array {
a.buf = appendUint32(appendArrayDelim(a.buf), i)
a.buf = enc.AppendUint32(enc.AppendArrayDelim(a.buf), i)
return a
}
// Uint64 append i as a uint64 to the array.
// Uint64 append append i as a uint64 to the array.
func (a *Array) Uint64(i uint64) *Array {
a.buf = appendUint64(appendArrayDelim(a.buf), i)
a.buf = enc.AppendUint64(enc.AppendArrayDelim(a.buf), i)
return a
}
// Float32 append f as a float32 to the array.
// Float32 append append f as a float32 to the array.
func (a *Array) Float32(f float32) *Array {
a.buf = appendFloat32(appendArrayDelim(a.buf), f)
a.buf = enc.AppendFloat32(enc.AppendArrayDelim(a.buf), f)
return a
}
// Float64 append f as a float64 to the array.
// Float64 append append f as a float64 to the array.
func (a *Array) Float64(f float64) *Array {
a.buf = appendFloat64(appendArrayDelim(a.buf), f)
a.buf = enc.AppendFloat64(enc.AppendArrayDelim(a.buf), f)
return a
}
// Time append t formated as string using zerolog.TimeFieldFormat.
// Time append append t formated as string using zerolog.TimeFieldFormat.
func (a *Array) Time(t time.Time) *Array {
a.buf = appendTime(appendArrayDelim(a.buf), t, TimeFieldFormat)
a.buf = enc.AppendTime(enc.AppendArrayDelim(a.buf), t, TimeFieldFormat)
return a
}
// Dur append d to the array.
// Dur append append d to the array.
func (a *Array) Dur(d time.Duration) *Array {
a.buf = appendDuration(appendArrayDelim(a.buf), d, DurationFieldUnit, DurationFieldInteger)
a.buf = enc.AppendDuration(enc.AppendArrayDelim(a.buf), d, DurationFieldUnit, DurationFieldInteger)
return a
}
// Interface append i marshaled using reflection.
// Interface append append i marshaled using reflection.
func (a *Array) Interface(i interface{}) *Array {
if obj, ok := i.(LogObjectMarshaler); ok {
return a.Object(obj)
}
a.buf = appendInterface(appendArrayDelim(a.buf), i)
a.buf = enc.AppendInterface(enc.AppendArrayDelim(a.buf), i)
return a
}
// IPAddr adds IPv4 or IPv6 address to the array
func (a *Array) IPAddr(ip net.IP) *Array {
a.buf = enc.AppendIPAddr(enc.AppendArrayDelim(a.buf), ip)
return a
}
// IPPrefix adds IPv4 or IPv6 Prefix (IP + mask) to the array
func (a *Array) IPPrefix(pfx net.IPNet) *Array {
a.buf = enc.AppendIPPrefix(enc.AppendArrayDelim(a.buf), pfx)
return a
}
// MACAddr adds a MAC (Ethernet) address to the array
func (a *Array) MACAddr(ha net.HardwareAddr) *Array {
a.buf = enc.AppendMACAddr(enc.AppendArrayDelim(a.buf), ha)
return a
}

View File

@ -5,116 +5,253 @@ import (
"encoding/json"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
)
const (
cReset = 0
cBold = 1
cRed = 31
cGreen = 32
cYellow = 33
cBlue = 34
cMagenta = 35
cCyan = 36
cGray = 37
cDarkGray = 90
colorBlack = iota + 30
colorRed
colorGreen
colorYellow
colorBlue
colorMagenta
colorCyan
colorWhite
colorBold = 1
colorDarkGray = 90
)
var consoleBufPool = sync.Pool{
var (
consoleBufPool = sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, 100))
},
}
}
)
// ConsoleWriter reads a JSON object per write operation and output an
// optionally colored human readable version on the Out writer.
const (
consoleDefaultTimeFormat = time.Kitchen
)
// Formatter transforms the input into a formatted string.
type Formatter func(interface{}) string
// ConsoleWriter parses the JSON input and writes it in an
// (optionally) colorized, human-friendly format to Out.
type ConsoleWriter struct {
// Out is the output destination.
Out io.Writer
// NoColor disables the colorized output.
NoColor bool
// TimeFormat specifies the format for timestamp in output.
TimeFormat string
// PartsOrder defines the order of parts in output.
PartsOrder []string
FormatTimestamp Formatter
FormatLevel Formatter
FormatCaller Formatter
FormatMessage Formatter
FormatFieldName Formatter
FormatFieldValue Formatter
FormatErrFieldName Formatter
FormatErrFieldValue Formatter
}
// NewConsoleWriter creates and initializes a new ConsoleWriter.
func NewConsoleWriter(options ...func(w *ConsoleWriter)) ConsoleWriter {
w := ConsoleWriter{
Out: os.Stdout,
TimeFormat: consoleDefaultTimeFormat,
PartsOrder: consoleDefaultPartsOrder(),
}
for _, opt := range options {
opt(&w)
}
return w
}
// Write transforms the JSON input with formatters and appends to w.Out.
func (w ConsoleWriter) Write(p []byte) (n int, err error) {
var event map[string]interface{}
if w.PartsOrder == nil {
w.PartsOrder = consoleDefaultPartsOrder()
}
var buf = consoleBufPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
consoleBufPool.Put(buf)
}()
var evt map[string]interface{}
p = decodeIfBinaryToBytes(p)
err = json.Unmarshal(p, &event)
d := json.NewDecoder(bytes.NewReader(p))
d.UseNumber()
err = d.Decode(&evt)
if err != nil {
return
return n, fmt.Errorf("cannot decode event: %s", err)
}
buf := consoleBufPool.Get().(*bytes.Buffer)
defer consoleBufPool.Put(buf)
lvlColor := cReset
level := "????"
if l, ok := event[LevelFieldName].(string); ok {
if !w.NoColor {
lvlColor = levelColor(l)
for _, p := range w.PartsOrder {
w.writePart(buf, evt, p)
}
level = strings.ToUpper(l)[0:4]
w.writeFields(evt, buf)
err = buf.WriteByte('\n')
if err != nil {
return n, err
}
fmt.Fprintf(buf, "%s |%s| %s",
colorize(event[TimestampFieldName], cDarkGray, !w.NoColor),
colorize(level, lvlColor, !w.NoColor),
colorize(event[MessageFieldName], cReset, !w.NoColor))
fields := make([]string, 0, len(event))
for field := range event {
_, err = buf.WriteTo(w.Out)
return len(p), err
}
// writeFields appends formatted key-value pairs to buf.
func (w ConsoleWriter) writeFields(evt map[string]interface{}, buf *bytes.Buffer) {
var fields = make([]string, 0, len(evt))
for field := range evt {
switch field {
case LevelFieldName, TimestampFieldName, MessageFieldName:
case LevelFieldName, TimestampFieldName, MessageFieldName, CallerFieldName:
continue
}
fields = append(fields, field)
}
sort.Strings(fields)
if len(fields) > 0 {
buf.WriteByte(' ')
}
// Move the "error" field to the front
ei := sort.Search(len(fields), func(i int) bool { return fields[i] >= ErrorFieldName })
if ei < len(fields) && fields[ei] == ErrorFieldName {
fields[ei] = ""
fields = append([]string{ErrorFieldName}, fields...)
var xfields = make([]string, 0, len(fields))
for _, field := range fields {
fmt.Fprintf(buf, " %s=", colorize(field, cCyan, !w.NoColor))
switch value := event[field].(type) {
if field == "" { // Skip empty fields
continue
}
xfields = append(xfields, field)
}
fields = xfields
}
for i, field := range fields {
var fn Formatter
var fv Formatter
if field == ErrorFieldName {
if w.FormatErrFieldName == nil {
fn = consoleDefaultFormatErrFieldName(w.NoColor)
} else {
fn = w.FormatErrFieldName
}
if w.FormatErrFieldValue == nil {
fv = consoleDefaultFormatErrFieldValue(w.NoColor)
} else {
fv = w.FormatErrFieldValue
}
} else {
if w.FormatFieldName == nil {
fn = consoleDefaultFormatFieldName(w.NoColor)
} else {
fn = w.FormatFieldName
}
if w.FormatFieldValue == nil {
fv = consoleDefaultFormatFieldValue
} else {
fv = w.FormatFieldValue
}
}
buf.WriteString(fn(field))
switch fValue := evt[field].(type) {
case string:
if needsQuote(value) {
buf.WriteString(strconv.Quote(value))
if needsQuote(fValue) {
buf.WriteString(fv(strconv.Quote(fValue)))
} else {
buf.WriteString(value)
buf.WriteString(fv(fValue))
}
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64:
fmt.Fprint(buf, value)
case json.Number:
buf.WriteString(fv(fValue))
default:
b, err := json.Marshal(value)
b, err := json.Marshal(fValue)
if err != nil {
fmt.Fprintf(buf, "[error: %v]", err)
fmt.Fprintf(buf, colorize("[error: %v]", colorRed, w.NoColor), err)
} else {
fmt.Fprint(buf, string(b))
fmt.Fprint(buf, fv(b))
}
}
if i < len(fields)-1 { // Skip space for last field
buf.WriteByte(' ')
}
}
buf.WriteByte('\n')
buf.WriteTo(w.Out)
n = len(p)
return
}
func colorize(s interface{}, color int, enabled bool) string {
if !enabled {
return fmt.Sprintf("%v", s)
}
return fmt.Sprintf("\x1b[%dm%v\x1b[0m", color, s)
}
// writePart appends a formatted part to buf.
func (w ConsoleWriter) writePart(buf *bytes.Buffer, evt map[string]interface{}, p string) {
var f Formatter
func levelColor(level string) int {
switch level {
case "debug":
return cMagenta
case "info":
return cGreen
case "warn":
return cYellow
case "error", "fatal", "panic":
return cRed
switch p {
case LevelFieldName:
if w.FormatLevel == nil {
f = consoleDefaultFormatLevel(w.NoColor)
} else {
f = w.FormatLevel
}
case TimestampFieldName:
if w.FormatTimestamp == nil {
f = consoleDefaultFormatTimestamp(w.TimeFormat, w.NoColor)
} else {
f = w.FormatTimestamp
}
case MessageFieldName:
if w.FormatMessage == nil {
f = consoleDefaultFormatMessage
} else {
f = w.FormatMessage
}
case CallerFieldName:
if w.FormatCaller == nil {
f = consoleDefaultFormatCaller(w.NoColor)
} else {
f = w.FormatCaller
}
default:
return cReset
if w.FormatFieldValue == nil {
f = consoleDefaultFormatFieldValue
} else {
f = w.FormatFieldValue
}
}
var s = f(evt[p])
if len(s) > 0 {
buf.WriteString(s)
if p != w.PartsOrder[len(w.PartsOrder)-1] { // Skip space for last part
buf.WriteByte(' ')
}
}
}
// needsQuote returns true when the string s should be quoted in output.
func needsQuote(s string) bool {
for i := range s {
if s[i] < 0x20 || s[i] > 0x7e || s[i] == ' ' || s[i] == '\\' || s[i] == '"' {
@ -123,3 +260,114 @@ func needsQuote(s string) bool {
}
return false
}
// colorize returns the string s wrapped in ANSI code c, unless disabled is true.
func colorize(s interface{}, c int, disabled bool) string {
if disabled {
return fmt.Sprintf("%s", s)
}
return fmt.Sprintf("\x1b[%dm%v\x1b[0m", c, s)
}
// ----- DEFAULT FORMATTERS ---------------------------------------------------
func consoleDefaultPartsOrder() []string {
return []string{
TimestampFieldName,
LevelFieldName,
CallerFieldName,
MessageFieldName,
}
}
func consoleDefaultFormatTimestamp(timeFormat string, noColor bool) Formatter {
if timeFormat == "" {
timeFormat = consoleDefaultTimeFormat
}
return func(i interface{}) string {
t := "<nil>"
switch tt := i.(type) {
case string:
ts, err := time.Parse(TimeFieldFormat, tt)
if err != nil {
t = tt
} else {
t = ts.Format(timeFormat)
}
case json.Number:
t = tt.String()
}
return colorize(t, colorDarkGray, noColor)
}
}
func consoleDefaultFormatLevel(noColor bool) Formatter {
return func(i interface{}) string {
var l string
if ll, ok := i.(string); ok {
switch ll {
case "debug":
l = colorize("DBG", colorYellow, noColor)
case "info":
l = colorize("INF", colorGreen, noColor)
case "warn":
l = colorize("WRN", colorRed, noColor)
case "error":
l = colorize(colorize("ERR", colorRed, noColor), colorBold, noColor)
case "fatal":
l = colorize(colorize("FTL", colorRed, noColor), colorBold, noColor)
case "panic":
l = colorize(colorize("PNC", colorRed, noColor), colorBold, noColor)
default:
l = colorize("???", colorBold, noColor)
}
} else {
l = strings.ToUpper(fmt.Sprintf("%s", i))[0:3]
}
return l
}
}
func consoleDefaultFormatCaller(noColor bool) Formatter {
return func(i interface{}) string {
var c string
if cc, ok := i.(string); ok {
c = cc
}
if len(c) > 0 {
cwd, err := os.Getwd()
if err == nil {
c = strings.TrimPrefix(c, cwd)
c = strings.TrimPrefix(c, "/")
}
c = colorize(c, colorBold, noColor) + colorize(" >", colorCyan, noColor)
}
return c
}
}
func consoleDefaultFormatMessage(i interface{}) string {
return fmt.Sprintf("%s", i)
}
func consoleDefaultFormatFieldName(noColor bool) Formatter {
return func(i interface{}) string {
return colorize(fmt.Sprintf("%s=", i), colorCyan, noColor)
}
}
func consoleDefaultFormatFieldValue(i interface{}) string {
return fmt.Sprintf("%s", i)
}
func consoleDefaultFormatErrFieldName(noColor bool) Formatter {
return func(i interface{}) string {
return colorize(fmt.Sprintf("%s=", i), colorRed, noColor)
}
}
func consoleDefaultFormatErrFieldValue(noColor bool) Formatter {
return func(i interface{}) string {
return colorize(fmt.Sprintf("%s", i), colorRed, noColor)
}
}

View File

@ -2,6 +2,7 @@ package zerolog
import (
"io/ioutil"
"net"
"time"
)
@ -23,9 +24,9 @@ func (c Context) Fields(fields map[string]interface{}) Context {
// Dict adds the field key with the dict to the logger context.
func (c Context) Dict(key string, dict *Event) Context {
dict.buf = appendEndMarker(dict.buf)
c.l.context = append(appendKey(c.l.context, key), dict.buf...)
eventPool.Put(dict)
dict.buf = enc.AppendEndMarker(dict.buf)
c.l.context = append(enc.AppendKey(c.l.context, key), dict.buf...)
putEvent(dict)
return c
}
@ -33,7 +34,7 @@ func (c Context) Dict(key string, dict *Event) Context {
// Use zerolog.Arr() to create the array or pass a type that
// implement the LogArrayMarshaler interface.
func (c Context) Array(key string, arr LogArrayMarshaler) Context {
c.l.context = appendKey(c.l.context, key)
c.l.context = enc.AppendKey(c.l.context, key)
if arr, ok := arr.(*Array); ok {
c.l.context = arr.write(c.l.context)
return c
@ -51,34 +52,43 @@ func (c Context) Array(key string, arr LogArrayMarshaler) Context {
// Object marshals an object that implement the LogObjectMarshaler interface.
func (c Context) Object(key string, obj LogObjectMarshaler) Context {
e := newEvent(levelWriterAdapter{ioutil.Discard}, 0, true)
e := newEvent(levelWriterAdapter{ioutil.Discard}, 0)
e.Object(key, obj)
c.l.context = appendObjectData(c.l.context, e.buf)
eventPool.Put(e)
c.l.context = enc.AppendObjectData(c.l.context, e.buf)
putEvent(e)
return c
}
// EmbedObject marshals and Embeds an object that implement the LogObjectMarshaler interface.
func (c Context) EmbedObject(obj LogObjectMarshaler) Context {
e := newEvent(levelWriterAdapter{ioutil.Discard}, 0)
e.EmbedObject(obj)
c.l.context = enc.AppendObjectData(c.l.context, e.buf)
putEvent(e)
return c
}
// Str adds the field key with val as a string to the logger context.
func (c Context) Str(key, val string) Context {
c.l.context = appendString(appendKey(c.l.context, key), val)
c.l.context = enc.AppendString(enc.AppendKey(c.l.context, key), val)
return c
}
// Strs adds the field key with val as a string to the logger context.
func (c Context) Strs(key string, vals []string) Context {
c.l.context = appendStrings(appendKey(c.l.context, key), vals)
c.l.context = enc.AppendStrings(enc.AppendKey(c.l.context, key), vals)
return c
}
// Bytes adds the field key with val as a []byte to the logger context.
func (c Context) Bytes(key string, val []byte) Context {
c.l.context = appendBytes(appendKey(c.l.context, key), val)
c.l.context = enc.AppendBytes(enc.AppendKey(c.l.context, key), val)
return c
}
// Hex adds the field key with val as a hex string to the logger context.
func (c Context) Hex(key string, val []byte) Context {
c.l.context = appendHex(appendKey(c.l.context, key), val)
c.l.context = enc.AppendHex(enc.AppendKey(c.l.context, key), val)
return c
}
@ -87,186 +97,206 @@ func (c Context) Hex(key string, val []byte) Context {
// No sanity check is performed on b; it must not contain carriage returns and
// be valid JSON.
func (c Context) RawJSON(key string, b []byte) Context {
c.l.context = appendJSON(appendKey(c.l.context, key), b)
c.l.context = appendJSON(enc.AppendKey(c.l.context, key), b)
return c
}
// AnErr adds the field key with err as a string to the logger context.
// AnErr adds the field key with serialized err to the logger context.
func (c Context) AnErr(key string, err error) Context {
if err != nil {
c.l.context = appendError(appendKey(c.l.context, key), err)
}
marshaled := ErrorMarshalFunc(err)
switch m := marshaled.(type) {
case nil:
return c
case LogObjectMarshaler:
return c.Object(key, m)
case error:
return c.Str(key, m.Error())
case string:
return c.Str(key, m)
default:
return c.Interface(key, m)
}
}
// Errs adds the field key with errs as an array of strings to the logger context.
// Errs adds the field key with errs as an array of serialized errors to the
// logger context.
func (c Context) Errs(key string, errs []error) Context {
c.l.context = appendErrors(appendKey(c.l.context, key), errs)
return c
arr := Arr()
for _, err := range errs {
marshaled := ErrorMarshalFunc(err)
switch m := marshaled.(type) {
case LogObjectMarshaler:
arr = arr.Object(m)
case error:
arr = arr.Str(m.Error())
case string:
arr = arr.Str(m)
default:
arr = arr.Interface(m)
}
}
return c.Array(key, arr)
}
// Err adds the field "error" with err as a string to the logger context.
// To customize the key name, change zerolog.ErrorFieldName.
// Err adds the field "error" with serialized err to the logger context.
func (c Context) Err(err error) Context {
if err != nil {
c.l.context = appendError(appendKey(c.l.context, ErrorFieldName), err)
}
return c
return c.AnErr(ErrorFieldName, err)
}
// Bool adds the field key with val as a bool to the logger context.
func (c Context) Bool(key string, b bool) Context {
c.l.context = appendBool(appendKey(c.l.context, key), b)
c.l.context = enc.AppendBool(enc.AppendKey(c.l.context, key), b)
return c
}
// Bools adds the field key with val as a []bool to the logger context.
func (c Context) Bools(key string, b []bool) Context {
c.l.context = appendBools(appendKey(c.l.context, key), b)
c.l.context = enc.AppendBools(enc.AppendKey(c.l.context, key), b)
return c
}
// Int adds the field key with i as a int to the logger context.
func (c Context) Int(key string, i int) Context {
c.l.context = appendInt(appendKey(c.l.context, key), i)
c.l.context = enc.AppendInt(enc.AppendKey(c.l.context, key), i)
return c
}
// Ints adds the field key with i as a []int to the logger context.
func (c Context) Ints(key string, i []int) Context {
c.l.context = appendInts(appendKey(c.l.context, key), i)
c.l.context = enc.AppendInts(enc.AppendKey(c.l.context, key), i)
return c
}
// Int8 adds the field key with i as a int8 to the logger context.
func (c Context) Int8(key string, i int8) Context {
c.l.context = appendInt8(appendKey(c.l.context, key), i)
c.l.context = enc.AppendInt8(enc.AppendKey(c.l.context, key), i)
return c
}
// Ints8 adds the field key with i as a []int8 to the logger context.
func (c Context) Ints8(key string, i []int8) Context {
c.l.context = appendInts8(appendKey(c.l.context, key), i)
c.l.context = enc.AppendInts8(enc.AppendKey(c.l.context, key), i)
return c
}
// Int16 adds the field key with i as a int16 to the logger context.
func (c Context) Int16(key string, i int16) Context {
c.l.context = appendInt16(appendKey(c.l.context, key), i)
c.l.context = enc.AppendInt16(enc.AppendKey(c.l.context, key), i)
return c
}
// Ints16 adds the field key with i as a []int16 to the logger context.
func (c Context) Ints16(key string, i []int16) Context {
c.l.context = appendInts16(appendKey(c.l.context, key), i)
c.l.context = enc.AppendInts16(enc.AppendKey(c.l.context, key), i)
return c
}
// Int32 adds the field key with i as a int32 to the logger context.
func (c Context) Int32(key string, i int32) Context {
c.l.context = appendInt32(appendKey(c.l.context, key), i)
c.l.context = enc.AppendInt32(enc.AppendKey(c.l.context, key), i)
return c
}
// Ints32 adds the field key with i as a []int32 to the logger context.
func (c Context) Ints32(key string, i []int32) Context {
c.l.context = appendInts32(appendKey(c.l.context, key), i)
c.l.context = enc.AppendInts32(enc.AppendKey(c.l.context, key), i)
return c
}
// Int64 adds the field key with i as a int64 to the logger context.
func (c Context) Int64(key string, i int64) Context {
c.l.context = appendInt64(appendKey(c.l.context, key), i)
c.l.context = enc.AppendInt64(enc.AppendKey(c.l.context, key), i)
return c
}
// Ints64 adds the field key with i as a []int64 to the logger context.
func (c Context) Ints64(key string, i []int64) Context {
c.l.context = appendInts64(appendKey(c.l.context, key), i)
c.l.context = enc.AppendInts64(enc.AppendKey(c.l.context, key), i)
return c
}
// Uint adds the field key with i as a uint to the logger context.
func (c Context) Uint(key string, i uint) Context {
c.l.context = appendUint(appendKey(c.l.context, key), i)
c.l.context = enc.AppendUint(enc.AppendKey(c.l.context, key), i)
return c
}
// Uints adds the field key with i as a []uint to the logger context.
func (c Context) Uints(key string, i []uint) Context {
c.l.context = appendUints(appendKey(c.l.context, key), i)
c.l.context = enc.AppendUints(enc.AppendKey(c.l.context, key), i)
return c
}
// Uint8 adds the field key with i as a uint8 to the logger context.
func (c Context) Uint8(key string, i uint8) Context {
c.l.context = appendUint8(appendKey(c.l.context, key), i)
c.l.context = enc.AppendUint8(enc.AppendKey(c.l.context, key), i)
return c
}
// Uints8 adds the field key with i as a []uint8 to the logger context.
func (c Context) Uints8(key string, i []uint8) Context {
c.l.context = appendUints8(appendKey(c.l.context, key), i)
c.l.context = enc.AppendUints8(enc.AppendKey(c.l.context, key), i)
return c
}
// Uint16 adds the field key with i as a uint16 to the logger context.
func (c Context) Uint16(key string, i uint16) Context {
c.l.context = appendUint16(appendKey(c.l.context, key), i)
c.l.context = enc.AppendUint16(enc.AppendKey(c.l.context, key), i)
return c
}
// Uints16 adds the field key with i as a []uint16 to the logger context.
func (c Context) Uints16(key string, i []uint16) Context {
c.l.context = appendUints16(appendKey(c.l.context, key), i)
c.l.context = enc.AppendUints16(enc.AppendKey(c.l.context, key), i)
return c
}
// Uint32 adds the field key with i as a uint32 to the logger context.
func (c Context) Uint32(key string, i uint32) Context {
c.l.context = appendUint32(appendKey(c.l.context, key), i)
c.l.context = enc.AppendUint32(enc.AppendKey(c.l.context, key), i)
return c
}
// Uints32 adds the field key with i as a []uint32 to the logger context.
func (c Context) Uints32(key string, i []uint32) Context {
c.l.context = appendUints32(appendKey(c.l.context, key), i)
c.l.context = enc.AppendUints32(enc.AppendKey(c.l.context, key), i)
return c
}
// Uint64 adds the field key with i as a uint64 to the logger context.
func (c Context) Uint64(key string, i uint64) Context {
c.l.context = appendUint64(appendKey(c.l.context, key), i)
c.l.context = enc.AppendUint64(enc.AppendKey(c.l.context, key), i)
return c
}
// Uints64 adds the field key with i as a []uint64 to the logger context.
func (c Context) Uints64(key string, i []uint64) Context {
c.l.context = appendUints64(appendKey(c.l.context, key), i)
c.l.context = enc.AppendUints64(enc.AppendKey(c.l.context, key), i)
return c
}
// Float32 adds the field key with f as a float32 to the logger context.
func (c Context) Float32(key string, f float32) Context {
c.l.context = appendFloat32(appendKey(c.l.context, key), f)
c.l.context = enc.AppendFloat32(enc.AppendKey(c.l.context, key), f)
return c
}
// Floats32 adds the field key with f as a []float32 to the logger context.
func (c Context) Floats32(key string, f []float32) Context {
c.l.context = appendFloats32(appendKey(c.l.context, key), f)
c.l.context = enc.AppendFloats32(enc.AppendKey(c.l.context, key), f)
return c
}
// Float64 adds the field key with f as a float64 to the logger context.
func (c Context) Float64(key string, f float64) Context {
c.l.context = appendFloat64(appendKey(c.l.context, key), f)
c.l.context = enc.AppendFloat64(enc.AppendKey(c.l.context, key), f)
return c
}
// Floats64 adds the field key with f as a []float64 to the logger context.
func (c Context) Floats64(key string, f []float64) Context {
c.l.context = appendFloats64(appendKey(c.l.context, key), f)
c.l.context = enc.AppendFloats64(enc.AppendKey(c.l.context, key), f)
return c
}
@ -289,38 +319,39 @@ func (c Context) Timestamp() Context {
// Time adds the field key with t formated as string using zerolog.TimeFieldFormat.
func (c Context) Time(key string, t time.Time) Context {
c.l.context = appendTime(appendKey(c.l.context, key), t, TimeFieldFormat)
c.l.context = enc.AppendTime(enc.AppendKey(c.l.context, key), t, TimeFieldFormat)
return c
}
// Times adds the field key with t formated as string using zerolog.TimeFieldFormat.
func (c Context) Times(key string, t []time.Time) Context {
c.l.context = appendTimes(appendKey(c.l.context, key), t, TimeFieldFormat)
c.l.context = enc.AppendTimes(enc.AppendKey(c.l.context, key), t, TimeFieldFormat)
return c
}
// Dur adds the fields key with d divided by unit and stored as a float.
func (c Context) Dur(key string, d time.Duration) Context {
c.l.context = appendDuration(appendKey(c.l.context, key), d, DurationFieldUnit, DurationFieldInteger)
c.l.context = enc.AppendDuration(enc.AppendKey(c.l.context, key), d, DurationFieldUnit, DurationFieldInteger)
return c
}
// Durs adds the fields key with d divided by unit and stored as a float.
func (c Context) Durs(key string, d []time.Duration) Context {
c.l.context = appendDurations(appendKey(c.l.context, key), d, DurationFieldUnit, DurationFieldInteger)
c.l.context = enc.AppendDurations(enc.AppendKey(c.l.context, key), d, DurationFieldUnit, DurationFieldInteger)
return c
}
// Interface adds the field key with obj marshaled using reflection.
func (c Context) Interface(key string, i interface{}) Context {
c.l.context = appendInterface(appendKey(c.l.context, key), i)
c.l.context = enc.AppendInterface(enc.AppendKey(c.l.context, key), i)
return c
}
type callerHook struct{}
func (ch callerHook) Run(e *Event, level Level, msg string) {
e.caller(4)
// Extra frames to skip (added by hook infra).
e.caller(CallerSkipFrameCount + contextCallerSkipFrameCount)
}
var ch = callerHook{}
@ -330,3 +361,35 @@ func (c Context) Caller() Context {
c.l = c.l.Hook(ch)
return c
}
type stackTraceHook struct{}
func (sh stackTraceHook) Run(e *Event, level Level, msg string) {
e.Stack()
}
var sh = stackTraceHook{}
// Stack enables stack trace printing for the error passed to Err().
func (c Context) Stack() Context {
c.l = c.l.Hook(sh)
return c
}
// IPAddr adds IPv4 or IPv6 Address to the context
func (c Context) IPAddr(key string, ip net.IP) Context {
c.l.context = enc.AppendIPAddr(enc.AppendKey(c.l.context, key), ip)
return c
}
// IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the context
func (c Context) IPPrefix(key string, pfx net.IPNet) Context {
c.l.context = enc.AppendIPPrefix(enc.AppendKey(c.l.context, key), pfx)
return c
}
// MACAddr adds MAC address to the context
func (c Context) MACAddr(key string, ha net.HardwareAddr) Context {
c.l.context = enc.AppendMACAddr(enc.AppendKey(c.l.context, key), ha)
return c
}

19
vendor/github.com/rs/zerolog/ctx.go generated vendored
View File

@ -2,38 +2,39 @@ package zerolog
import (
"context"
"io/ioutil"
)
var disabledLogger *Logger
func init() {
l := New(ioutil.Discard).Level(Disabled)
l := Nop()
disabledLogger = &l
}
type ctxKey struct{}
// WithContext returns a copy of ctx with l associated. If an instance of Logger
// is already in the context, the pointer to this logger is updated with l.
// is already in the context, the context is not updated.
//
// For instance, to add a field to an existing logger in the context, use this
// notation:
//
// ctx := r.Context()
// l := zerolog.Ctx(ctx)
// ctx = l.With().Str("foo", "bar").WithContext(ctx)
func (l Logger) WithContext(ctx context.Context) context.Context {
// l.UpdateContext(func(c Context) Context {
// return c.Str("bar", "baz")
// })
func (l *Logger) WithContext(ctx context.Context) context.Context {
if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok {
// Update existing pointer.
*lp = l
if lp == l {
// Do not store same logger.
return ctx
}
if l.level == Disabled {
} else if l.level == Disabled {
// Do not store disabled logger.
return ctx
}
return context.WithValue(ctx, ctxKey{}, &l)
return context.WithValue(ctx, ctxKey{}, l)
}
// Ctx returns the Logger associated with the ctx. If no logger

View File

@ -5,202 +5,19 @@ package zerolog
// This file contains bindings to do binary encoding.
import (
"time"
"github.com/rs/zerolog/internal/cbor"
)
func appendInterface(dst []byte, i interface{}) []byte {
return cbor.AppendInterface(dst, i)
}
var (
_ encoder = (*cbor.Encoder)(nil)
func appendKey(dst []byte, s string) []byte {
return cbor.AppendKey(dst, s)
}
func appendFloats64(dst []byte, f []float64) []byte {
return cbor.AppendFloats64(dst, f)
}
func appendFloat64(dst []byte, f float64) []byte {
return cbor.AppendFloat64(dst, f)
}
func appendFloats32(dst []byte, f []float32) []byte {
return cbor.AppendFloats32(dst, f)
}
func appendFloat32(dst []byte, f float32) []byte {
return cbor.AppendFloat32(dst, f)
}
func appendUints64(dst []byte, i []uint64) []byte {
return cbor.AppendUints64(dst, i)
}
func appendUint64(dst []byte, i uint64) []byte {
return cbor.AppendUint64(dst, i)
}
func appendUints32(dst []byte, i []uint32) []byte {
return cbor.AppendUints32(dst, i)
}
func appendUint32(dst []byte, i uint32) []byte {
return cbor.AppendUint32(dst, i)
}
func appendUints16(dst []byte, i []uint16) []byte {
return cbor.AppendUints16(dst, i)
}
func appendUint16(dst []byte, i uint16) []byte {
return cbor.AppendUint16(dst, i)
}
func appendUints8(dst []byte, i []uint8) []byte {
return cbor.AppendUints8(dst, i)
}
func appendUint8(dst []byte, i uint8) []byte {
return cbor.AppendUint8(dst, i)
}
func appendUints(dst []byte, i []uint) []byte {
return cbor.AppendUints(dst, i)
}
func appendUint(dst []byte, i uint) []byte {
return cbor.AppendUint(dst, i)
}
func appendInts64(dst []byte, i []int64) []byte {
return cbor.AppendInts64(dst, i)
}
func appendInt64(dst []byte, i int64) []byte {
return cbor.AppendInt64(dst, i)
}
func appendInts32(dst []byte, i []int32) []byte {
return cbor.AppendInts32(dst, i)
}
func appendInt32(dst []byte, i int32) []byte {
return cbor.AppendInt32(dst, i)
}
func appendInts16(dst []byte, i []int16) []byte {
return cbor.AppendInts16(dst, i)
}
func appendInt16(dst []byte, i int16) []byte {
return cbor.AppendInt16(dst, i)
}
func appendInts8(dst []byte, i []int8) []byte {
return cbor.AppendInts8(dst, i)
}
func appendInt8(dst []byte, i int8) []byte {
return cbor.AppendInt8(dst, i)
}
func appendInts(dst []byte, i []int) []byte {
return cbor.AppendInts(dst, i)
}
func appendInt(dst []byte, i int) []byte {
return cbor.AppendInt(dst, i)
}
func appendBools(dst []byte, b []bool) []byte {
return cbor.AppendBools(dst, b)
}
func appendBool(dst []byte, b bool) []byte {
return cbor.AppendBool(dst, b)
}
func appendError(dst []byte, e error) []byte {
return cbor.AppendError(dst, e)
}
func appendErrors(dst []byte, e []error) []byte {
return cbor.AppendErrors(dst, e)
}
func appendString(dst []byte, s string) []byte {
return cbor.AppendString(dst, s)
}
func appendStrings(dst []byte, s []string) []byte {
return cbor.AppendStrings(dst, s)
}
func appendDuration(dst []byte, t time.Duration, d time.Duration, fmt bool) []byte {
return cbor.AppendDuration(dst, t, d, fmt)
}
func appendDurations(dst []byte, t []time.Duration, d time.Duration, fmt bool) []byte {
return cbor.AppendDurations(dst, t, d, fmt)
}
func appendTimes(dst []byte, t []time.Time, fmt string) []byte {
return cbor.AppendTimes(dst, t, fmt)
}
func appendTime(dst []byte, t time.Time, fmt string) []byte {
return cbor.AppendTime(dst, t, fmt)
}
func appendEndMarker(dst []byte) []byte {
return cbor.AppendEndMarker(dst)
}
func appendLineBreak(dst []byte) []byte {
// No line breaks needed in binary format.
return dst
}
func appendBeginMarker(dst []byte) []byte {
return cbor.AppendBeginMarker(dst)
}
func appendBytes(dst []byte, b []byte) []byte {
return cbor.AppendBytes(dst, b)
}
func appendArrayStart(dst []byte) []byte {
return cbor.AppendArrayStart(dst)
}
func appendArrayEnd(dst []byte) []byte {
return cbor.AppendArrayEnd(dst)
}
func appendArrayDelim(dst []byte) []byte {
return cbor.AppendArrayDelim(dst)
}
func appendObjectData(dst []byte, src []byte) []byte {
// Map begin character is present in the src, which
// should not be copied when appending to existing data.
return cbor.AppendObjectData(dst, src[1:])
}
enc = cbor.Encoder{}
)
func appendJSON(dst []byte, j []byte) []byte {
return cbor.AppendEmbeddedJSON(dst, j)
}
func appendNil(dst []byte) []byte {
return cbor.AppendNull(dst)
}
func appendHex(dst []byte, val []byte) []byte {
return cbor.AppendHex(dst, val)
}
// decodeIfBinaryToString - converts a binary formatted log msg to a
// JSON formatted String Log message.
func decodeIfBinaryToString(in []byte) string {

View File

@ -6,199 +6,19 @@ package zerolog
// JSON encoded byte stream.
import (
"strconv"
"time"
"github.com/rs/zerolog/internal/json"
)
func appendInterface(dst []byte, i interface{}) []byte {
return json.AppendInterface(dst, i)
}
var (
_ encoder = (*json.Encoder)(nil)
func appendKey(dst []byte, s string) []byte {
return json.AppendKey(dst, s)
}
func appendFloats64(dst []byte, f []float64) []byte {
return json.AppendFloats64(dst, f)
}
func appendFloat64(dst []byte, f float64) []byte {
return json.AppendFloat64(dst, f)
}
func appendFloats32(dst []byte, f []float32) []byte {
return json.AppendFloats32(dst, f)
}
func appendFloat32(dst []byte, f float32) []byte {
return json.AppendFloat32(dst, f)
}
func appendUints64(dst []byte, i []uint64) []byte {
return json.AppendUints64(dst, i)
}
func appendUint64(dst []byte, i uint64) []byte {
return strconv.AppendUint(dst, uint64(i), 10)
}
func appendUints32(dst []byte, i []uint32) []byte {
return json.AppendUints32(dst, i)
}
func appendUint32(dst []byte, i uint32) []byte {
return strconv.AppendUint(dst, uint64(i), 10)
}
func appendUints16(dst []byte, i []uint16) []byte {
return json.AppendUints16(dst, i)
}
func appendUint16(dst []byte, i uint16) []byte {
return strconv.AppendUint(dst, uint64(i), 10)
}
func appendUints8(dst []byte, i []uint8) []byte {
return json.AppendUints8(dst, i)
}
func appendUint8(dst []byte, i uint8) []byte {
return strconv.AppendUint(dst, uint64(i), 10)
}
func appendUints(dst []byte, i []uint) []byte {
return json.AppendUints(dst, i)
}
func appendUint(dst []byte, i uint) []byte {
return strconv.AppendUint(dst, uint64(i), 10)
}
func appendInts64(dst []byte, i []int64) []byte {
return json.AppendInts64(dst, i)
}
func appendInt64(dst []byte, i int64) []byte {
return strconv.AppendInt(dst, int64(i), 10)
}
func appendInts32(dst []byte, i []int32) []byte {
return json.AppendInts32(dst, i)
}
func appendInt32(dst []byte, i int32) []byte {
return strconv.AppendInt(dst, int64(i), 10)
}
func appendInts16(dst []byte, i []int16) []byte {
return json.AppendInts16(dst, i)
}
func appendInt16(dst []byte, i int16) []byte {
return strconv.AppendInt(dst, int64(i), 10)
}
func appendInts8(dst []byte, i []int8) []byte {
return json.AppendInts8(dst, i)
}
func appendInt8(dst []byte, i int8) []byte {
return strconv.AppendInt(dst, int64(i), 10)
}
func appendInts(dst []byte, i []int) []byte {
return json.AppendInts(dst, i)
}
func appendInt(dst []byte, i int) []byte {
return strconv.AppendInt(dst, int64(i), 10)
}
func appendBools(dst []byte, b []bool) []byte {
return json.AppendBools(dst, b)
}
func appendBool(dst []byte, b bool) []byte {
return strconv.AppendBool(dst, b)
}
func appendError(dst []byte, e error) []byte {
return json.AppendError(dst, e)
}
func appendErrors(dst []byte, e []error) []byte {
return json.AppendErrors(dst, e)
}
func appendString(dst []byte, s string) []byte {
return json.AppendString(dst, s)
}
func appendStrings(dst []byte, s []string) []byte {
return json.AppendStrings(dst, s)
}
func appendDuration(dst []byte, t time.Duration, d time.Duration, fmt bool) []byte {
return json.AppendDuration(dst, t, d, fmt)
}
func appendDurations(dst []byte, t []time.Duration, d time.Duration, fmt bool) []byte {
return json.AppendDurations(dst, t, d, fmt)
}
func appendTimes(dst []byte, t []time.Time, fmt string) []byte {
return json.AppendTimes(dst, t, fmt)
}
func appendTime(dst []byte, t time.Time, fmt string) []byte {
return json.AppendTime(dst, t, fmt)
}
func appendEndMarker(dst []byte) []byte {
return append(dst, '}')
}
func appendLineBreak(dst []byte) []byte {
return append(dst, '\n')
}
func appendBeginMarker(dst []byte) []byte {
return append(dst, '{')
}
func appendBytes(dst []byte, b []byte) []byte {
return json.AppendBytes(dst, b)
}
func appendArrayStart(dst []byte) []byte {
return append(dst, '[')
}
func appendArrayEnd(dst []byte) []byte {
return append(dst, ']')
}
func appendArrayDelim(dst []byte) []byte {
if len(dst) > 0 {
return append(dst, ',')
}
return dst
}
func appendObjectData(dst []byte, src []byte) []byte {
return json.AppendObjectData(dst, src)
}
enc = json.Encoder{}
)
func appendJSON(dst []byte, j []byte) []byte {
return append(dst, j...)
}
func appendNil(dst []byte) []byte {
return append(dst, "null"...)
}
func decodeIfBinaryToString(in []byte) string {
return string(in)
}
@ -210,7 +30,3 @@ func decodeObjectToStr(in []byte) string {
func decodeIfBinaryToBytes(in []byte) []byte {
return in
}
func appendHex(in []byte, val []byte) []byte {
return json.AppendHex(in, val)
}

299
vendor/github.com/rs/zerolog/event.go generated vendored
View File

@ -2,9 +2,9 @@ package zerolog
import (
"fmt"
"net"
"os"
"runtime"
"strconv"
"sync"
"time"
)
@ -24,8 +24,22 @@ type Event struct {
w LevelWriter
level Level
done func(msg string)
stack bool // enable error stack trace
ch []Hook // hooks from context
h []Hook
}
func putEvent(e *Event) {
// Proper usage of a sync.Pool requires each entry to have approximately
// the same memory cost. To obtain this property when the stored type
// contains a variably-sized buffer, we add a hard limit on the maximum buffer
// to place back in the pool.
//
// See https://golang.org/issue/23199
const maxSize = 1 << 16 // 64KiB
if cap(e.buf) > maxSize {
return
}
eventPool.Put(e)
}
// LogObjectMarshaler provides a strongly-typed and encoding-agnostic interface
@ -40,14 +54,11 @@ type LogArrayMarshaler interface {
MarshalZerologArray(a *Array)
}
func newEvent(w LevelWriter, level Level, enabled bool) *Event {
if !enabled {
return &Event{}
}
func newEvent(w LevelWriter, level Level) *Event {
e := eventPool.Get().(*Event)
e.buf = e.buf[:0]
e.h = e.h[:0]
e.buf = appendBeginMarker(e.buf)
e.ch = nil
e.buf = enc.AppendBeginMarker(e.buf)
e.w = w
e.level = level
return e
@ -57,19 +68,30 @@ func (e *Event) write() (err error) {
if e == nil {
return nil
}
e.buf = appendEndMarker(e.buf)
e.buf = appendLineBreak(e.buf)
if e.level != Disabled {
e.buf = enc.AppendEndMarker(e.buf)
e.buf = enc.AppendLineBreak(e.buf)
if e.w != nil {
_, err = e.w.WriteLevel(e.level, e.buf)
}
eventPool.Put(e)
}
putEvent(e)
return
}
// Enabled return false if the *Event is going to be filtered out by
// log level or sampling.
func (e *Event) Enabled() bool {
return e != nil
return e != nil && e.level != Disabled
}
// Discard disables the event so Msg(f) won't print it.
func (e *Event) Discard() *Event {
if e == nil {
return e
}
e.level = Disabled
return nil
}
// Msg sends the *Event with msg added as the message field if not empty.
@ -80,31 +102,7 @@ func (e *Event) Msg(msg string) {
if e == nil {
return
}
if len(e.ch) > 0 {
e.ch[0].Run(e, e.level, msg)
if len(e.ch) > 1 {
for _, hook := range e.ch[1:] {
hook.Run(e, e.level, msg)
}
}
}
if len(e.h) > 0 {
e.h[0].Run(e, e.level, msg)
if len(e.h) > 1 {
for _, hook := range e.h[1:] {
hook.Run(e, e.level, msg)
}
}
}
if msg != "" {
e.buf = appendString(appendKey(e.buf, MessageFieldName), msg)
}
if e.done != nil {
defer e.done(msg)
}
if err := e.write(); err != nil {
fmt.Fprintf(os.Stderr, "zerolog: could not write event: %v", err)
}
e.msg(msg)
}
// Msgf sends the event with formated msg added as the message field if not empty.
@ -115,7 +113,31 @@ func (e *Event) Msgf(format string, v ...interface{}) {
if e == nil {
return
}
e.Msg(fmt.Sprintf(format, v...))
e.msg(fmt.Sprintf(format, v...))
}
func (e *Event) msg(msg string) {
if len(e.ch) > 0 {
e.ch[0].Run(e, e.level, msg)
if len(e.ch) > 1 {
for _, hook := range e.ch[1:] {
hook.Run(e, e.level, msg)
}
}
}
if msg != "" {
e.buf = enc.AppendString(enc.AppendKey(e.buf, MessageFieldName), msg)
}
if e.done != nil {
defer e.done(msg)
}
if err := e.write(); err != nil {
if ErrorHandler != nil {
ErrorHandler(err)
} else {
fmt.Fprintf(os.Stderr, "zerolog: could not write event: %v\n", err)
}
}
}
// Fields is a helper function to use a map to set fields using type assertion.
@ -133,9 +155,9 @@ func (e *Event) Dict(key string, dict *Event) *Event {
if e == nil {
return e
}
dict.buf = appendEndMarker(dict.buf)
e.buf = append(appendKey(e.buf, key), dict.buf...)
eventPool.Put(dict)
dict.buf = enc.AppendEndMarker(dict.buf)
e.buf = append(enc.AppendKey(e.buf, key), dict.buf...)
putEvent(dict)
return e
}
@ -143,7 +165,7 @@ func (e *Event) Dict(key string, dict *Event) *Event {
// Call usual field methods like Str, Int etc to add fields to this
// event and give it as argument the *Event.Dict method.
func Dict() *Event {
return newEvent(nil, 0, true)
return newEvent(nil, 0)
}
// Array adds the field key with an array to the event context.
@ -153,7 +175,7 @@ func (e *Event) Array(key string, arr LogArrayMarshaler) *Event {
if e == nil {
return e
}
e.buf = appendKey(e.buf, key)
e.buf = enc.AppendKey(e.buf, key)
var a *Array
if aa, ok := arr.(*Array); ok {
a = aa
@ -166,9 +188,9 @@ func (e *Event) Array(key string, arr LogArrayMarshaler) *Event {
}
func (e *Event) appendObject(obj LogObjectMarshaler) {
e.buf = appendBeginMarker(e.buf)
e.buf = enc.AppendBeginMarker(e.buf)
obj.MarshalZerologObject(e)
e.buf = appendEndMarker(e.buf)
e.buf = enc.AppendEndMarker(e.buf)
}
// Object marshals an object that implement the LogObjectMarshaler interface.
@ -176,17 +198,26 @@ func (e *Event) Object(key string, obj LogObjectMarshaler) *Event {
if e == nil {
return e
}
e.buf = appendKey(e.buf, key)
e.buf = enc.AppendKey(e.buf, key)
e.appendObject(obj)
return e
}
// Object marshals an object that implement the LogObjectMarshaler interface.
func (e *Event) EmbedObject(obj LogObjectMarshaler) *Event {
if e == nil {
return e
}
obj.MarshalZerologObject(e)
return e
}
// Str adds the field key with val as a string to the *Event context.
func (e *Event) Str(key, val string) *Event {
if e == nil {
return e
}
e.buf = appendString(appendKey(e.buf, key), val)
e.buf = enc.AppendString(enc.AppendKey(e.buf, key), val)
return e
}
@ -195,7 +226,7 @@ func (e *Event) Strs(key string, vals []string) *Event {
if e == nil {
return e
}
e.buf = appendStrings(appendKey(e.buf, key), vals)
e.buf = enc.AppendStrings(enc.AppendKey(e.buf, key), vals)
return e
}
@ -207,7 +238,7 @@ func (e *Event) Bytes(key string, val []byte) *Event {
if e == nil {
return e
}
e.buf = appendBytes(appendKey(e.buf, key), val)
e.buf = enc.AppendBytes(enc.AppendKey(e.buf, key), val)
return e
}
@ -216,7 +247,7 @@ func (e *Event) Hex(key string, val []byte) *Event {
if e == nil {
return e
}
e.buf = appendHex(appendKey(e.buf, key), val)
e.buf = enc.AppendHex(enc.AppendKey(e.buf, key), val)
return e
}
@ -228,41 +259,88 @@ func (e *Event) RawJSON(key string, b []byte) *Event {
if e == nil {
return e
}
e.buf = appendJSON(appendKey(e.buf, key), b)
e.buf = appendJSON(enc.AppendKey(e.buf, key), b)
return e
}
// AnErr adds the field key with err as a string to the *Event context.
// AnErr adds the field key with serialized err to the *Event context.
// If err is nil, no field is added.
func (e *Event) AnErr(key string, err error) *Event {
if e == nil {
return e
}
if err != nil {
e.buf = appendError(appendKey(e.buf, key), err)
}
switch m := ErrorMarshalFunc(err).(type) {
case nil:
return e
case LogObjectMarshaler:
return e.Object(key, m)
case error:
return e.Str(key, m.Error())
case string:
return e.Str(key, m)
default:
return e.Interface(key, m)
}
}
// Errs adds the field key with errs as an array of strings to the *Event context.
// If err is nil, no field is added.
// Errs adds the field key with errs as an array of serialized errors to the
// *Event context.
func (e *Event) Errs(key string, errs []error) *Event {
if e == nil {
return e
}
e.buf = appendErrors(appendKey(e.buf, key), errs)
return e
arr := Arr()
for _, err := range errs {
switch m := ErrorMarshalFunc(err).(type) {
case LogObjectMarshaler:
arr = arr.Object(m)
case error:
arr = arr.Err(m)
case string:
arr = arr.Str(m)
default:
arr = arr.Interface(m)
}
}
return e.Array(key, arr)
}
// Err adds the field "error" with err as a string to the *Event context.
// Err adds the field "error" with serialized err to the *Event context.
// If err is nil, no field is added.
// To customize the key name, change zerolog.ErrorFieldName.
//
// To customize the key name, change zerolog.ErrorFieldName.
//
// If Stack() has been called before and zerolog.ErrorStackMarshaler is defined,
// the err is passed to ErrorStackMarshaler and the result is appended to the
// zerolog.ErrorStackFieldName.
func (e *Event) Err(err error) *Event {
if e == nil {
return e
}
if err != nil {
e.buf = appendError(appendKey(e.buf, ErrorFieldName), err)
if e.stack && ErrorStackMarshaler != nil {
switch m := ErrorStackMarshaler(err).(type) {
case nil:
case LogObjectMarshaler:
e.Object(ErrorStackFieldName, m)
case error:
e.Str(ErrorStackFieldName, m.Error())
case string:
e.Str(ErrorStackFieldName, m)
default:
e.Interface(ErrorStackFieldName, m)
}
}
return e.AnErr(ErrorFieldName, err)
}
// Stack enables stack trace printing for the error passed to Err().
//
// ErrorStackMarshaler must be set for this method to do something.
func (e *Event) Stack() *Event {
if e != nil {
e.stack = true
}
return e
}
@ -272,7 +350,7 @@ func (e *Event) Bool(key string, b bool) *Event {
if e == nil {
return e
}
e.buf = appendBool(appendKey(e.buf, key), b)
e.buf = enc.AppendBool(enc.AppendKey(e.buf, key), b)
return e
}
@ -281,7 +359,7 @@ func (e *Event) Bools(key string, b []bool) *Event {
if e == nil {
return e
}
e.buf = appendBools(appendKey(e.buf, key), b)
e.buf = enc.AppendBools(enc.AppendKey(e.buf, key), b)
return e
}
@ -290,7 +368,7 @@ func (e *Event) Int(key string, i int) *Event {
if e == nil {
return e
}
e.buf = appendInt(appendKey(e.buf, key), i)
e.buf = enc.AppendInt(enc.AppendKey(e.buf, key), i)
return e
}
@ -299,7 +377,7 @@ func (e *Event) Ints(key string, i []int) *Event {
if e == nil {
return e
}
e.buf = appendInts(appendKey(e.buf, key), i)
e.buf = enc.AppendInts(enc.AppendKey(e.buf, key), i)
return e
}
@ -308,7 +386,7 @@ func (e *Event) Int8(key string, i int8) *Event {
if e == nil {
return e
}
e.buf = appendInt8(appendKey(e.buf, key), i)
e.buf = enc.AppendInt8(enc.AppendKey(e.buf, key), i)
return e
}
@ -317,7 +395,7 @@ func (e *Event) Ints8(key string, i []int8) *Event {
if e == nil {
return e
}
e.buf = appendInts8(appendKey(e.buf, key), i)
e.buf = enc.AppendInts8(enc.AppendKey(e.buf, key), i)
return e
}
@ -326,7 +404,7 @@ func (e *Event) Int16(key string, i int16) *Event {
if e == nil {
return e
}
e.buf = appendInt16(appendKey(e.buf, key), i)
e.buf = enc.AppendInt16(enc.AppendKey(e.buf, key), i)
return e
}
@ -335,7 +413,7 @@ func (e *Event) Ints16(key string, i []int16) *Event {
if e == nil {
return e
}
e.buf = appendInts16(appendKey(e.buf, key), i)
e.buf = enc.AppendInts16(enc.AppendKey(e.buf, key), i)
return e
}
@ -344,7 +422,7 @@ func (e *Event) Int32(key string, i int32) *Event {
if e == nil {
return e
}
e.buf = appendInt32(appendKey(e.buf, key), i)
e.buf = enc.AppendInt32(enc.AppendKey(e.buf, key), i)
return e
}
@ -353,7 +431,7 @@ func (e *Event) Ints32(key string, i []int32) *Event {
if e == nil {
return e
}
e.buf = appendInts32(appendKey(e.buf, key), i)
e.buf = enc.AppendInts32(enc.AppendKey(e.buf, key), i)
return e
}
@ -362,7 +440,7 @@ func (e *Event) Int64(key string, i int64) *Event {
if e == nil {
return e
}
e.buf = appendInt64(appendKey(e.buf, key), i)
e.buf = enc.AppendInt64(enc.AppendKey(e.buf, key), i)
return e
}
@ -371,7 +449,7 @@ func (e *Event) Ints64(key string, i []int64) *Event {
if e == nil {
return e
}
e.buf = appendInts64(appendKey(e.buf, key), i)
e.buf = enc.AppendInts64(enc.AppendKey(e.buf, key), i)
return e
}
@ -380,7 +458,7 @@ func (e *Event) Uint(key string, i uint) *Event {
if e == nil {
return e
}
e.buf = appendUint(appendKey(e.buf, key), i)
e.buf = enc.AppendUint(enc.AppendKey(e.buf, key), i)
return e
}
@ -389,7 +467,7 @@ func (e *Event) Uints(key string, i []uint) *Event {
if e == nil {
return e
}
e.buf = appendUints(appendKey(e.buf, key), i)
e.buf = enc.AppendUints(enc.AppendKey(e.buf, key), i)
return e
}
@ -398,7 +476,7 @@ func (e *Event) Uint8(key string, i uint8) *Event {
if e == nil {
return e
}
e.buf = appendUint8(appendKey(e.buf, key), i)
e.buf = enc.AppendUint8(enc.AppendKey(e.buf, key), i)
return e
}
@ -407,7 +485,7 @@ func (e *Event) Uints8(key string, i []uint8) *Event {
if e == nil {
return e
}
e.buf = appendUints8(appendKey(e.buf, key), i)
e.buf = enc.AppendUints8(enc.AppendKey(e.buf, key), i)
return e
}
@ -416,7 +494,7 @@ func (e *Event) Uint16(key string, i uint16) *Event {
if e == nil {
return e
}
e.buf = appendUint16(appendKey(e.buf, key), i)
e.buf = enc.AppendUint16(enc.AppendKey(e.buf, key), i)
return e
}
@ -425,7 +503,7 @@ func (e *Event) Uints16(key string, i []uint16) *Event {
if e == nil {
return e
}
e.buf = appendUints16(appendKey(e.buf, key), i)
e.buf = enc.AppendUints16(enc.AppendKey(e.buf, key), i)
return e
}
@ -434,7 +512,7 @@ func (e *Event) Uint32(key string, i uint32) *Event {
if e == nil {
return e
}
e.buf = appendUint32(appendKey(e.buf, key), i)
e.buf = enc.AppendUint32(enc.AppendKey(e.buf, key), i)
return e
}
@ -443,7 +521,7 @@ func (e *Event) Uints32(key string, i []uint32) *Event {
if e == nil {
return e
}
e.buf = appendUints32(appendKey(e.buf, key), i)
e.buf = enc.AppendUints32(enc.AppendKey(e.buf, key), i)
return e
}
@ -452,7 +530,7 @@ func (e *Event) Uint64(key string, i uint64) *Event {
if e == nil {
return e
}
e.buf = appendUint64(appendKey(e.buf, key), i)
e.buf = enc.AppendUint64(enc.AppendKey(e.buf, key), i)
return e
}
@ -461,7 +539,7 @@ func (e *Event) Uints64(key string, i []uint64) *Event {
if e == nil {
return e
}
e.buf = appendUints64(appendKey(e.buf, key), i)
e.buf = enc.AppendUints64(enc.AppendKey(e.buf, key), i)
return e
}
@ -470,7 +548,7 @@ func (e *Event) Float32(key string, f float32) *Event {
if e == nil {
return e
}
e.buf = appendFloat32(appendKey(e.buf, key), f)
e.buf = enc.AppendFloat32(enc.AppendKey(e.buf, key), f)
return e
}
@ -479,7 +557,7 @@ func (e *Event) Floats32(key string, f []float32) *Event {
if e == nil {
return e
}
e.buf = appendFloats32(appendKey(e.buf, key), f)
e.buf = enc.AppendFloats32(enc.AppendKey(e.buf, key), f)
return e
}
@ -488,7 +566,7 @@ func (e *Event) Float64(key string, f float64) *Event {
if e == nil {
return e
}
e.buf = appendFloat64(appendKey(e.buf, key), f)
e.buf = enc.AppendFloat64(enc.AppendKey(e.buf, key), f)
return e
}
@ -497,7 +575,7 @@ func (e *Event) Floats64(key string, f []float64) *Event {
if e == nil {
return e
}
e.buf = appendFloats64(appendKey(e.buf, key), f)
e.buf = enc.AppendFloats64(enc.AppendKey(e.buf, key), f)
return e
}
@ -510,7 +588,7 @@ func (e *Event) Timestamp() *Event {
if e == nil {
return e
}
e.buf = appendTime(appendKey(e.buf, TimestampFieldName), TimestampFunc(), TimeFieldFormat)
e.buf = enc.AppendTime(enc.AppendKey(e.buf, TimestampFieldName), TimestampFunc(), TimeFieldFormat)
return e
}
@ -519,7 +597,7 @@ func (e *Event) Time(key string, t time.Time) *Event {
if e == nil {
return e
}
e.buf = appendTime(appendKey(e.buf, key), t, TimeFieldFormat)
e.buf = enc.AppendTime(enc.AppendKey(e.buf, key), t, TimeFieldFormat)
return e
}
@ -528,7 +606,7 @@ func (e *Event) Times(key string, t []time.Time) *Event {
if e == nil {
return e
}
e.buf = appendTimes(appendKey(e.buf, key), t, TimeFieldFormat)
e.buf = enc.AppendTimes(enc.AppendKey(e.buf, key), t, TimeFieldFormat)
return e
}
@ -539,7 +617,7 @@ func (e *Event) Dur(key string, d time.Duration) *Event {
if e == nil {
return e
}
e.buf = appendDuration(appendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger)
e.buf = enc.AppendDuration(enc.AppendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger)
return e
}
@ -550,7 +628,7 @@ func (e *Event) Durs(key string, d []time.Duration) *Event {
if e == nil {
return e
}
e.buf = appendDurations(appendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger)
e.buf = enc.AppendDurations(enc.AppendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger)
return e
}
@ -565,7 +643,7 @@ func (e *Event) TimeDiff(key string, t time.Time, start time.Time) *Event {
if t.After(start) {
d = t.Sub(start)
}
e.buf = appendDuration(appendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger)
e.buf = enc.AppendDuration(enc.AppendKey(e.buf, key), d, DurationFieldUnit, DurationFieldInteger)
return e
}
@ -577,13 +655,13 @@ func (e *Event) Interface(key string, i interface{}) *Event {
if obj, ok := i.(LogObjectMarshaler); ok {
return e.Object(key, obj)
}
e.buf = appendInterface(appendKey(e.buf, key), i)
e.buf = enc.AppendInterface(enc.AppendKey(e.buf, key), i)
return e
}
// Caller adds the file:line of the caller with the zerolog.CallerFieldName key.
func (e *Event) Caller() *Event {
return e.caller(2)
return e.caller(CallerSkipFrameCount)
}
func (e *Event) caller(skip int) *Event {
@ -594,6 +672,33 @@ func (e *Event) caller(skip int) *Event {
if !ok {
return e
}
e.buf = appendString(appendKey(e.buf, CallerFieldName), file+":"+strconv.Itoa(line))
e.buf = enc.AppendString(enc.AppendKey(e.buf, CallerFieldName), CallerMarshalFunc(file, line))
return e
}
// IPAddr adds IPv4 or IPv6 Address to the event
func (e *Event) IPAddr(key string, ip net.IP) *Event {
if e == nil {
return e
}
e.buf = enc.AppendIPAddr(enc.AppendKey(e.buf, key), ip)
return e
}
// IPPrefix adds IPv4 or IPv6 Prefix (address and mask) to the event
func (e *Event) IPPrefix(key string, pfx net.IPNet) *Event {
if e == nil {
return e
}
e.buf = enc.AppendIPPrefix(enc.AppendKey(e.buf, key), pfx)
return e
}
// MACAddr adds MAC address to the event
func (e *Event) MACAddr(key string, ha net.HardwareAddr) *Event {
if e == nil {
return e
}
e.buf = enc.AppendMACAddr(enc.AppendKey(e.buf, key), ha)
return e
}

View File

@ -1,6 +1,7 @@
package zerolog
import (
"net"
"sort"
"time"
)
@ -12,114 +13,229 @@ func appendFields(dst []byte, fields map[string]interface{}) []byte {
}
sort.Strings(keys)
for _, key := range keys {
dst = appendKey(dst, key)
switch val := fields[key].(type) {
dst = enc.AppendKey(dst, key)
val := fields[key]
if val, ok := val.(LogObjectMarshaler); ok {
e := newEvent(nil, 0)
e.buf = e.buf[:0]
e.appendObject(val)
dst = append(dst, e.buf...)
putEvent(e)
continue
}
switch val := val.(type) {
case string:
dst = appendString(dst, val)
dst = enc.AppendString(dst, val)
case []byte:
dst = appendBytes(dst, val)
dst = enc.AppendBytes(dst, val)
case error:
dst = appendError(dst, val)
case []error:
dst = appendErrors(dst, val)
case bool:
dst = appendBool(dst, val)
case int:
dst = appendInt(dst, val)
case int8:
dst = appendInt8(dst, val)
case int16:
dst = appendInt16(dst, val)
case int32:
dst = appendInt32(dst, val)
case int64:
dst = appendInt64(dst, val)
case uint:
dst = appendUint(dst, val)
case uint8:
dst = appendUint8(dst, val)
case uint16:
dst = appendUint16(dst, val)
case uint32:
dst = appendUint32(dst, val)
case uint64:
dst = appendUint64(dst, val)
case float32:
dst = appendFloat32(dst, val)
case float64:
dst = appendFloat64(dst, val)
case time.Time:
dst = appendTime(dst, val, TimeFieldFormat)
case time.Duration:
dst = appendDuration(dst, val, DurationFieldUnit, DurationFieldInteger)
case *string:
dst = appendString(dst, *val)
case *bool:
dst = appendBool(dst, *val)
case *int:
dst = appendInt(dst, *val)
case *int8:
dst = appendInt8(dst, *val)
case *int16:
dst = appendInt16(dst, *val)
case *int32:
dst = appendInt32(dst, *val)
case *int64:
dst = appendInt64(dst, *val)
case *uint:
dst = appendUint(dst, *val)
case *uint8:
dst = appendUint8(dst, *val)
case *uint16:
dst = appendUint16(dst, *val)
case *uint32:
dst = appendUint32(dst, *val)
case *uint64:
dst = appendUint64(dst, *val)
case *float32:
dst = appendFloat32(dst, *val)
case *float64:
dst = appendFloat64(dst, *val)
case *time.Time:
dst = appendTime(dst, *val, TimeFieldFormat)
case *time.Duration:
dst = appendDuration(dst, *val, DurationFieldUnit, DurationFieldInteger)
case []string:
dst = appendStrings(dst, val)
case []bool:
dst = appendBools(dst, val)
case []int:
dst = appendInts(dst, val)
case []int8:
dst = appendInts8(dst, val)
case []int16:
dst = appendInts16(dst, val)
case []int32:
dst = appendInts32(dst, val)
case []int64:
dst = appendInts64(dst, val)
case []uint:
dst = appendUints(dst, val)
// case []uint8:
// dst = appendUints8(dst, val)
case []uint16:
dst = appendUints16(dst, val)
case []uint32:
dst = appendUints32(dst, val)
case []uint64:
dst = appendUints64(dst, val)
case []float32:
dst = appendFloats32(dst, val)
case []float64:
dst = appendFloats64(dst, val)
case []time.Time:
dst = appendTimes(dst, val, TimeFieldFormat)
case []time.Duration:
dst = appendDurations(dst, val, DurationFieldUnit, DurationFieldInteger)
case nil:
dst = appendNil(dst)
marshaled := ErrorMarshalFunc(val)
switch m := marshaled.(type) {
case LogObjectMarshaler:
e := newEvent(nil, 0)
e.buf = e.buf[:0]
e.appendObject(m)
dst = append(dst, e.buf...)
putEvent(e)
case error:
dst = enc.AppendString(dst, m.Error())
case string:
dst = enc.AppendString(dst, m)
default:
dst = appendInterface(dst, val)
dst = enc.AppendInterface(dst, m)
}
case []error:
dst = enc.AppendArrayStart(dst)
for i, err := range val {
marshaled := ErrorMarshalFunc(err)
switch m := marshaled.(type) {
case LogObjectMarshaler:
e := newEvent(nil, 0)
e.buf = e.buf[:0]
e.appendObject(m)
dst = append(dst, e.buf...)
putEvent(e)
case error:
dst = enc.AppendString(dst, m.Error())
case string:
dst = enc.AppendString(dst, m)
default:
dst = enc.AppendInterface(dst, m)
}
if i < (len(val) - 1) {
enc.AppendArrayDelim(dst)
}
}
dst = enc.AppendArrayEnd(dst)
case bool:
dst = enc.AppendBool(dst, val)
case int:
dst = enc.AppendInt(dst, val)
case int8:
dst = enc.AppendInt8(dst, val)
case int16:
dst = enc.AppendInt16(dst, val)
case int32:
dst = enc.AppendInt32(dst, val)
case int64:
dst = enc.AppendInt64(dst, val)
case uint:
dst = enc.AppendUint(dst, val)
case uint8:
dst = enc.AppendUint8(dst, val)
case uint16:
dst = enc.AppendUint16(dst, val)
case uint32:
dst = enc.AppendUint32(dst, val)
case uint64:
dst = enc.AppendUint64(dst, val)
case float32:
dst = enc.AppendFloat32(dst, val)
case float64:
dst = enc.AppendFloat64(dst, val)
case time.Time:
dst = enc.AppendTime(dst, val, TimeFieldFormat)
case time.Duration:
dst = enc.AppendDuration(dst, val, DurationFieldUnit, DurationFieldInteger)
case *string:
if val != nil {
dst = enc.AppendString(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *bool:
if val != nil {
dst = enc.AppendBool(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *int:
if val != nil {
dst = enc.AppendInt(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *int8:
if val != nil {
dst = enc.AppendInt8(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *int16:
if val != nil {
dst = enc.AppendInt16(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *int32:
if val != nil {
dst = enc.AppendInt32(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *int64:
if val != nil {
dst = enc.AppendInt64(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *uint:
if val != nil {
dst = enc.AppendUint(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *uint8:
if val != nil {
dst = enc.AppendUint8(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *uint16:
if val != nil {
dst = enc.AppendUint16(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *uint32:
if val != nil {
dst = enc.AppendUint32(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *uint64:
if val != nil {
dst = enc.AppendUint64(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *float32:
if val != nil {
dst = enc.AppendFloat32(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *float64:
if val != nil {
dst = enc.AppendFloat64(dst, *val)
} else {
dst = enc.AppendNil(dst)
}
case *time.Time:
if val != nil {
dst = enc.AppendTime(dst, *val, TimeFieldFormat)
} else {
dst = enc.AppendNil(dst)
}
case *time.Duration:
if val != nil {
dst = enc.AppendDuration(dst, *val, DurationFieldUnit, DurationFieldInteger)
} else {
dst = enc.AppendNil(dst)
}
case []string:
dst = enc.AppendStrings(dst, val)
case []bool:
dst = enc.AppendBools(dst, val)
case []int:
dst = enc.AppendInts(dst, val)
case []int8:
dst = enc.AppendInts8(dst, val)
case []int16:
dst = enc.AppendInts16(dst, val)
case []int32:
dst = enc.AppendInts32(dst, val)
case []int64:
dst = enc.AppendInts64(dst, val)
case []uint:
dst = enc.AppendUints(dst, val)
// case []uint8:
// dst = enc.AppendUints8(dst, val)
case []uint16:
dst = enc.AppendUints16(dst, val)
case []uint32:
dst = enc.AppendUints32(dst, val)
case []uint64:
dst = enc.AppendUints64(dst, val)
case []float32:
dst = enc.AppendFloats32(dst, val)
case []float64:
dst = enc.AppendFloats64(dst, val)
case []time.Time:
dst = enc.AppendTimes(dst, val, TimeFieldFormat)
case []time.Duration:
dst = enc.AppendDurations(dst, val, DurationFieldUnit, DurationFieldInteger)
case nil:
dst = enc.AppendNil(dst)
case net.IP:
dst = enc.AppendIPAddr(dst, val)
case net.IPNet:
dst = enc.AppendIPPrefix(dst, val)
case net.HardwareAddr:
dst = enc.AppendMACAddr(dst, val)
default:
dst = enc.AppendInterface(dst, val)
}
}
return dst

View File

@ -1,6 +1,9 @@
package zerolog
import "time"
import (
"strconv"
"time"
)
import "sync/atomic"
var (
@ -19,6 +22,25 @@ var (
// CallerFieldName is the field name used for caller field.
CallerFieldName = "caller"
// CallerSkipFrameCount is the number of stack frames to skip to find the caller.
CallerSkipFrameCount = 2
// CallerMarshalFunc allows customization of global caller marshaling
CallerMarshalFunc = func(file string, line int) string {
return file+":"+strconv.Itoa(line)
}
// ErrorStackFieldName is the field name used for error stacks.
ErrorStackFieldName = "stack"
// ErrorStackMarshaler extract the stack from err if any.
ErrorStackMarshaler func(err error) interface{}
// ErrorMarshalFunc allows customization of global error marshaling
ErrorMarshalFunc = func(err error) interface{} {
return err
}
// TimeFieldFormat defines the time format of the Time field type.
// If set to an empty string, the time is formatted as an UNIX timestamp
// as integer.
@ -34,6 +56,11 @@ var (
// DurationFieldInteger renders Dur fields as integer instead of float if
// set to true.
DurationFieldInteger = false
// ErrorHandler is called whenever zerolog fails to write an event on its
// output. If not set, an error is printed on the stderr. This handler must
// be thread safe and non-blocking.
ErrorHandler func(err error)
)
var (
@ -49,7 +76,8 @@ func SetGlobalLevel(l Level) {
atomic.StoreUint32(gLevel, uint32(l))
}
func globalLevel() Level {
// GlobalLevel returns the current global log level
func GlobalLevel() Level {
return Level(atomic.LoadUint32(gLevel))
}

View File

@ -6,6 +6,15 @@ type Hook interface {
Run(e *Event, level Level, message string)
}
// HookFunc is an adaptor to allow the use of an ordinary function
// as a Hook.
type HookFunc func(e *Event, level Level, message string)
// Run implements the Hook interface.
func (h HookFunc) Run(e *Event, level Level, message string) {
h(e, level, message)
}
// LevelHook applies a different hook for each level.
type LevelHook struct {
NoLevelHook, DebugHook, InfoHook, WarnHook, ErrorHook, FatalHook, PanicHook Hook

View File

@ -1,74 +1,56 @@
Reference:
CBOR Encoding is described in RFC7049 https://tools.ietf.org/html/rfc7049
## Reference:
CBOR Encoding is described in [RFC7049](https://tools.ietf.org/html/rfc7049)
## Comparison of JSON vs CBOR
Two main areas of reduction are:
1. CPU usage to write a log msg
2. Size (in bytes) of log messages.
Tests and benchmark:
CPU Usage savings are below:
```
sprint @ cbor>go test -v -benchmem -bench=.
=== RUN TestDecodeInteger
--- PASS: TestDecodeInteger (0.00s)
=== RUN TestDecodeString
--- PASS: TestDecodeString (0.00s)
=== RUN TestDecodeArray
--- PASS: TestDecodeArray (0.00s)
=== RUN TestDecodeMap
--- PASS: TestDecodeMap (0.00s)
=== RUN TestDecodeBool
--- PASS: TestDecodeBool (0.00s)
=== RUN TestDecodeFloat
--- PASS: TestDecodeFloat (0.00s)
=== RUN TestDecodeTimestamp
--- PASS: TestDecodeTimestamp (0.00s)
=== RUN TestDecodeCbor2Json
--- PASS: TestDecodeCbor2Json (0.00s)
=== RUN TestAppendString
--- PASS: TestAppendString (0.00s)
=== RUN TestAppendBytes
--- PASS: TestAppendBytes (0.00s)
=== RUN TestAppendTimeNow
--- PASS: TestAppendTimeNow (0.00s)
=== RUN TestAppendTimePastPresentInteger
--- PASS: TestAppendTimePastPresentInteger (0.00s)
=== RUN TestAppendTimePastPresentFloat
--- PASS: TestAppendTimePastPresentFloat (0.00s)
=== RUN TestAppendNull
--- PASS: TestAppendNull (0.00s)
=== RUN TestAppendBool
--- PASS: TestAppendBool (0.00s)
=== RUN TestAppendBoolArray
--- PASS: TestAppendBoolArray (0.00s)
=== RUN TestAppendInt
--- PASS: TestAppendInt (0.00s)
=== RUN TestAppendIntArray
--- PASS: TestAppendIntArray (0.00s)
=== RUN TestAppendFloat32
--- PASS: TestAppendFloat32 (0.00s)
goos: linux
goarch: amd64
pkg: github.com/toravir/zerolog/internal/cbor
BenchmarkAppendString/MultiBytesLast-4 30000000 43.3 ns/op 0 B/op 0 allocs/op
BenchmarkAppendString/NoEncoding-4 30000000 48.2 ns/op 0 B/op 0 allocs/op
BenchmarkAppendString/EncodingFirst-4 30000000 48.2 ns/op 0 B/op 0 allocs/op
BenchmarkAppendString/EncodingMiddle-4 30000000 41.7 ns/op 0 B/op 0 allocs/op
BenchmarkAppendString/EncodingLast-4 30000000 51.8 ns/op 0 B/op 0 allocs/op
BenchmarkAppendString/MultiBytesFirst-4 50000000 38.0 ns/op 0 B/op 0 allocs/op
BenchmarkAppendString/MultiBytesMiddle-4 50000000 38.0 ns/op 0 B/op 0 allocs/op
BenchmarkAppendTime/Integer-4 50000000 39.6 ns/op 0 B/op 0 allocs/op
BenchmarkAppendTime/Float-4 30000000 56.1 ns/op 0 B/op 0 allocs/op
BenchmarkAppendInt/uint8-4 50000000 29.1 ns/op 0 B/op 0 allocs/op
BenchmarkAppendInt/uint16-4 50000000 30.3 ns/op 0 B/op 0 allocs/op
BenchmarkAppendInt/uint32-4 50000000 37.1 ns/op 0 B/op 0 allocs/op
BenchmarkAppendInt/int8-4 100000000 21.5 ns/op 0 B/op 0 allocs/op
BenchmarkAppendInt/int16-4 50000000 25.8 ns/op 0 B/op 0 allocs/op
BenchmarkAppendInt/int32-4 50000000 26.7 ns/op 0 B/op 0 allocs/op
BenchmarkAppendInt/int-Positive-4 100000000 21.5 ns/op 0 B/op 0 allocs/op
BenchmarkAppendInt/int-Negative-4 100000000 20.7 ns/op 0 B/op 0 allocs/op
BenchmarkAppendInt/uint64-4 50000000 36.7 ns/op 0 B/op 0 allocs/op
BenchmarkAppendInt/int64-4 30000000 39.6 ns/op 0 B/op 0 allocs/op
BenchmarkAppendFloat/Float32-4 50000000 23.9 ns/op 0 B/op 0 allocs/op
BenchmarkAppendFloat/Float64-4 50000000 32.8 ns/op 0 B/op 0 allocs/op
PASS
ok github.com/toravir/zerolog/internal/cbor 34.969s
sprint @ cbor>
name JSON time/op CBOR time/op delta
Info-32 15.3ns ± 1% 11.7ns ± 3% -23.78% (p=0.000 n=9+10)
ContextFields-32 16.2ns ± 2% 12.3ns ± 3% -23.97% (p=0.000 n=9+9)
ContextAppend-32 6.70ns ± 0% 6.20ns ± 0% -7.44% (p=0.000 n=9+9)
LogFields-32 66.4ns ± 0% 24.6ns ± 2% -62.89% (p=0.000 n=10+9)
LogArrayObject-32 911ns ±11% 768ns ± 6% -15.64% (p=0.000 n=10+10)
LogFieldType/Floats-32 70.3ns ± 2% 29.5ns ± 1% -57.98% (p=0.000 n=10+10)
LogFieldType/Err-32 14.0ns ± 3% 12.1ns ± 8% -13.20% (p=0.000 n=8+10)
LogFieldType/Dur-32 17.2ns ± 2% 13.1ns ± 1% -24.27% (p=0.000 n=10+9)
LogFieldType/Object-32 54.3ns ±11% 52.3ns ± 7% ~ (p=0.239 n=10+10)
LogFieldType/Ints-32 20.3ns ± 2% 15.1ns ± 2% -25.50% (p=0.000 n=9+10)
LogFieldType/Interfaces-32 642ns ±11% 621ns ± 9% ~ (p=0.118 n=10+10)
LogFieldType/Interface(Objects)-32 635ns ±13% 632ns ± 9% ~ (p=0.592 n=10+10)
LogFieldType/Times-32 294ns ± 0% 27ns ± 1% -90.71% (p=0.000 n=10+9)
LogFieldType/Durs-32 121ns ± 0% 33ns ± 2% -72.44% (p=0.000 n=9+9)
LogFieldType/Interface(Object)-32 56.6ns ± 8% 52.3ns ± 8% -7.54% (p=0.007 n=10+10)
LogFieldType/Errs-32 17.8ns ± 3% 16.1ns ± 2% -9.71% (p=0.000 n=10+9)
LogFieldType/Time-32 40.5ns ± 1% 12.7ns ± 6% -68.66% (p=0.000 n=8+9)
LogFieldType/Bool-32 12.0ns ± 5% 10.2ns ± 2% -15.18% (p=0.000 n=10+8)
LogFieldType/Bools-32 17.2ns ± 2% 12.6ns ± 4% -26.63% (p=0.000 n=10+10)
LogFieldType/Int-32 12.3ns ± 2% 11.2ns ± 4% -9.27% (p=0.000 n=9+10)
LogFieldType/Float-32 16.7ns ± 1% 12.6ns ± 2% -24.42% (p=0.000 n=7+9)
LogFieldType/Str-32 12.7ns ± 7% 11.3ns ± 7% -10.88% (p=0.000 n=10+9)
LogFieldType/Strs-32 20.3ns ± 3% 18.2ns ± 3% -10.25% (p=0.000 n=9+10)
LogFieldType/Interface-32 183ns ±12% 175ns ± 9% ~ (p=0.078 n=10+10)
```
Log message size savings is greatly dependent on the number and type of fields in the log message.
Assuming this log message (with an Integer, timestamp and string, in addition to level).
`{"level":"error","Fault":41650,"time":"2018-04-01T15:18:19-07:00","message":"Some Message"}`
Two measurements were done for the log file sizes - one without any compression, second
using [compress/zlib](https://golang.org/pkg/compress/zlib/).
Results for 10,000 log messages:
| Log Format | Plain File Size (in KB) | Compressed File Size (in KB) |
| :--- | :---: | :---: |
| JSON | 920 | 28 |
| CBOR | 550 | 28 |
The example used to calculate the above data is available in [Examples](examples).

View File

@ -1,43 +1,11 @@
package cbor
type Encoder struct{}
// AppendKey adds a key (string) to the binary encoded log message
func AppendKey(dst []byte, key string) []byte {
func (e Encoder) AppendKey(dst []byte, key string) []byte {
if len(dst) < 1 {
dst = AppendBeginMarker(dst)
dst = e.AppendBeginMarker(dst)
}
return AppendString(dst, key)
}
// AppendError adds the Error to the log message if error is NOT nil
func AppendError(dst []byte, err error) []byte {
if err == nil {
return append(dst, `null`...)
}
return AppendString(dst, err.Error())
}
// AppendErrors when given an array of errors,
// adds them to the log message if a specific error is nil, then
// Nil is added, or else the error string is added.
func AppendErrors(dst []byte, errs []error) []byte {
if len(errs) == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
}
dst = AppendArrayStart(dst)
if errs[0] != nil {
dst = AppendString(dst, errs[0].Error())
} else {
dst = AppendNull(dst)
}
if len(errs) > 1 {
for _, err := range errs[1:] {
if err == nil {
dst = AppendNull(dst)
continue
}
dst = AppendString(dst, err.Error())
}
}
dst = AppendArrayEnd(dst)
return dst
return e.AppendString(dst, key)
}

View File

@ -7,25 +7,34 @@ import "time"
const (
majorOffset = 5
additionalMax = 23
//Non Values
// Non Values.
additionalTypeBoolFalse byte = 20
additionalTypeBoolTrue byte = 21
additionalTypeNull byte = 22
//Integer (+ve and -ve) Sub-types
// Integer (+ve and -ve) Sub-types.
additionalTypeIntUint8 byte = 24
additionalTypeIntUint16 byte = 25
additionalTypeIntUint32 byte = 26
additionalTypeIntUint64 byte = 27
//Float Sub-types
// Float Sub-types.
additionalTypeFloat16 byte = 25
additionalTypeFloat32 byte = 26
additionalTypeFloat64 byte = 27
additionalTypeBreak byte = 31
//Tag Sub-types
// Tag Sub-types.
additionalTypeTimestamp byte = 01
additionalTypeEmbeddedJSON byte = 31
additionalTypeTagHexString uint16 = 262
//Unspecified number of elements
// Extended Tags - from https://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml
additionalTypeTagNetworkAddr uint16 = 260
additionalTypeTagNetworkPrefix uint16 = 261
additionalTypeEmbeddedJSON uint16 = 262
additionalTypeTagHexString uint16 = 263
// Unspecified number of elements.
additionalTypeInfiniteCount byte = 31
)
const (

View File

@ -1,548 +0,0 @@
package cbor
import (
"bytes"
"fmt"
"io"
"math"
"strconv"
"time"
"unicode/utf8"
)
var decodeTimeZone *time.Location
const hexTable = "0123456789abcdef"
func decodeIntAdditonalType(src []byte, minor byte) (int64, uint, error) {
val := int64(0)
bytesRead := 0
if minor <= 23 {
val = int64(minor)
bytesRead = 0
} else {
switch minor {
case additionalTypeIntUint8:
bytesRead = 1
case additionalTypeIntUint16:
bytesRead = 2
case additionalTypeIntUint32:
bytesRead = 4
case additionalTypeIntUint64:
bytesRead = 8
default:
return 0, 0, fmt.Errorf("Invalid Additional Type: %d in decodeInteger (expected <28)", minor)
}
for i := 0; i < bytesRead; i++ {
val = val * 256
val += int64(src[i])
}
}
return val, uint(bytesRead), nil
}
func decodeInteger(src []byte) (int64, uint, error) {
major := src[0] & maskOutAdditionalType
minor := src[0] & maskOutMajorType
if major != majorTypeUnsignedInt && major != majorTypeNegativeInt {
return 0, 0, fmt.Errorf("Major type is: %d in decodeInteger!! (expected 0 or 1)", major)
}
val, bytesRead, err := decodeIntAdditonalType(src[1:], minor)
if err != nil {
return 0, 0, err
}
if major == 0 {
return val, 1 + bytesRead, nil
}
return (-1 - val), 1 + bytesRead, nil
}
func decodeFloat(src []byte) (float64, uint, error) {
major := (src[0] & maskOutAdditionalType)
minor := src[0] & maskOutMajorType
if major != majorTypeSimpleAndFloat {
return 0, 0, fmt.Errorf("Incorrect Major type is: %d in decodeFloat", major)
}
switch minor {
case additionalTypeFloat16:
return 0, 0, fmt.Errorf("float16 is not suppported in decodeFloat")
case additionalTypeFloat32:
switch string(src[1:5]) {
case float32Nan:
return math.NaN(), 5, nil
case float32PosInfinity:
return math.Inf(0), 5, nil
case float32NegInfinity:
return math.Inf(-1), 5, nil
}
n := uint32(0)
for i := 0; i < 4; i++ {
n = n * 256
n += uint32(src[i+1])
}
val := math.Float32frombits(n)
return float64(val), 5, nil
case additionalTypeFloat64:
switch string(src[1:9]) {
case float64Nan:
return math.NaN(), 9, nil
case float64PosInfinity:
return math.Inf(0), 9, nil
case float64NegInfinity:
return math.Inf(-1), 9, nil
}
n := uint64(0)
for i := 0; i < 8; i++ {
n = n * 256
n += uint64(src[i+1])
}
val := math.Float64frombits(n)
return val, 9, nil
}
return 0, 0, fmt.Errorf("Invalid Additional Type: %d in decodeFloat", minor)
}
func decodeStringComplex(dst []byte, s string, pos uint) []byte {
i := int(pos)
const hex = "0123456789abcdef"
start := 0
for i < len(s) {
b := s[i]
if b >= utf8.RuneSelf {
r, size := utf8.DecodeRuneInString(s[i:])
if r == utf8.RuneError && size == 1 {
// In case of error, first append previous simple characters to
// the byte slice if any and append a replacement character code
// in place of the invalid sequence.
if start < i {
dst = append(dst, s[start:i]...)
}
dst = append(dst, `\ufffd`...)
i += size
start = i
continue
}
i += size
continue
}
if b >= 0x20 && b <= 0x7e && b != '\\' && b != '"' {
i++
continue
}
// We encountered a character that needs to be encoded.
// Let's append the previous simple characters to the byte slice
// and switch our operation to read and encode the remainder
// characters byte-by-byte.
if start < i {
dst = append(dst, s[start:i]...)
}
switch b {
case '"', '\\':
dst = append(dst, '\\', b)
case '\b':
dst = append(dst, '\\', 'b')
case '\f':
dst = append(dst, '\\', 'f')
case '\n':
dst = append(dst, '\\', 'n')
case '\r':
dst = append(dst, '\\', 'r')
case '\t':
dst = append(dst, '\\', 't')
default:
dst = append(dst, '\\', 'u', '0', '0', hex[b>>4], hex[b&0xF])
}
i++
start = i
}
if start < len(s) {
dst = append(dst, s[start:]...)
}
return dst
}
func decodeString(src []byte, noQuotes bool) ([]byte, uint, error) {
major := src[0] & maskOutAdditionalType
minor := src[0] & maskOutMajorType
if major != majorTypeByteString {
return []byte{}, 0, fmt.Errorf("Major type is: %d in decodeString", major)
}
result := []byte{'"'}
if noQuotes {
result = []byte{}
}
length, bytesRead, err := decodeIntAdditonalType(src[1:], minor)
if err != nil {
return []byte{}, 0, err
}
bytesRead++
st := bytesRead
len := uint(length)
bytesRead += len
result = append(result, src[st:st+len]...)
if noQuotes {
return result, bytesRead, nil
}
return append(result, '"'), bytesRead, nil
}
func decodeUTF8String(src []byte) ([]byte, uint, error) {
major := src[0] & maskOutAdditionalType
minor := src[0] & maskOutMajorType
if major != majorTypeUtf8String {
return []byte{}, 0, fmt.Errorf("Major type is: %d in decodeUTF8String", major)
}
result := []byte{'"'}
length, bytesRead, err := decodeIntAdditonalType(src[1:], minor)
if err != nil {
return []byte{}, 0, err
}
bytesRead++
st := bytesRead
len := uint(length)
bytesRead += len
for i := st; i < bytesRead; i++ {
// Check if the character needs encoding. Control characters, slashes,
// and the double quote need json encoding. Bytes above the ascii
// boundary needs utf8 encoding.
if src[i] < 0x20 || src[i] > 0x7e || src[i] == '\\' || src[i] == '"' {
// We encountered a character that needs to be encoded. Switch
// to complex version of the algorithm.
dst := []byte{'"'}
dst = decodeStringComplex(dst, string(src[st:st+len]), i-st)
return append(dst, '"'), bytesRead, nil
}
}
// The string has no need for encoding an therefore is directly
// appended to the byte slice.
result = append(result, src[st:st+len]...)
return append(result, '"'), bytesRead, nil
}
func array2Json(src []byte, dst io.Writer) (uint, error) {
dst.Write([]byte{'['})
major := (src[0] & maskOutAdditionalType)
minor := src[0] & maskOutMajorType
if major != majorTypeArray {
return 0, fmt.Errorf("Major type is: %d in array2Json", major)
}
len := 0
bytesRead := uint(0)
unSpecifiedCount := false
if minor == additionalTypeInfiniteCount {
unSpecifiedCount = true
bytesRead = 1
} else {
var length int64
var err error
length, bytesRead, err = decodeIntAdditonalType(src[1:], minor)
if err != nil {
fmt.Println("Error!!!")
return 0, err
}
len = int(length)
bytesRead++
}
curPos := bytesRead
for i := 0; unSpecifiedCount || i < len; i++ {
bc, err := Cbor2JsonOneObject(src[curPos:], dst)
if err != nil {
if src[curPos] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) {
bytesRead++
break
}
return 0, err
}
curPos += bc
bytesRead += bc
if unSpecifiedCount {
if src[curPos] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) {
bytesRead++
break
}
dst.Write([]byte{','})
} else if i+1 < len {
dst.Write([]byte{','})
}
}
dst.Write([]byte{']'})
return bytesRead, nil
}
func map2Json(src []byte, dst io.Writer) (uint, error) {
major := (src[0] & maskOutAdditionalType)
minor := src[0] & maskOutMajorType
if major != majorTypeMap {
return 0, fmt.Errorf("Major type is: %d in map2Json", major)
}
len := 0
bytesRead := uint(0)
unSpecifiedCount := false
if minor == additionalTypeInfiniteCount {
unSpecifiedCount = true
bytesRead = 1
} else {
var length int64
var err error
length, bytesRead, err = decodeIntAdditonalType(src[1:], minor)
if err != nil {
fmt.Println("Error!!!")
return 0, err
}
len = int(length)
bytesRead++
}
if len%2 == 1 {
return 0, fmt.Errorf("Invalid Length of map %d - has to be even", len)
}
dst.Write([]byte{'{'})
curPos := bytesRead
for i := 0; unSpecifiedCount || i < len; i++ {
bc, err := Cbor2JsonOneObject(src[curPos:], dst)
if err != nil {
//We hit the BREAK
if src[curPos] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) {
bytesRead++
break
}
return 0, err
}
curPos += bc
bytesRead += bc
if i%2 == 0 {
//Even position values are keys
dst.Write([]byte{':'})
} else {
if unSpecifiedCount {
if src[curPos] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) {
bytesRead++
break
}
dst.Write([]byte{','})
} else if i+1 < len {
dst.Write([]byte{','})
}
}
}
dst.Write([]byte{'}'})
return bytesRead, nil
}
func decodeTagData(src []byte) ([]byte, uint, error) {
major := (src[0] & maskOutAdditionalType)
minor := src[0] & maskOutMajorType
if major != majorTypeTags {
return nil, 0, fmt.Errorf("Major type is: %d in decodeTagData", major)
}
if minor == additionalTypeTimestamp {
tsMajor := src[1] & maskOutAdditionalType
if tsMajor == majorTypeUnsignedInt || tsMajor == majorTypeNegativeInt {
n, bc, err := decodeInteger(src[1:])
if err != nil {
return []byte{}, 0, err
}
t := time.Unix(n, 0)
if decodeTimeZone != nil {
t = t.In(decodeTimeZone)
} else {
t = t.In(time.UTC)
}
tsb := []byte{}
tsb = append(tsb, '"')
tsb = t.AppendFormat(tsb, IntegerTimeFieldFormat)
tsb = append(tsb, '"')
return tsb, 1 + bc, nil
} else if tsMajor == majorTypeSimpleAndFloat {
n, bc, err := decodeFloat(src[1:])
if err != nil {
return []byte{}, 0, err
}
secs := int64(n)
n -= float64(secs)
n *= float64(1e9)
t := time.Unix(secs, int64(n))
if decodeTimeZone != nil {
t = t.In(decodeTimeZone)
} else {
t = t.In(time.UTC)
}
tsb := []byte{}
tsb = append(tsb, '"')
tsb = t.AppendFormat(tsb, NanoTimeFieldFormat)
tsb = append(tsb, '"')
return tsb, 1 + bc, nil
} else {
return nil, 0, fmt.Errorf("TS format is neigther int nor float: %d", tsMajor)
}
} else if minor == additionalTypeEmbeddedJSON {
dataMajor := src[1] & maskOutAdditionalType
if dataMajor == majorTypeByteString {
emb, bc, err := decodeString(src[1:], true)
if err != nil {
return nil, 0, err
}
return emb, 1 + bc, nil
}
return nil, 0, fmt.Errorf("Unsupported embedded Type: %d in decodeEmbeddedJSON", dataMajor)
} else if minor == additionalTypeIntUint16 {
val,_,_ := decodeIntAdditonalType(src[1:], minor)
if uint16(val) == additionalTypeTagHexString {
emb, bc, _ := decodeString(src[3:], true)
dst := []byte{'"'}
for _, v := range emb {
dst = append(dst, hexTable[v>>4], hexTable[v&0x0f])
}
return append(dst, '"'), 3+bc, nil
}
}
return nil, 0, fmt.Errorf("Unsupported Additional Type: %d in decodeTagData", minor)
}
func decodeSimpleFloat(src []byte) ([]byte, uint, error) {
major := (src[0] & maskOutAdditionalType)
minor := src[0] & maskOutMajorType
if major != majorTypeSimpleAndFloat {
return nil, 0, fmt.Errorf("Major type is: %d in decodeSimpleFloat", major)
}
switch minor {
case additionalTypeBoolTrue:
return []byte("true"), 1, nil
case additionalTypeBoolFalse:
return []byte("false"), 1, nil
case additionalTypeNull:
return []byte("null"), 1, nil
case additionalTypeFloat16:
fallthrough
case additionalTypeFloat32:
fallthrough
case additionalTypeFloat64:
v, bc, err := decodeFloat(src)
if err != nil {
return nil, 0, err
}
ba := []byte{}
switch {
case math.IsNaN(v):
return []byte("\"NaN\""), bc, nil
case math.IsInf(v, 1):
return []byte("\"+Inf\""), bc, nil
case math.IsInf(v, -1):
return []byte("\"-Inf\""), bc, nil
}
if bc == 5 {
ba = strconv.AppendFloat(ba, v, 'f', -1, 32)
} else {
ba = strconv.AppendFloat(ba, v, 'f', -1, 64)
}
return ba, bc, nil
default:
return nil, 0, fmt.Errorf("Invalid Additional Type: %d in decodeSimpleFloat", minor)
}
}
// Cbor2JsonOneObject takes in byte array and decodes ONE CBOR Object
// usually a MAP. Use this when only ONE CBOR object needs decoding.
// Decoded string is written to the dst.
// Returns the bytes decoded and if any error was encountered.
func Cbor2JsonOneObject(src []byte, dst io.Writer) (uint, error) {
var err error
major := (src[0] & maskOutAdditionalType)
bc := uint(0)
var s []byte
switch major {
case majorTypeUnsignedInt:
fallthrough
case majorTypeNegativeInt:
var n int64
n, bc, err = decodeInteger(src)
dst.Write([]byte(strconv.Itoa(int(n))))
case majorTypeByteString:
s, bc, err = decodeString(src, false)
dst.Write(s)
case majorTypeUtf8String:
s, bc, err = decodeUTF8String(src)
dst.Write(s)
case majorTypeArray:
bc, err = array2Json(src, dst)
case majorTypeMap:
bc, err = map2Json(src, dst)
case majorTypeTags:
s, bc, err = decodeTagData(src)
dst.Write(s)
case majorTypeSimpleAndFloat:
s, bc, err = decodeSimpleFloat(src)
dst.Write(s)
}
return bc, err
}
// Cbor2JsonManyObjects decodes all the CBOR Objects present in the
// source byte array. It keeps on decoding until it runs out of bytes.
// Decoded string is written to the dst. At the end of every CBOR Object
// newline is written to the output stream.
// Returns the number of bytes decoded and if any error was encountered.
func Cbor2JsonManyObjects(src []byte, dst io.Writer) (uint, error) {
curPos := uint(0)
totalBytes := uint(len(src))
for curPos < totalBytes {
bc, err := Cbor2JsonOneObject(src[curPos:], dst)
if err != nil {
return curPos, err
}
dst.Write([]byte("\n"))
curPos += bc
}
return curPos, nil
}
// Detect if the bytes to be printed is Binary or not.
func binaryFmt(p []byte) bool {
if len(p) > 0 && p[0] > 0x7F {
return true
}
return false
}
// DecodeIfBinaryToString converts a binary formatted log msg to a
// JSON formatted String Log message - suitable for printing to Console/Syslog.
func DecodeIfBinaryToString(in []byte) string {
if binaryFmt(in) {
var b bytes.Buffer
Cbor2JsonManyObjects(in, &b)
return b.String()
}
return string(in)
}
// DecodeObjectToStr checks if the input is a binary format, if so,
// it will decode a single Object and return the decoded string.
func DecodeObjectToStr(in []byte) string {
if binaryFmt(in) {
var b bytes.Buffer
Cbor2JsonOneObject(in, &b)
return b.String()
}
return string(in)
}
// DecodeIfBinaryToBytes checks if the input is a binary format, if so,
// it will decode all Objects and return the decoded string as byte array.
func DecodeIfBinaryToBytes(in []byte) []byte {
if binaryFmt(in) {
var b bytes.Buffer
Cbor2JsonManyObjects(in, &b)
return b.Bytes()
}
return in
}

View File

@ -1,7 +1,7 @@
package cbor
// AppendStrings encodes and adds an array of strings to the dst byte array.
func AppendStrings(dst []byte, vals []string) []byte {
func (e Encoder) AppendStrings(dst []byte, vals []string) []byte {
major := majorTypeArray
l := len(vals)
if l <= additionalMax {
@ -11,13 +11,13 @@ func AppendStrings(dst []byte, vals []string) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendString(dst, v)
dst = e.AppendString(dst, v)
}
return dst
}
// AppendString encodes and adds a string to the dst byte array.
func AppendString(dst []byte, s string) []byte {
func (Encoder) AppendString(dst []byte, s string) []byte {
major := majorTypeUtf8String
l := len(s)
@ -31,7 +31,7 @@ func AppendString(dst []byte, s string) []byte {
}
// AppendBytes encodes and adds an array of bytes to the dst byte array.
func AppendBytes(dst, s []byte) []byte {
func (Encoder) AppendBytes(dst, s []byte) []byte {
major := majorTypeByteString
l := len(s)
@ -48,8 +48,13 @@ func AppendBytes(dst, s []byte) []byte {
func AppendEmbeddedJSON(dst, s []byte) []byte {
major := majorTypeTags
minor := additionalTypeEmbeddedJSON
dst = append(dst, byte(major|minor))
// Append the TAG to indicate this is Embedded JSON.
dst = append(dst, byte(major|additionalTypeIntUint16))
dst = append(dst, byte(minor>>8))
dst = append(dst, byte(minor&0xff))
// Append the JSON Object as Byte String.
major = majorTypeByteString
l := len(s)

View File

@ -21,7 +21,7 @@ func appendIntegerTimestamp(dst []byte, t time.Time) []byte {
return dst
}
func appendFloatTimestamp(dst []byte, t time.Time) []byte {
func (e Encoder) appendFloatTimestamp(dst []byte, t time.Time) []byte {
major := majorTypeTags
minor := additionalTypeTimestamp
dst = append(dst, byte(major|minor))
@ -29,24 +29,24 @@ func appendFloatTimestamp(dst []byte, t time.Time) []byte {
nanos := t.Nanosecond()
var val float64
val = float64(secs)*1.0 + float64(nanos)*1E-9
return AppendFloat64(dst, val)
return e.AppendFloat64(dst, val)
}
// AppendTime encodes and adds a timestamp to the dst byte array.
func AppendTime(dst []byte, t time.Time, unused string) []byte {
func (e Encoder) AppendTime(dst []byte, t time.Time, unused string) []byte {
utc := t.UTC()
if utc.Nanosecond() == 0 {
return appendIntegerTimestamp(dst, utc)
}
return appendFloatTimestamp(dst, utc)
return e.appendFloatTimestamp(dst, utc)
}
// AppendTimes encodes and adds an array of timestamps to the dst byte array.
func AppendTimes(dst []byte, vals []time.Time, unused string) []byte {
func (e Encoder) AppendTimes(dst []byte, vals []time.Time, unused string) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -56,7 +56,7 @@ func AppendTimes(dst []byte, vals []time.Time, unused string) []byte {
}
for _, t := range vals {
dst = AppendTime(dst, t, unused)
dst = e.AppendTime(dst, t, unused)
}
return dst
}
@ -64,21 +64,21 @@ func AppendTimes(dst []byte, vals []time.Time, unused string) []byte {
// AppendDuration encodes and adds a duration to the dst byte array.
// useInt field indicates whether to store the duration as seconds (integer) or
// as seconds+nanoseconds (float).
func AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte {
func (e Encoder) AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte {
if useInt {
return AppendInt64(dst, int64(d/unit))
return e.AppendInt64(dst, int64(d/unit))
}
return AppendFloat64(dst, float64(d)/float64(unit))
return e.AppendFloat64(dst, float64(d)/float64(unit))
}
// AppendDurations encodes and adds an array of durations to the dst byte array.
// useInt field indicates whether to store the duration as seconds (integer) or
// as seconds+nanoseconds (float).
func AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte {
func (e Encoder) AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -87,7 +87,7 @@ func AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useIn
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, d := range vals {
dst = AppendDuration(dst, d, unit, useInt)
dst = e.AppendDuration(dst, d, unit, useInt)
}
return dst
}

View File

@ -4,25 +4,55 @@ import (
"encoding/json"
"fmt"
"math"
"net"
)
// AppendNull inserts a 'Nil' object into the dst byte array.
func AppendNull(dst []byte) []byte {
// AppendNil inserts a 'Nil' object into the dst byte array.
func (Encoder) AppendNil(dst []byte) []byte {
return append(dst, byte(majorTypeSimpleAndFloat|additionalTypeNull))
}
// AppendBeginMarker inserts a map start into the dst byte array.
func AppendBeginMarker(dst []byte) []byte {
func (Encoder) AppendBeginMarker(dst []byte) []byte {
return append(dst, byte(majorTypeMap|additionalTypeInfiniteCount))
}
// AppendEndMarker inserts a map end into the dst byte array.
func AppendEndMarker(dst []byte) []byte {
func (Encoder) AppendEndMarker(dst []byte) []byte {
return append(dst, byte(majorTypeSimpleAndFloat|additionalTypeBreak))
}
// AppendObjectData takes an object in form of a byte array and appends to dst.
func (Encoder) AppendObjectData(dst []byte, o []byte) []byte {
// BeginMarker is present in the dst, which
// should not be copied when appending to existing data.
return append(dst, o[1:]...)
}
// AppendArrayStart adds markers to indicate the start of an array.
func (Encoder) AppendArrayStart(dst []byte) []byte {
return append(dst, byte(majorTypeArray|additionalTypeInfiniteCount))
}
// AppendArrayEnd adds markers to indicate the end of an array.
func (Encoder) AppendArrayEnd(dst []byte) []byte {
return append(dst, byte(majorTypeSimpleAndFloat|additionalTypeBreak))
}
// AppendArrayDelim adds markers to indicate end of a particular array element.
func (Encoder) AppendArrayDelim(dst []byte) []byte {
//No delimiters needed in cbor
return dst
}
// AppendLineBreak is a noop that keep API compat with json encoder.
func (Encoder) AppendLineBreak(dst []byte) []byte {
// No line breaks needed in binary format.
return dst
}
// AppendBool encodes and inserts a boolean value into the dst byte array.
func AppendBool(dst []byte, val bool) []byte {
func (Encoder) AppendBool(dst []byte, val bool) []byte {
b := additionalTypeBoolFalse
if val {
b = additionalTypeBoolTrue
@ -31,11 +61,11 @@ func AppendBool(dst []byte, val bool) []byte {
}
// AppendBools encodes and inserts an array of boolean values into the dst byte array.
func AppendBools(dst []byte, vals []bool) []byte {
func (e Encoder) AppendBools(dst []byte, vals []bool) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -44,13 +74,13 @@ func AppendBools(dst []byte, vals []bool) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendBool(dst, v)
dst = e.AppendBool(dst, v)
}
return dst
}
// AppendInt encodes and inserts an integer value into the dst byte array.
func AppendInt(dst []byte, val int) []byte {
func (Encoder) AppendInt(dst []byte, val int) []byte {
major := majorTypeUnsignedInt
contentVal := val
if val < 0 {
@ -67,11 +97,11 @@ func AppendInt(dst []byte, val int) []byte {
}
// AppendInts encodes and inserts an array of integer values into the dst byte array.
func AppendInts(dst []byte, vals []int) []byte {
func (e Encoder) AppendInts(dst []byte, vals []int) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -80,22 +110,22 @@ func AppendInts(dst []byte, vals []int) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendInt(dst, v)
dst = e.AppendInt(dst, v)
}
return dst
}
// AppendInt8 encodes and inserts an int8 value into the dst byte array.
func AppendInt8(dst []byte, val int8) []byte {
return AppendInt(dst, int(val))
func (e Encoder) AppendInt8(dst []byte, val int8) []byte {
return e.AppendInt(dst, int(val))
}
// AppendInts8 encodes and inserts an array of integer values into the dst byte array.
func AppendInts8(dst []byte, vals []int8) []byte {
func (e Encoder) AppendInts8(dst []byte, vals []int8) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -104,22 +134,22 @@ func AppendInts8(dst []byte, vals []int8) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendInt(dst, int(v))
dst = e.AppendInt(dst, int(v))
}
return dst
}
// AppendInt16 encodes and inserts a int16 value into the dst byte array.
func AppendInt16(dst []byte, val int16) []byte {
return AppendInt(dst, int(val))
func (e Encoder) AppendInt16(dst []byte, val int16) []byte {
return e.AppendInt(dst, int(val))
}
// AppendInts16 encodes and inserts an array of int16 values into the dst byte array.
func AppendInts16(dst []byte, vals []int16) []byte {
func (e Encoder) AppendInts16(dst []byte, vals []int16) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -128,22 +158,22 @@ func AppendInts16(dst []byte, vals []int16) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendInt(dst, int(v))
dst = e.AppendInt(dst, int(v))
}
return dst
}
// AppendInt32 encodes and inserts a int32 value into the dst byte array.
func AppendInt32(dst []byte, val int32) []byte {
return AppendInt(dst, int(val))
func (e Encoder) AppendInt32(dst []byte, val int32) []byte {
return e.AppendInt(dst, int(val))
}
// AppendInts32 encodes and inserts an array of int32 values into the dst byte array.
func AppendInts32(dst []byte, vals []int32) []byte {
func (e Encoder) AppendInts32(dst []byte, vals []int32) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -152,13 +182,13 @@ func AppendInts32(dst []byte, vals []int32) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendInt(dst, int(v))
dst = e.AppendInt(dst, int(v))
}
return dst
}
// AppendInt64 encodes and inserts a int64 value into the dst byte array.
func AppendInt64(dst []byte, val int64) []byte {
func (Encoder) AppendInt64(dst []byte, val int64) []byte {
major := majorTypeUnsignedInt
contentVal := val
if val < 0 {
@ -175,11 +205,11 @@ func AppendInt64(dst []byte, val int64) []byte {
}
// AppendInts64 encodes and inserts an array of int64 values into the dst byte array.
func AppendInts64(dst []byte, vals []int64) []byte {
func (e Encoder) AppendInts64(dst []byte, vals []int64) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -188,22 +218,22 @@ func AppendInts64(dst []byte, vals []int64) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendInt64(dst, v)
dst = e.AppendInt64(dst, v)
}
return dst
}
// AppendUint encodes and inserts an unsigned integer value into the dst byte array.
func AppendUint(dst []byte, val uint) []byte {
return AppendInt64(dst, int64(val))
func (e Encoder) AppendUint(dst []byte, val uint) []byte {
return e.AppendInt64(dst, int64(val))
}
// AppendUints encodes and inserts an array of unsigned integer values into the dst byte array.
func AppendUints(dst []byte, vals []uint) []byte {
func (e Encoder) AppendUints(dst []byte, vals []uint) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -212,22 +242,22 @@ func AppendUints(dst []byte, vals []uint) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendUint(dst, v)
dst = e.AppendUint(dst, v)
}
return dst
}
// AppendUint8 encodes and inserts a unsigned int8 value into the dst byte array.
func AppendUint8(dst []byte, val uint8) []byte {
return AppendUint(dst, uint(val))
func (e Encoder) AppendUint8(dst []byte, val uint8) []byte {
return e.AppendUint(dst, uint(val))
}
// AppendUints8 encodes and inserts an array of uint8 values into the dst byte array.
func AppendUints8(dst []byte, vals []uint8) []byte {
func (e Encoder) AppendUints8(dst []byte, vals []uint8) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -236,22 +266,22 @@ func AppendUints8(dst []byte, vals []uint8) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendUint8(dst, v)
dst = e.AppendUint8(dst, v)
}
return dst
}
// AppendUint16 encodes and inserts a uint16 value into the dst byte array.
func AppendUint16(dst []byte, val uint16) []byte {
return AppendUint(dst, uint(val))
func (e Encoder) AppendUint16(dst []byte, val uint16) []byte {
return e.AppendUint(dst, uint(val))
}
// AppendUints16 encodes and inserts an array of uint16 values into the dst byte array.
func AppendUints16(dst []byte, vals []uint16) []byte {
func (e Encoder) AppendUints16(dst []byte, vals []uint16) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -260,22 +290,22 @@ func AppendUints16(dst []byte, vals []uint16) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendUint16(dst, v)
dst = e.AppendUint16(dst, v)
}
return dst
}
// AppendUint32 encodes and inserts a uint32 value into the dst byte array.
func AppendUint32(dst []byte, val uint32) []byte {
return AppendUint(dst, uint(val))
func (e Encoder) AppendUint32(dst []byte, val uint32) []byte {
return e.AppendUint(dst, uint(val))
}
// AppendUints32 encodes and inserts an array of uint32 values into the dst byte array.
func AppendUints32(dst []byte, vals []uint32) []byte {
func (e Encoder) AppendUints32(dst []byte, vals []uint32) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -284,13 +314,13 @@ func AppendUints32(dst []byte, vals []uint32) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendUint32(dst, v)
dst = e.AppendUint32(dst, v)
}
return dst
}
// AppendUint64 encodes and inserts a uint64 value into the dst byte array.
func AppendUint64(dst []byte, val uint64) []byte {
func (Encoder) AppendUint64(dst []byte, val uint64) []byte {
major := majorTypeUnsignedInt
contentVal := val
if contentVal <= additionalMax {
@ -303,11 +333,11 @@ func AppendUint64(dst []byte, val uint64) []byte {
}
// AppendUints64 encodes and inserts an array of uint64 values into the dst byte array.
func AppendUints64(dst []byte, vals []uint64) []byte {
func (e Encoder) AppendUints64(dst []byte, vals []uint64) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -316,13 +346,13 @@ func AppendUints64(dst []byte, vals []uint64) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendUint64(dst, v)
dst = e.AppendUint64(dst, v)
}
return dst
}
// AppendFloat32 encodes and inserts a single precision float value into the dst byte array.
func AppendFloat32(dst []byte, val float32) []byte {
func (Encoder) AppendFloat32(dst []byte, val float32) []byte {
switch {
case math.IsNaN(float64(val)):
return append(dst, "\xfa\x7f\xc0\x00\x00"...)
@ -342,11 +372,11 @@ func AppendFloat32(dst []byte, val float32) []byte {
}
// AppendFloats32 encodes and inserts an array of single precision float value into the dst byte array.
func AppendFloats32(dst []byte, vals []float32) []byte {
func (e Encoder) AppendFloats32(dst []byte, vals []float32) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -355,13 +385,13 @@ func AppendFloats32(dst []byte, vals []float32) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendFloat32(dst, v)
dst = e.AppendFloat32(dst, v)
}
return dst
}
// AppendFloat64 encodes and inserts a double precision float value into the dst byte array.
func AppendFloat64(dst []byte, val float64) []byte {
func (Encoder) AppendFloat64(dst []byte, val float64) []byte {
switch {
case math.IsNaN(val):
return append(dst, "\xfb\x7f\xf8\x00\x00\x00\x00\x00\x00"...)
@ -382,11 +412,11 @@ func AppendFloat64(dst []byte, val float64) []byte {
}
// AppendFloats64 encodes and inserts an array of double precision float values into the dst byte array.
func AppendFloats64(dst []byte, vals []float64) []byte {
func (e Encoder) AppendFloats64(dst []byte, vals []float64) []byte {
major := majorTypeArray
l := len(vals)
if l == 0 {
return AppendArrayEnd(AppendArrayStart(dst))
return e.AppendArrayEnd(e.AppendArrayStart(dst))
}
if l <= additionalMax {
lb := byte(l)
@ -395,44 +425,54 @@ func AppendFloats64(dst []byte, vals []float64) []byte {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
for _, v := range vals {
dst = AppendFloat64(dst, v)
dst = e.AppendFloat64(dst, v)
}
return dst
}
// AppendInterface takes an arbitrary object and converts it to JSON and embeds it dst.
func AppendInterface(dst []byte, i interface{}) []byte {
func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte {
marshaled, err := json.Marshal(i)
if err != nil {
return AppendString(dst, fmt.Sprintf("marshaling error: %v", err))
return e.AppendString(dst, fmt.Sprintf("marshaling error: %v", err))
}
return AppendEmbeddedJSON(dst, marshaled)
}
// AppendObjectData takes an object in form of a byte array and appends to dst.
func AppendObjectData(dst []byte, o []byte) []byte {
return append(dst, o...)
// AppendIPAddr encodes and inserts an IP Address (IPv4 or IPv6).
func (e Encoder) AppendIPAddr(dst []byte, ip net.IP) []byte {
dst = append(dst, byte(majorTypeTags|additionalTypeIntUint16))
dst = append(dst, byte(additionalTypeTagNetworkAddr>>8))
dst = append(dst, byte(additionalTypeTagNetworkAddr&0xff))
return e.AppendBytes(dst, ip)
}
// AppendArrayStart adds markers to indicate the start of an array.
func AppendArrayStart(dst []byte) []byte {
return append(dst, byte(majorTypeArray|additionalTypeInfiniteCount))
// AppendIPPrefix encodes and inserts an IP Address Prefix (Address + Mask Length).
func (e Encoder) AppendIPPrefix(dst []byte, pfx net.IPNet) []byte {
dst = append(dst, byte(majorTypeTags|additionalTypeIntUint16))
dst = append(dst, byte(additionalTypeTagNetworkPrefix>>8))
dst = append(dst, byte(additionalTypeTagNetworkPrefix&0xff))
// Prefix is a tuple (aka MAP of 1 pair of elements) -
// first element is prefix, second is mask length.
dst = append(dst, byte(majorTypeMap|0x1))
dst = e.AppendBytes(dst, pfx.IP)
maskLen, _ := pfx.Mask.Size()
return e.AppendUint8(dst, uint8(maskLen))
}
// AppendArrayEnd adds markers to indicate the end of an array.
func AppendArrayEnd(dst []byte) []byte {
return append(dst, byte(majorTypeSimpleAndFloat|additionalTypeBreak))
// AppendMACAddr encodes and inserts an Hardware (MAC) address.
func (e Encoder) AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte {
dst = append(dst, byte(majorTypeTags|additionalTypeIntUint16))
dst = append(dst, byte(additionalTypeTagNetworkAddr>>8))
dst = append(dst, byte(additionalTypeTagNetworkAddr&0xff))
return e.AppendBytes(dst, ha)
}
// AppendArrayDelim adds markers to indicate end of a particular array element.
func AppendArrayDelim(dst []byte) []byte {
//No delimiters needed in cbor
return dst
}
func AppendHex (dst []byte, val []byte) []byte {
// AppendHex adds a TAG and inserts a hex bytes as a string.
func (e Encoder) AppendHex(dst []byte, val []byte) []byte {
dst = append(dst, byte(majorTypeTags|additionalTypeIntUint16))
dst = append(dst, byte(additionalTypeTagHexString>>8))
dst = append(dst, byte(additionalTypeTagHexString&0xff))
return AppendBytes(dst, val)
return e.AppendBytes(dst, val)
}

View File

@ -1,44 +1,12 @@
package json
type Encoder struct{}
// AppendKey appends a new key to the output JSON.
func AppendKey(dst []byte, key string) []byte {
func (e Encoder) AppendKey(dst []byte, key string) []byte {
if len(dst) > 1 && dst[len(dst)-1] != '{' {
dst = append(dst, ',')
}
dst = AppendString(dst, key)
dst = e.AppendString(dst, key)
return append(dst, ':')
}
// AppendError encodes the error string to json and appends
// the encoded string to the input byte slice.
func AppendError(dst []byte, err error) []byte {
if err == nil {
return append(dst, `null`...)
}
return AppendString(dst, err.Error())
}
// AppendErrors encodes the error strings to json and
// appends the encoded string list to the input byte slice.
func AppendErrors(dst []byte, errs []error) []byte {
if len(errs) == 0 {
return append(dst, '[', ']')
}
dst = append(dst, '[')
if errs[0] != nil {
dst = AppendString(dst, errs[0].Error())
} else {
dst = append(dst, "null"...)
}
if len(errs) > 1 {
for _, err := range errs[1:] {
if err == nil {
dst = append(dst, ",null"...)
continue
}
dst = AppendString(append(dst, ','), err.Error())
}
}
dst = append(dst, ']')
return dst
}

View File

@ -3,7 +3,7 @@ package json
import "unicode/utf8"
// AppendBytes is a mirror of appendString with []byte arg
func AppendBytes(dst, s []byte) []byte {
func (Encoder) AppendBytes(dst, s []byte) []byte {
dst = append(dst, '"')
for i := 0; i < len(s); i++ {
if !noEscapeTable[s[i]] {
@ -20,7 +20,7 @@ func AppendBytes(dst, s []byte) []byte {
//
// The operation loops though each byte and encodes it as hex using
// the hex lookup table.
func AppendHex(dst, s []byte) []byte {
func (Encoder) AppendHex(dst, s []byte) []byte {
dst = append(dst, '"')
for _, v := range s {
dst = append(dst, hex[v>>4], hex[v&0x0f])

View File

@ -14,15 +14,15 @@ func init() {
// AppendStrings encodes the input strings to json and
// appends the encoded string list to the input byte slice.
func AppendStrings(dst []byte, vals []string) []byte {
func (e Encoder) AppendStrings(dst []byte, vals []string) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
dst = append(dst, '[')
dst = AppendString(dst, vals[0])
dst = e.AppendString(dst, vals[0])
if len(vals) > 1 {
for _, val := range vals[1:] {
dst = AppendString(append(dst, ','), val)
dst = e.AppendString(append(dst, ','), val)
}
}
dst = append(dst, ']')
@ -38,7 +38,7 @@ func AppendStrings(dst []byte, vals []string) []byte {
// entirety to the byte slice.
// If we encounter a byte that does need encoding, switch up
// the operation and perform a byte-by-byte read-encode-append.
func AppendString(dst []byte, s string) []byte {
func (Encoder) AppendString(dst []byte, s string) []byte {
// Start with a double quote.
dst = append(dst, '"')
// Loop through each character in the string.

View File

@ -7,16 +7,16 @@ import (
// AppendTime formats the input time with the given format
// and appends the encoded string to the input byte slice.
func AppendTime(dst []byte, t time.Time, format string) []byte {
func (e Encoder) AppendTime(dst []byte, t time.Time, format string) []byte {
if format == "" {
return AppendInt64(dst, t.Unix())
return e.AppendInt64(dst, t.Unix())
}
return append(t.AppendFormat(append(dst, '"'), format), '"')
}
// AppendTimes converts the input times with the given format
// and appends the encoded string list to the input byte slice.
func AppendTimes(dst []byte, vals []time.Time, format string) []byte {
func (Encoder) AppendTimes(dst []byte, vals []time.Time, format string) []byte {
if format == "" {
return appendUnixTimes(dst, vals)
}
@ -42,7 +42,7 @@ func appendUnixTimes(dst []byte, vals []time.Time) []byte {
dst = strconv.AppendInt(dst, vals[0].Unix(), 10)
if len(vals) > 1 {
for _, t := range vals[1:] {
dst = strconv.AppendInt(dst, t.Unix(), 10)
dst = strconv.AppendInt(append(dst, ','), t.Unix(), 10)
}
}
dst = append(dst, ']')
@ -51,24 +51,24 @@ func appendUnixTimes(dst []byte, vals []time.Time) []byte {
// AppendDuration formats the input duration with the given unit & format
// and appends the encoded string to the input byte slice.
func AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte {
func (e Encoder) AppendDuration(dst []byte, d time.Duration, unit time.Duration, useInt bool) []byte {
if useInt {
return strconv.AppendInt(dst, int64(d/unit), 10)
}
return AppendFloat64(dst, float64(d)/float64(unit))
return e.AppendFloat64(dst, float64(d)/float64(unit))
}
// AppendDurations formats the input durations with the given unit & format
// and appends the encoded string list to the input byte slice.
func AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte {
func (e Encoder) AppendDurations(dst []byte, vals []time.Duration, unit time.Duration, useInt bool) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
dst = append(dst, '[')
dst = AppendDuration(dst, vals[0], unit, useInt)
dst = e.AppendDuration(dst, vals[0], unit, useInt)
if len(vals) > 1 {
for _, d := range vals[1:] {
dst = AppendDuration(append(dst, ','), d, unit, useInt)
dst = e.AppendDuration(append(dst, ','), d, unit, useInt)
}
}
dst = append(dst, ']')

View File

@ -4,18 +4,57 @@ import (
"encoding/json"
"fmt"
"math"
"net"
"strconv"
)
// AppendNil inserts a 'Nil' object into the dst byte array.
func (Encoder) AppendNil(dst []byte) []byte {
return append(dst, "null"...)
}
// AppendBeginMarker inserts a map start into the dst byte array.
func (Encoder) AppendBeginMarker(dst []byte) []byte {
return append(dst, '{')
}
// AppendEndMarker inserts a map end into the dst byte array.
func (Encoder) AppendEndMarker(dst []byte) []byte {
return append(dst, '}')
}
// AppendLineBreak appends a line break.
func (Encoder) AppendLineBreak(dst []byte) []byte {
return append(dst, '\n')
}
// AppendArrayStart adds markers to indicate the start of an array.
func (Encoder) AppendArrayStart(dst []byte) []byte {
return append(dst, '[')
}
// AppendArrayEnd adds markers to indicate the end of an array.
func (Encoder) AppendArrayEnd(dst []byte) []byte {
return append(dst, ']')
}
// AppendArrayDelim adds markers to indicate end of a particular array element.
func (Encoder) AppendArrayDelim(dst []byte) []byte {
if len(dst) > 0 {
return append(dst, ',')
}
return dst
}
// AppendBool converts the input bool to a string and
// appends the encoded string to the input byte slice.
func AppendBool(dst []byte, val bool) []byte {
func (Encoder) AppendBool(dst []byte, val bool) []byte {
return strconv.AppendBool(dst, val)
}
// AppendBools encodes the input bools to json and
// appends the encoded string list to the input byte slice.
func AppendBools(dst []byte, vals []bool) []byte {
func (Encoder) AppendBools(dst []byte, vals []bool) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
@ -32,13 +71,13 @@ func AppendBools(dst []byte, vals []bool) []byte {
// AppendInt converts the input int to a string and
// appends the encoded string to the input byte slice.
func AppendInt(dst []byte, val int) []byte {
func (Encoder) AppendInt(dst []byte, val int) []byte {
return strconv.AppendInt(dst, int64(val), 10)
}
// AppendInts encodes the input ints to json and
// appends the encoded string list to the input byte slice.
func AppendInts(dst []byte, vals []int) []byte {
func (Encoder) AppendInts(dst []byte, vals []int) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
@ -55,13 +94,13 @@ func AppendInts(dst []byte, vals []int) []byte {
// AppendInt8 converts the input []int8 to a string and
// appends the encoded string to the input byte slice.
func AppendInt8(dst []byte, val int8) []byte {
func (Encoder) AppendInt8(dst []byte, val int8) []byte {
return strconv.AppendInt(dst, int64(val), 10)
}
// AppendInts8 encodes the input int8s to json and
// appends the encoded string list to the input byte slice.
func AppendInts8(dst []byte, vals []int8) []byte {
func (Encoder) AppendInts8(dst []byte, vals []int8) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
@ -78,13 +117,13 @@ func AppendInts8(dst []byte, vals []int8) []byte {
// AppendInt16 converts the input int16 to a string and
// appends the encoded string to the input byte slice.
func AppendInt16(dst []byte, val int16) []byte {
func (Encoder) AppendInt16(dst []byte, val int16) []byte {
return strconv.AppendInt(dst, int64(val), 10)
}
// AppendInts16 encodes the input int16s to json and
// appends the encoded string list to the input byte slice.
func AppendInts16(dst []byte, vals []int16) []byte {
func (Encoder) AppendInts16(dst []byte, vals []int16) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
@ -101,13 +140,13 @@ func AppendInts16(dst []byte, vals []int16) []byte {
// AppendInt32 converts the input int32 to a string and
// appends the encoded string to the input byte slice.
func AppendInt32(dst []byte, val int32) []byte {
func (Encoder) AppendInt32(dst []byte, val int32) []byte {
return strconv.AppendInt(dst, int64(val), 10)
}
// AppendInts32 encodes the input int32s to json and
// appends the encoded string list to the input byte slice.
func AppendInts32(dst []byte, vals []int32) []byte {
func (Encoder) AppendInts32(dst []byte, vals []int32) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
@ -124,13 +163,13 @@ func AppendInts32(dst []byte, vals []int32) []byte {
// AppendInt64 converts the input int64 to a string and
// appends the encoded string to the input byte slice.
func AppendInt64(dst []byte, val int64) []byte {
func (Encoder) AppendInt64(dst []byte, val int64) []byte {
return strconv.AppendInt(dst, val, 10)
}
// AppendInts64 encodes the input int64s to json and
// appends the encoded string list to the input byte slice.
func AppendInts64(dst []byte, vals []int64) []byte {
func (Encoder) AppendInts64(dst []byte, vals []int64) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
@ -147,13 +186,13 @@ func AppendInts64(dst []byte, vals []int64) []byte {
// AppendUint converts the input uint to a string and
// appends the encoded string to the input byte slice.
func AppendUint(dst []byte, val uint) []byte {
func (Encoder) AppendUint(dst []byte, val uint) []byte {
return strconv.AppendUint(dst, uint64(val), 10)
}
// AppendUints encodes the input uints to json and
// appends the encoded string list to the input byte slice.
func AppendUints(dst []byte, vals []uint) []byte {
func (Encoder) AppendUints(dst []byte, vals []uint) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
@ -170,13 +209,13 @@ func AppendUints(dst []byte, vals []uint) []byte {
// AppendUint8 converts the input uint8 to a string and
// appends the encoded string to the input byte slice.
func AppendUint8(dst []byte, val uint8) []byte {
func (Encoder) AppendUint8(dst []byte, val uint8) []byte {
return strconv.AppendUint(dst, uint64(val), 10)
}
// AppendUints8 encodes the input uint8s to json and
// appends the encoded string list to the input byte slice.
func AppendUints8(dst []byte, vals []uint8) []byte {
func (Encoder) AppendUints8(dst []byte, vals []uint8) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
@ -193,13 +232,13 @@ func AppendUints8(dst []byte, vals []uint8) []byte {
// AppendUint16 converts the input uint16 to a string and
// appends the encoded string to the input byte slice.
func AppendUint16(dst []byte, val uint16) []byte {
func (Encoder) AppendUint16(dst []byte, val uint16) []byte {
return strconv.AppendUint(dst, uint64(val), 10)
}
// AppendUints16 encodes the input uint16s to json and
// appends the encoded string list to the input byte slice.
func AppendUints16(dst []byte, vals []uint16) []byte {
func (Encoder) AppendUints16(dst []byte, vals []uint16) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
@ -216,13 +255,13 @@ func AppendUints16(dst []byte, vals []uint16) []byte {
// AppendUint32 converts the input uint32 to a string and
// appends the encoded string to the input byte slice.
func AppendUint32(dst []byte, val uint32) []byte {
func (Encoder) AppendUint32(dst []byte, val uint32) []byte {
return strconv.AppendUint(dst, uint64(val), 10)
}
// AppendUints32 encodes the input uint32s to json and
// appends the encoded string list to the input byte slice.
func AppendUints32(dst []byte, vals []uint32) []byte {
func (Encoder) AppendUints32(dst []byte, vals []uint32) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
@ -239,13 +278,13 @@ func AppendUints32(dst []byte, vals []uint32) []byte {
// AppendUint64 converts the input uint64 to a string and
// appends the encoded string to the input byte slice.
func AppendUint64(dst []byte, val uint64) []byte {
func (Encoder) AppendUint64(dst []byte, val uint64) []byte {
return strconv.AppendUint(dst, uint64(val), 10)
}
// AppendUints64 encodes the input uint64s to json and
// appends the encoded string list to the input byte slice.
func AppendUints64(dst []byte, vals []uint64) []byte {
func (Encoder) AppendUints64(dst []byte, vals []uint64) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
@ -260,9 +299,7 @@ func AppendUints64(dst []byte, vals []uint64) []byte {
return dst
}
// AppendFloat converts the input float to a string and
// appends the encoded string to the input byte slice.
func AppendFloat(dst []byte, val float64, bitSize int) []byte {
func appendFloat(dst []byte, val float64, bitSize int) []byte {
// JSON does not permit NaN or Infinity. A typical JSON encoder would fail
// with an error, but a logging library wants the data to get thru so we
// make a tradeoff and store those types as string.
@ -279,21 +316,21 @@ func AppendFloat(dst []byte, val float64, bitSize int) []byte {
// AppendFloat32 converts the input float32 to a string and
// appends the encoded string to the input byte slice.
func AppendFloat32(dst []byte, val float32) []byte {
return AppendFloat(dst, float64(val), 32)
func (Encoder) AppendFloat32(dst []byte, val float32) []byte {
return appendFloat(dst, float64(val), 32)
}
// AppendFloats32 encodes the input float32s to json and
// appends the encoded string list to the input byte slice.
func AppendFloats32(dst []byte, vals []float32) []byte {
func (Encoder) AppendFloats32(dst []byte, vals []float32) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
dst = append(dst, '[')
dst = AppendFloat(dst, float64(vals[0]), 32)
dst = appendFloat(dst, float64(vals[0]), 32)
if len(vals) > 1 {
for _, val := range vals[1:] {
dst = AppendFloat(append(dst, ','), float64(val), 32)
dst = appendFloat(append(dst, ','), float64(val), 32)
}
}
dst = append(dst, ']')
@ -302,21 +339,21 @@ func AppendFloats32(dst []byte, vals []float32) []byte {
// AppendFloat64 converts the input float64 to a string and
// appends the encoded string to the input byte slice.
func AppendFloat64(dst []byte, val float64) []byte {
return AppendFloat(dst, val, 64)
func (Encoder) AppendFloat64(dst []byte, val float64) []byte {
return appendFloat(dst, val, 64)
}
// AppendFloats64 encodes the input float64s to json and
// appends the encoded string list to the input byte slice.
func AppendFloats64(dst []byte, vals []float64) []byte {
func (Encoder) AppendFloats64(dst []byte, vals []float64) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
dst = append(dst, '[')
dst = AppendFloat(dst, vals[0], 32)
dst = appendFloat(dst, vals[0], 32)
if len(vals) > 1 {
for _, val := range vals[1:] {
dst = AppendFloat(append(dst, ','), val, 64)
dst = appendFloat(append(dst, ','), val, 64)
}
}
dst = append(dst, ']')
@ -325,15 +362,17 @@ func AppendFloats64(dst []byte, vals []float64) []byte {
// AppendInterface marshals the input interface to a string and
// appends the encoded string to the input byte slice.
func AppendInterface(dst []byte, i interface{}) []byte {
func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte {
marshaled, err := json.Marshal(i)
if err != nil {
return AppendString(dst, fmt.Sprintf("marshaling error: %v", err))
return e.AppendString(dst, fmt.Sprintf("marshaling error: %v", err))
}
return append(dst, marshaled...)
}
func AppendObjectData(dst []byte, o []byte) []byte {
// AppendObjectData takes in an object that is already in a byte array
// and adds it to the dst.
func (Encoder) AppendObjectData(dst []byte, o []byte) []byte {
// Two conditions we want to put a ',' between existing content and
// new content:
// 1. new content starts with '{' - which shd be dropped OR
@ -345,3 +384,19 @@ func AppendObjectData(dst []byte, o []byte) []byte {
}
return append(dst, o...)
}
// AppendIPAddr adds IPv4 or IPv6 address to dst.
func (e Encoder) AppendIPAddr(dst []byte, ip net.IP) []byte {
return e.AppendString(dst, ip.String())
}
// AppendIPPrefix adds IPv4 or IPv6 Prefix (address & mask) to dst.
func (e Encoder) AppendIPPrefix(dst []byte, pfx net.IPNet) []byte {
return e.AppendString(dst, pfx.String())
}
// AppendMACAddr adds MAC address to dst.
func (e Encoder) AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte {
return e.AppendString(dst, ha.String())
}

42
vendor/github.com/rs/zerolog/log.go generated vendored
View File

@ -148,6 +148,28 @@ func (l Level) String() string {
return ""
}
// ParseLevel converts a level string into a zerolog Level value.
// returns an error if the input string does not match known values.
func ParseLevel(levelStr string) (Level, error) {
switch levelStr {
case DebugLevel.String():
return DebugLevel, nil
case InfoLevel.String():
return InfoLevel, nil
case WarnLevel.String():
return WarnLevel, nil
case ErrorLevel.String():
return ErrorLevel, nil
case FatalLevel.String():
return FatalLevel, nil
case PanicLevel.String():
return PanicLevel, nil
case NoLevel.String():
return NoLevel, nil
}
return NoLevel, fmt.Errorf("Unknown Level String: '%s', defaulting to NoLevel", levelStr)
}
// A Logger represents an active logging object that generates lines
// of JSON output to an io.Writer. Each logging operation makes a single
// call to the Writer's Write method. There is no guaranty on access
@ -270,22 +292,24 @@ func (l *Logger) Error() *Event {
}
// Fatal starts a new message with fatal level. The os.Exit(1) function
// is called by the Msg method.
// is called by the Msg method, which terminates the program immediately.
//
// You must call Msg on the returned event in order to send the event.
func (l *Logger) Fatal() *Event {
return l.newEvent(FatalLevel, func(msg string) { os.Exit(1) })
}
// Panic starts a new message with panic level. The message is also sent
// to the panic function.
// Panic starts a new message with panic level. The panic() function
// is called by the Msg method, which stops the ordinary flow of a goroutine.
//
// You must call Msg on the returned event in order to send the event.
func (l *Logger) Panic() *Event {
return l.newEvent(PanicLevel, func(msg string) { panic(msg) })
}
// WithLevel starts a new message with level.
// WithLevel starts a new message with level. Unlike Fatal and Panic
// methods, WithLevel does not terminate the program or stop the ordinary
// flow of a gourotine when used with their respective levels.
//
// You must call Msg on the returned event in order to send the event.
func (l *Logger) WithLevel(level Level) *Event {
@ -299,9 +323,9 @@ func (l *Logger) WithLevel(level Level) *Event {
case ErrorLevel:
return l.Error()
case FatalLevel:
return l.Fatal()
return l.newEvent(FatalLevel, nil)
case PanicLevel:
return l.Panic()
return l.newEvent(PanicLevel, nil)
case NoLevel:
return l.Log()
case Disabled:
@ -352,21 +376,21 @@ func (l *Logger) newEvent(level Level, done func(string)) *Event {
if !enabled {
return nil
}
e := newEvent(l.w, level, true)
e := newEvent(l.w, level)
e.done = done
e.ch = l.hooks
if level != NoLevel {
e.Str(LevelFieldName, level.String())
}
if l.context != nil && len(l.context) > 0 {
e.buf = appendObjectData(e.buf, l.context)
e.buf = enc.AppendObjectData(e.buf, l.context)
}
return e
}
// should returns true if the log event should be logged.
func (l *Logger) should(lvl Level) bool {
if lvl < l.level || lvl < globalLevel() {
if lvl < l.level || lvl < GlobalLevel() {
return false
}
if l.sampler != nil && !samplingDisabled() {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 377 KiB

After

Width:  |  Height:  |  Size: 141 KiB

Some files were not shown because too many files have changed in this diff Show More