Upgrade to go 1.19 and update dependencies (#3069)

* Update to go 1.19
* Update dependencies
* Update cross-compile script
* Add missing targets to cross-compile-all
* Update cache action to remove warning
This commit is contained in:
WithoutPants
2022-11-04 13:41:26 +11:00
committed by GitHub
parent f25881a3bf
commit bba7c23957
939 changed files with 101336 additions and 43819 deletions

View File

@@ -1,8 +0,0 @@
language: go
go:
- 1.9
- "1.10"
- tip
matrix:
allow_failures:
- go: tip

View File

@@ -88,13 +88,14 @@ handler = c.Handler(handler)
* **AllowedOrigins** `[]string`: A list of origins a cross-domain request can be executed from. If the special `*` value is present in the list, all origins will be allowed. An origin may contain a wildcard (`*`) to replace 0 or more characters (i.e.: `http://*.domain.com`). Usage of wildcards implies a small performance penality. Only one wildcard can be used per origin. The default value is `*`.
* **AllowOriginFunc** `func (origin string) bool`: A custom function to validate the origin. It takes the origin as an argument and returns true if allowed, or false otherwise. If this option is set, the content of `AllowedOrigins` is ignored.
* **AllowOriginRequestFunc** `func (r *http.Request origin string) bool`: A custom function to validate the origin. It takes the HTTP Request object and the origin as argument and returns true if allowed or false otherwise. If this option is set, the content of `AllowedOrigins` and `AllowOriginFunc` is ignored
* **AllowOriginRequestFunc** `func (r *http.Request, origin string) bool`: A custom function to validate the origin. It takes the HTTP Request object and the origin as argument and returns true if allowed or false otherwise. If this option is set, the content of `AllowedOrigins` and `AllowOriginFunc` is ignored
* **AllowedMethods** `[]string`: A list of methods the client is allowed to use with cross-domain requests. Default value is simple methods (`GET` and `POST`).
* **AllowedHeaders** `[]string`: A list of non simple headers the client is allowed to use with cross-domain requests.
* **ExposedHeaders** `[]string`: Indicates which headers are safe to expose to the API of a CORS API specification
* **AllowCredentials** `bool`: Indicates whether the request can include user credentials like cookies, HTTP authentication or client side SSL certificates. The default is `false`.
* **MaxAge** `int`: Indicates how long (in seconds) the results of a preflight request can be cached. The default is `0` which stands for no max age.
* **OptionsPassthrough** `bool`: Instructs preflight to let other potential next handlers to process the `OPTIONS` method. Turn this on if your application handles `OPTIONS`.
* **OptionsSuccessStatus** `int`: Provides a status code to use for successful OPTIONS requests. Default value is `http.StatusNoContent` (`204`).
* **Debug** `bool`: Debugging flag adds additional output to debug server side CORS issues.
See [API documentation](http://godoc.org/github.com/rs/cors) for more info.

65
vendor/github.com/rs/cors/cors.go generated vendored
View File

@@ -5,8 +5,8 @@ as defined by http://www.w3.org/TR/cors/
You can configure it by passing an option struct to cors.New:
c := cors.New(cors.Options{
AllowedOrigins: []string{"foo.com"},
AllowedMethods: []string{"GET", "POST", "DELETE"},
AllowedOrigins: []string{"foo.com"},
AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodDelete},
AllowCredentials: true,
})
@@ -41,7 +41,7 @@ type Options struct {
// as argument and returns true if allowed or false otherwise. If this option is
// set, the content of AllowedOrigins is ignored.
AllowOriginFunc func(origin string) bool
// AllowOriginFunc is a custom function to validate the origin. It takes the HTTP Request object and the origin as
// AllowOriginRequestFunc is a custom function to validate the origin. It takes the HTTP Request object and the origin as
// argument and returns true if allowed or false otherwise. If this option is set, the content of `AllowedOrigins`
// and `AllowOriginFunc` is ignored.
AllowOriginRequestFunc func(r *http.Request, origin string) bool
@@ -65,14 +65,22 @@ type Options struct {
// OptionsPassthrough instructs preflight to let other potential next handlers to
// process the OPTIONS method. Turn this on if your application handles OPTIONS.
OptionsPassthrough bool
// Provides a status code to use for successful OPTIONS requests.
// Default value is http.StatusNoContent (204).
OptionsSuccessStatus int
// Debugging flag adds additional output to debug server side CORS issues
Debug bool
}
// Logger generic interface for logger
type Logger interface {
Printf(string, ...interface{})
}
// Cors http handler
type Cors struct {
// Debug logger
Log *log.Logger
Log Logger
// Normalized list of plain allowed origins
allowedOrigins []string
// List of allowed origins containing wildcards
@@ -92,8 +100,10 @@ type Cors struct {
allowedOriginsAll bool
// Set to true when allowed headers contains a "*"
allowedHeadersAll bool
allowCredentials bool
optionPassthrough bool
// Status code to use for successful OPTIONS requests
optionsSuccessStatus int
allowCredentials bool
optionPassthrough bool
}
// New creates a new Cors handler with the provided options.
@@ -106,7 +116,7 @@ func New(options Options) *Cors {
maxAge: options.MaxAge,
optionPassthrough: options.OptionsPassthrough,
}
if options.Debug {
if options.Debug && c.Log == nil {
c.Log = log.New(os.Stdout, "[cors] ", log.LstdFlags)
}
@@ -161,11 +171,18 @@ func New(options Options) *Cors {
// Allowed Methods
if len(options.AllowedMethods) == 0 {
// Default is spec's "simple" methods
c.allowedMethods = []string{"GET", "POST", "HEAD"}
c.allowedMethods = []string{http.MethodGet, http.MethodPost, http.MethodHead}
} else {
c.allowedMethods = convert(options.AllowedMethods, strings.ToUpper)
}
// Options Success Status Code
if options.OptionsSuccessStatus == 0 {
c.optionsSuccessStatus = http.StatusNoContent
} else {
c.optionsSuccessStatus = options.OptionsSuccessStatus
}
return c
}
@@ -178,8 +195,15 @@ func Default() *Cors {
// origins with all standard methods with any header and credentials.
func AllowAll() *Cors {
return New(Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"HEAD", "GET", "POST", "PUT", "PATCH", "DELETE"},
AllowedOrigins: []string{"*"},
AllowedMethods: []string{
http.MethodHead,
http.MethodGet,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
},
AllowedHeaders: []string{"*"},
AllowCredentials: false,
})
@@ -199,7 +223,7 @@ func (c *Cors) Handler(h http.Handler) http.Handler {
if c.optionPassthrough {
h.ServeHTTP(w, r)
} else {
w.WriteHeader(http.StatusOK)
w.WriteHeader(c.optionsSuccessStatus)
}
} else {
c.logf("Handler: Actual request")
@@ -214,6 +238,8 @@ func (c *Cors) HandlerFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
c.logf("HandlerFunc: Preflight request")
c.handlePreflight(w, r)
w.WriteHeader(c.optionsSuccessStatus)
} else {
c.logf("HandlerFunc: Actual request")
c.handleActualRequest(w, r)
@@ -232,7 +258,7 @@ func (c *Cors) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.Handl
if c.optionPassthrough {
next(w, r)
} else {
w.WriteHeader(http.StatusOK)
w.WriteHeader(c.optionsSuccessStatus)
}
} else {
c.logf("ServeHTTP: Actual request")
@@ -304,10 +330,6 @@ func (c *Cors) handleActualRequest(w http.ResponseWriter, r *http.Request) {
headers := w.Header()
origin := r.Header.Get("Origin")
if r.Method == http.MethodOptions {
c.logf(" Actual request no headers added: method == %s", r.Method)
return
}
// Always set Vary, see https://github.com/rs/cors/issues/10
headers.Add("Vary", "Origin")
if origin == "" {
@@ -342,13 +364,19 @@ func (c *Cors) handleActualRequest(w http.ResponseWriter, r *http.Request) {
c.logf(" Actual response added headers: %v", headers)
}
// convenience method. checks if debugging is turned on before printing
// convenience method. checks if a logger is set.
func (c *Cors) logf(format string, a ...interface{}) {
if c.Log != nil {
c.Log.Printf(format, a...)
}
}
// check the Origin of a request. No origin at all is also allowed.
func (c *Cors) OriginAllowed(r *http.Request) bool {
origin := r.Header.Get("Origin")
return c.isOriginAllowed(r, origin)
}
// isOriginAllowed checks if a given origin is allowed to perform cross-domain requests
// on the endpoint
func (c *Cors) isOriginAllowed(r *http.Request, origin string) bool {
@@ -376,7 +404,7 @@ func (c *Cors) isOriginAllowed(r *http.Request, origin string) bool {
}
// isMethodAllowed checks if a given method can be used as part of a cross-domain request
// on the endpoing
// on the endpoint
func (c *Cors) isMethodAllowed(method string) bool {
if len(c.allowedMethods) == 0 {
// If no method allowed, always return false, even for preflight request
@@ -407,6 +435,7 @@ func (c *Cors) areHeadersAllowed(requestedHeaders []string) bool {
for _, h := range c.allowedHeaders {
if h == header {
found = true
break
}
}
if !found {

4
vendor/github.com/rs/cors/utils.go generated vendored
View File

@@ -12,7 +12,7 @@ type wildcard struct {
}
func (w wildcard) match(s string) bool {
return len(s) >= len(w.prefix+w.suffix) && strings.HasPrefix(s, w.prefix) && strings.HasSuffix(s, w.suffix)
return len(s) >= len(w.prefix)+len(w.suffix) && strings.HasPrefix(s, w.prefix) && strings.HasSuffix(s, w.suffix)
}
// convert converts a list of string using the passed converter function
@@ -52,7 +52,7 @@ func parseHeaderList(headerList string) []string {
} else {
h = append(h, b)
}
case b == '-' || b == '_' || (b >= '0' && b <= '9'):
case b == '-' || b == '_' || b == '.' || (b >= '0' && b <= '9'):
h = append(h, b)
}

View File

@@ -399,6 +399,8 @@ log.Logger = log.With().Str("foo", "bar").Logger()
### Add file and line number to log
Equivalent of `Llongfile`:
```go
log.Logger = log.With().Caller().Logger()
log.Info().Msg("hello world")
@@ -406,10 +408,29 @@ log.Info().Msg("hello world")
// Output: {"level": "info", "message": "hello world", "caller": "/go/src/your_project/some_file:21"}
```
Equivalent of `Lshortfile`:
```go
zerolog.CallerMarshalFunc = func(file string, line int) string {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
return file + ":" + strconv.Itoa(line)
}
log.Logger = log.With().Caller().Logger()
log.Info().Msg("hello world")
// Output: {"level": "info", "message": "hello world", "caller": "some_file:21"}
```
### Thread-safe, lock-free, non-blocking writer
If your writer might be slow or not thread-safe and you need your log producers to never get slowed down by a slow writer, you can use a `diode.Writer` as follow:
If your writer might be slow or not thread-safe and you need your log producers to never get slowed down by a slow writer, you can use a `diode.Writer` as follows:
```go
wr := diode.NewWriter(os.Stdout, 1000, 10*time.Millisecond, func(missed int) {
@@ -560,11 +581,11 @@ func main() {
// Output (Line 1: Console; Line 2: Stdout)
// 12:36PM INF Hello World!
// {"level":"info","time":"2019-11-07T12:36:38+03:00","message":"Hello World!"}
```
```
## Global Settings
Some settings can be changed and will by applied to all loggers:
Some settings can be changed and will be applied to all loggers:
* `log.Logger`: You can set this value to customize the global logger (the one used by package level methods).
* `zerolog.SetGlobalLevel`: Can raise the minimum level of all loggers. Call this with `zerolog.Disabled` to disable logging altogether (quiet mode).
@@ -604,7 +625,7 @@ Most fields are also available in the slice format (`Strs` for `[]string`, `Errs
## Binary Encoding
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:
In addition to the default JSON encoding, `zerolog` can produce binary logs using [CBOR](https://cbor.io) encoding. The choice of encoding can be decided at compile time using the build tag `binary_log` as follows:
```bash
go build -tags binary_log .

View File

@@ -49,7 +49,7 @@ func (*Array) MarshalZerologArray(*Array) {
func (a *Array) write(dst []byte) []byte {
dst = enc.AppendArrayStart(dst)
if len(a.buf) > 0 {
dst = append(append(dst, a.buf...))
dst = append(dst, a.buf...)
}
dst = enc.AppendArrayEnd(dst)
putArray(a)
@@ -193,7 +193,7 @@ func (a *Array) Float64(f float64) *Array {
return a
}
// Time append append t formated as string using zerolog.TimeFieldFormat.
// Time append append t formatted as string using zerolog.TimeFieldFormat.
func (a *Array) Time(t time.Time) *Array {
a.buf = enc.AppendTime(enc.AppendArrayDelim(a.buf), t, TimeFieldFormat)
return a

View File

@@ -12,6 +12,8 @@ import (
"strings"
"sync"
"time"
"github.com/mattn/go-colorable"
)
const (
@@ -61,6 +63,9 @@ type ConsoleWriter struct {
// PartsExclude defines parts to not display in output.
PartsExclude []string
// FieldsExclude defines contextual fields to not display in output.
FieldsExclude []string
FormatTimestamp Formatter
FormatLevel Formatter
FormatCaller Formatter
@@ -69,6 +74,8 @@ type ConsoleWriter struct {
FormatFieldValue Formatter
FormatErrFieldName Formatter
FormatErrFieldValue Formatter
FormatExtra func(map[string]interface{}, *bytes.Buffer) error
}
// NewConsoleWriter creates and initializes a new ConsoleWriter.
@@ -83,11 +90,21 @@ func NewConsoleWriter(options ...func(w *ConsoleWriter)) ConsoleWriter {
opt(&w)
}
// Fix color on Windows
if w.Out == os.Stdout || w.Out == os.Stderr {
w.Out = colorable.NewColorable(w.Out.(*os.File))
}
return w
}
// Write transforms the JSON input with formatters and appends to w.Out.
func (w ConsoleWriter) Write(p []byte) (n int, err error) {
// Fix color on Windows
if w.Out == os.Stdout || w.Out == os.Stderr {
w.Out = colorable.NewColorable(w.Out.(*os.File))
}
if w.PartsOrder == nil {
w.PartsOrder = consoleDefaultPartsOrder()
}
@@ -113,10 +130,18 @@ func (w ConsoleWriter) Write(p []byte) (n int, err error) {
w.writeFields(evt, buf)
if w.FormatExtra != nil {
err = w.FormatExtra(evt, buf)
if err != nil {
return n, err
}
}
err = buf.WriteByte('\n')
if err != nil {
return n, err
}
_, err = buf.WriteTo(w.Out)
return len(p), err
}
@@ -125,6 +150,17 @@ func (w ConsoleWriter) Write(p []byte) (n int, err error) {
func (w ConsoleWriter) writeFields(evt map[string]interface{}, buf *bytes.Buffer) {
var fields = make([]string, 0, len(evt))
for field := range evt {
var isExcluded bool
for _, excluded := range w.FieldsExclude {
if field == excluded {
isExcluded = true
break
}
}
if isExcluded {
continue
}
switch field {
case LevelFieldName, TimestampFieldName, MessageFieldName, CallerFieldName:
continue
@@ -133,7 +169,8 @@ func (w ConsoleWriter) writeFields(evt map[string]interface{}, buf *bytes.Buffer
}
sort.Strings(fields)
if len(fields) > 0 {
// Write space only if something has already been written to the buffer, and if there are fields.
if buf.Len() > 0 && len(fields) > 0 {
buf.WriteByte(' ')
}
@@ -194,7 +231,7 @@ func (w ConsoleWriter) writeFields(evt map[string]interface{}, buf *bytes.Buffer
case json.Number:
buf.WriteString(fv(fValue))
default:
b, err := json.Marshal(fValue)
b, err := InterfaceMarshalFunc(fValue)
if err != nil {
fmt.Fprintf(buf, colorize("[error: %v]", colorRed, w.NoColor), err)
} else {
@@ -256,10 +293,10 @@ func (w ConsoleWriter) writePart(buf *bytes.Buffer, evt map[string]interface{},
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(' ')
if buf.Len() > 0 {
buf.WriteByte(' ') // Write space only if not the first part
}
buf.WriteString(s)
}
}
@@ -304,7 +341,7 @@ func consoleDefaultFormatTimestamp(timeFormat string, noColor bool) Formatter {
if err != nil {
t = tt
} else {
t = ts.Format(timeFormat)
t = ts.Local().Format(timeFormat)
}
case json.Number:
i, err := tt.Int64()
@@ -320,7 +357,7 @@ func consoleDefaultFormatTimestamp(timeFormat string, noColor bool) Formatter {
nsec = int64(time.Duration(i) * time.Microsecond)
sec = 0
}
ts := time.Unix(sec, nsec).UTC()
ts := time.Unix(sec, nsec)
t = ts.Format(timeFormat)
}
}

View File

@@ -25,9 +25,9 @@ type ctxKey struct{}
// l.UpdateContext(func(c Context) Context {
// return c.Str("bar", "baz")
// })
func (l *Logger) WithContext(ctx context.Context) context.Context {
func (l Logger) WithContext(ctx context.Context) context.Context {
if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok {
if lp == l {
if lp == &l {
// Do not store same logger.
return ctx
}
@@ -35,7 +35,7 @@ func (l *Logger) WithContext(ctx context.Context) context.Context {
// 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

@@ -129,6 +129,13 @@ func (e *Event) Msgf(format string, v ...interface{}) {
e.msg(fmt.Sprintf(format, v...))
}
func (e *Event) MsgFunc(createMsg func() string) {
if e == nil {
return
}
e.msg(createMsg())
}
func (e *Event) msg(msg string) {
for _, hook := range e.ch {
hook.Run(e, e.level, msg)
@@ -645,7 +652,7 @@ func (e *Event) Timestamp() *Event {
return e
}
// Time adds the field key with t formated as string using zerolog.TimeFieldFormat.
// Time adds the field key with t formatted as string using zerolog.TimeFieldFormat.
func (e *Event) Time(key string, t time.Time) *Event {
if e == nil {
return e
@@ -654,7 +661,7 @@ func (e *Event) Time(key string, t time.Time) *Event {
return e
}
// Times adds the field key with t formated as string using zerolog.TimeFieldFormat.
// Times adds the field key with t formatted as string using zerolog.TimeFieldFormat.
func (e *Event) Times(key string, t []time.Time) *Event {
if e == nil {
return e
@@ -737,11 +744,11 @@ func (e *Event) caller(skip int) *Event {
if e == nil {
return e
}
_, file, line, ok := runtime.Caller(skip + e.skipFrame)
pc, file, line, ok := runtime.Caller(skip + e.skipFrame)
if !ok {
return e
}
e.buf = enc.AppendString(enc.AppendKey(e.buf, CallerFieldName), CallerMarshalFunc(file, line))
e.buf = enc.AppendString(enc.AppendKey(e.buf, CallerFieldName), CallerMarshalFunc(pc, file, line))
return e
}

View File

@@ -19,6 +19,10 @@ const (
// TimeFormatUnixMicro defines a time format that makes time fields to be
// serialized as Unix timestamp integers in microseconds.
TimeFormatUnixMicro = "UNIXMICRO"
// TimeFormatUnixNano defines a time format that makes time fields to be
// serialized as Unix timestamp integers in nanoseconds.
TimeFormatUnixNano = "UNIXNANO"
)
var (
@@ -61,7 +65,7 @@ var (
CallerSkipFrameCount = 2
// CallerMarshalFunc allows customization of global caller marshaling
CallerMarshalFunc = func(file string, line int) string {
CallerMarshalFunc = func(pc uintptr, file string, line int) string {
return file + ":" + strconv.Itoa(line)
}
@@ -81,7 +85,7 @@ var (
InterfaceMarshalFunc = json.Marshal
// TimeFieldFormat defines the time format of the Time field type. If set to
// TimeFormatUnix, TimeFormatUnixMs or TimeFormatUnixMicro, the time is formatted as an UNIX
// TimeFormatUnix, TimeFormatUnixMs, TimeFormatUnixMicro or TimeFormatUnixNano, the time is formatted as a UNIX
// timestamp as integer.
TimeFieldFormat = time.RFC3339

View File

@@ -67,7 +67,7 @@ const (
var IntegerTimeFieldFormat = time.RFC3339
// NanoTimeFieldFormat indicates the format of timestamp decoded
// from a float value (time in seconds and nano seconds).
// from a float value (time in seconds and nanoseconds).
var NanoTimeFieldFormat = time.RFC3339Nano
func appendCborTypePrefix(dst []byte, major byte, number uint64) []byte {
@@ -91,7 +91,8 @@ func appendCborTypePrefix(dst []byte, major byte, number uint64) []byte {
minor = additionalTypeIntUint64
}
dst = append(dst, byte(major|minor))
dst = append(dst, major|minor)
byteCount--
for ; byteCount >= 0; byteCount-- {
dst = append(dst, byte(number>>(uint(byteCount)*8)))

View File

@@ -43,7 +43,7 @@ func readByte(src *bufio.Reader) byte {
return b
}
func decodeIntAdditonalType(src *bufio.Reader, minor byte) int64 {
func decodeIntAdditionalType(src *bufio.Reader, minor byte) int64 {
val := int64(0)
if minor <= 23 {
val = int64(minor)
@@ -77,7 +77,7 @@ func decodeInteger(src *bufio.Reader) int64 {
if major != majorTypeUnsignedInt && major != majorTypeNegativeInt {
panic(fmt.Errorf("Major type is: %d in decodeInteger!! (expected 0 or 1)", major))
}
val := decodeIntAdditonalType(src, minor)
val := decodeIntAdditionalType(src, minor)
if major == 0 {
return val
}
@@ -204,7 +204,7 @@ func decodeString(src *bufio.Reader, noQuotes bool) []byte {
if !noQuotes {
result = append(result, '"')
}
length := decodeIntAdditonalType(src, minor)
length := decodeIntAdditionalType(src, minor)
len := int(length)
pbs := readNBytes(src, len)
result = append(result, pbs...)
@@ -222,7 +222,7 @@ func decodeUTF8String(src *bufio.Reader) []byte {
panic(fmt.Errorf("Major type is: %d in decodeUTF8String", major))
}
result := []byte{'"'}
length := decodeIntAdditonalType(src, minor)
length := decodeIntAdditionalType(src, minor)
len := int(length)
pbs := readNBytes(src, len)
@@ -238,7 +238,7 @@ func decodeUTF8String(src *bufio.Reader) []byte {
return append(dst, '"')
}
}
// The string has no need for encoding an therefore is directly
// The string has no need for encoding and therefore is directly
// appended to the byte slice.
result = append(result, pbs...)
return append(result, '"')
@@ -257,7 +257,7 @@ func array2Json(src *bufio.Reader, dst io.Writer) {
if minor == additionalTypeInfiniteCount {
unSpecifiedCount = true
} else {
length := decodeIntAdditonalType(src, minor)
length := decodeIntAdditionalType(src, minor)
len = int(length)
}
for i := 0; unSpecifiedCount || i < len; i++ {
@@ -266,7 +266,7 @@ func array2Json(src *bufio.Reader, dst io.Writer) {
if e != nil {
panic(e)
}
if pb[0] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) {
if pb[0] == majorTypeSimpleAndFloat|additionalTypeBreak {
readByte(src)
break
}
@@ -277,7 +277,7 @@ func array2Json(src *bufio.Reader, dst io.Writer) {
if e != nil {
panic(e)
}
if pb[0] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) {
if pb[0] == majorTypeSimpleAndFloat|additionalTypeBreak {
readByte(src)
break
}
@@ -301,7 +301,7 @@ func map2Json(src *bufio.Reader, dst io.Writer) {
if minor == additionalTypeInfiniteCount {
unSpecifiedCount = true
} else {
length := decodeIntAdditonalType(src, minor)
length := decodeIntAdditionalType(src, minor)
len = int(length)
}
dst.Write([]byte{'{'})
@@ -311,7 +311,7 @@ func map2Json(src *bufio.Reader, dst io.Writer) {
if e != nil {
panic(e)
}
if pb[0] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) {
if pb[0] == majorTypeSimpleAndFloat|additionalTypeBreak {
readByte(src)
break
}
@@ -326,7 +326,7 @@ func map2Json(src *bufio.Reader, dst io.Writer) {
if e != nil {
panic(e)
}
if pb[0] == byte(majorTypeSimpleAndFloat|additionalTypeBreak) {
if pb[0] == majorTypeSimpleAndFloat|additionalTypeBreak {
readByte(src)
break
}
@@ -352,7 +352,7 @@ func decodeTagData(src *bufio.Reader) []byte {
// Tag value is larger than 256 (so uint16).
case additionalTypeIntUint16:
val := decodeIntAdditonalType(src, minor)
val := decodeIntAdditionalType(src, minor)
switch uint16(val) {
case additionalTypeEmbeddedJSON:
@@ -383,7 +383,7 @@ func decodeTagData(src *bufio.Reader) []byte {
case additionalTypeTagNetworkPrefix:
pb := readByte(src)
if pb != byte(majorTypeMap|0x1) {
if pb != majorTypeMap|0x1 {
panic(fmt.Errorf("IP Prefix is NOT of MAP of 1 elements as expected"))
}
octets := decodeString(src, true)

View File

@@ -8,7 +8,7 @@ func (e Encoder) AppendStrings(dst []byte, vals []string) []byte {
l := len(vals)
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -25,7 +25,7 @@ func (Encoder) AppendString(dst []byte, s string) []byte {
l := len(s)
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, majorTypeUtf8String, uint64(l))
}
@@ -64,7 +64,7 @@ func (Encoder) AppendBytes(dst, s []byte) []byte {
l := len(s)
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -77,7 +77,7 @@ func AppendEmbeddedJSON(dst, s []byte) []byte {
minor := additionalTypeEmbeddedJSON
// Append the TAG to indicate this is Embedded JSON.
dst = append(dst, byte(major|additionalTypeIntUint16))
dst = append(dst, major|additionalTypeIntUint16)
dst = append(dst, byte(minor>>8))
dst = append(dst, byte(minor&0xff))
@@ -87,7 +87,7 @@ func AppendEmbeddedJSON(dst, s []byte) []byte {
l := len(s)
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}

View File

@@ -7,7 +7,7 @@ import (
func appendIntegerTimestamp(dst []byte, t time.Time) []byte {
major := majorTypeTags
minor := additionalTypeTimestamp
dst = append(dst, byte(major|minor))
dst = append(dst, major|minor)
secs := t.Unix()
var val uint64
if secs < 0 {
@@ -17,18 +17,18 @@ func appendIntegerTimestamp(dst []byte, t time.Time) []byte {
major = majorTypeUnsignedInt
val = uint64(secs)
}
dst = appendCborTypePrefix(dst, major, uint64(val))
dst = appendCborTypePrefix(dst, major, val)
return dst
}
func (e Encoder) appendFloatTimestamp(dst []byte, t time.Time) []byte {
major := majorTypeTags
minor := additionalTypeTimestamp
dst = append(dst, byte(major|minor))
dst = append(dst, major|minor)
secs := t.Unix()
nanos := t.Nanosecond()
var val float64
val = float64(secs)*1.0 + float64(nanos)*1E-9
val = float64(secs)*1.0 + float64(nanos)*1e-9
return e.AppendFloat64(dst, val)
}
@@ -50,7 +50,7 @@ func (e Encoder) AppendTimes(dst []byte, vals []time.Time, unused string) []byte
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -82,7 +82,7 @@ func (e Encoder) AppendDurations(dst []byte, vals []time.Duration, unit time.Dur
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}

View File

@@ -8,17 +8,17 @@ import (
// AppendNil inserts a 'Nil' object into the dst byte array.
func (Encoder) AppendNil(dst []byte) []byte {
return append(dst, byte(majorTypeSimpleAndFloat|additionalTypeNull))
return append(dst, majorTypeSimpleAndFloat|additionalTypeNull)
}
// AppendBeginMarker inserts a map start into the dst byte array.
func (Encoder) AppendBeginMarker(dst []byte) []byte {
return append(dst, byte(majorTypeMap|additionalTypeInfiniteCount))
return append(dst, majorTypeMap|additionalTypeInfiniteCount)
}
// AppendEndMarker inserts a map end into the dst byte array.
func (Encoder) AppendEndMarker(dst []byte) []byte {
return append(dst, byte(majorTypeSimpleAndFloat|additionalTypeBreak))
return append(dst, majorTypeSimpleAndFloat|additionalTypeBreak)
}
// AppendObjectData takes an object in form of a byte array and appends to dst.
@@ -30,12 +30,12 @@ func (Encoder) AppendObjectData(dst []byte, o []byte) []byte {
// AppendArrayStart adds markers to indicate the start of an array.
func (Encoder) AppendArrayStart(dst []byte) []byte {
return append(dst, byte(majorTypeArray|additionalTypeInfiniteCount))
return append(dst, majorTypeArray|additionalTypeInfiniteCount)
}
// AppendArrayEnd adds markers to indicate the end of an array.
func (Encoder) AppendArrayEnd(dst []byte) []byte {
return append(dst, byte(majorTypeSimpleAndFloat|additionalTypeBreak))
return append(dst, majorTypeSimpleAndFloat|additionalTypeBreak)
}
// AppendArrayDelim adds markers to indicate end of a particular array element.
@@ -56,7 +56,7 @@ func (Encoder) AppendBool(dst []byte, val bool) []byte {
if val {
b = additionalTypeBoolTrue
}
return append(dst, byte(majorTypeSimpleAndFloat|b))
return append(dst, majorTypeSimpleAndFloat|b)
}
// AppendBools encodes and inserts an array of boolean values into the dst byte array.
@@ -68,7 +68,7 @@ func (e Encoder) AppendBools(dst []byte, vals []bool) []byte {
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -88,7 +88,7 @@ func (Encoder) AppendInt(dst []byte, val int) []byte {
}
if contentVal <= additionalMax {
lb := byte(contentVal)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(contentVal))
}
@@ -104,7 +104,7 @@ func (e Encoder) AppendInts(dst []byte, vals []int) []byte {
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -128,7 +128,7 @@ func (e Encoder) AppendInts8(dst []byte, vals []int8) []byte {
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -152,7 +152,7 @@ func (e Encoder) AppendInts16(dst []byte, vals []int16) []byte {
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -176,7 +176,7 @@ func (e Encoder) AppendInts32(dst []byte, vals []int32) []byte {
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -196,7 +196,7 @@ func (Encoder) AppendInt64(dst []byte, val int64) []byte {
}
if contentVal <= additionalMax {
lb := byte(contentVal)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(contentVal))
}
@@ -212,7 +212,7 @@ func (e Encoder) AppendInts64(dst []byte, vals []int64) []byte {
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -236,7 +236,7 @@ func (e Encoder) AppendUints(dst []byte, vals []uint) []byte {
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -260,7 +260,7 @@ func (e Encoder) AppendUints8(dst []byte, vals []uint8) []byte {
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -284,7 +284,7 @@ func (e Encoder) AppendUints16(dst []byte, vals []uint16) []byte {
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -308,7 +308,7 @@ func (e Encoder) AppendUints32(dst []byte, vals []uint32) []byte {
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -324,9 +324,9 @@ func (Encoder) AppendUint64(dst []byte, val uint64) []byte {
contentVal := val
if contentVal <= additionalMax {
lb := byte(contentVal)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(contentVal))
dst = appendCborTypePrefix(dst, major, contentVal)
}
return dst
}
@@ -340,7 +340,7 @@ func (e Encoder) AppendUints64(dst []byte, vals []uint64) []byte {
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -367,7 +367,7 @@ func (Encoder) AppendFloat32(dst []byte, val float32) []byte {
for i := uint(0); i < 4; i++ {
buf[i] = byte(n >> ((3 - i) * 8))
}
return append(append(dst, byte(major|subType)), buf[0], buf[1], buf[2], buf[3])
return append(append(dst, major|subType), buf[0], buf[1], buf[2], buf[3])
}
// AppendFloats32 encodes and inserts an array of single precision float value into the dst byte array.
@@ -379,7 +379,7 @@ func (e Encoder) AppendFloats32(dst []byte, vals []float32) []byte {
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -402,7 +402,7 @@ func (Encoder) AppendFloat64(dst []byte, val float64) []byte {
major := majorTypeSimpleAndFloat
subType := additionalTypeFloat64
n := math.Float64bits(val)
dst = append(dst, byte(major|subType))
dst = append(dst, major|subType)
for i := uint(1); i <= 8; i++ {
b := byte(n >> ((8 - i) * 8))
dst = append(dst, b)
@@ -419,7 +419,7 @@ func (e Encoder) AppendFloats64(dst []byte, vals []float64) []byte {
}
if l <= additionalMax {
lb := byte(l)
dst = append(dst, byte(major|lb))
dst = append(dst, major|lb)
} else {
dst = appendCborTypePrefix(dst, major, uint64(l))
}
@@ -440,7 +440,7 @@ func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte {
// 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, majorTypeTags|additionalTypeIntUint16)
dst = append(dst, byte(additionalTypeTagNetworkAddr>>8))
dst = append(dst, byte(additionalTypeTagNetworkAddr&0xff))
return e.AppendBytes(dst, ip)
@@ -448,21 +448,21 @@ func (e Encoder) AppendIPAddr(dst []byte, ip net.IP) []byte {
// 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, 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 = append(dst, majorTypeMap|0x1)
dst = e.AppendBytes(dst, pfx.IP)
maskLen, _ := pfx.Mask.Size()
return e.AppendUint8(dst, uint8(maskLen))
}
// AppendMACAddr encodes and inserts an Hardware (MAC) address.
// AppendMACAddr encodes and inserts a Hardware (MAC) address.
func (e Encoder) AppendMACAddr(dst []byte, ha net.HardwareAddr) []byte {
dst = append(dst, byte(majorTypeTags|additionalTypeIntUint16))
dst = append(dst, majorTypeTags|additionalTypeIntUint16)
dst = append(dst, byte(additionalTypeTagNetworkAddr>>8))
dst = append(dst, byte(additionalTypeTagNetworkAddr&0xff))
return e.AppendBytes(dst, ha)
@@ -470,7 +470,7 @@ func (e Encoder) AppendMACAddr(dst []byte, ha net.HardwareAddr) []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, majorTypeTags|additionalTypeIntUint16)
dst = append(dst, byte(additionalTypeTagHexString>>8))
dst = append(dst, byte(additionalTypeTagHexString&0xff))
return e.AppendBytes(dst, val)

View File

@@ -37,7 +37,7 @@ func (e Encoder) AppendStrings(dst []byte, vals []string) []byte {
//
// The operation loops though each byte in the string looking
// for characters that need json or utf8 encoding. If the string
// does not need encoding, then the string is appended in it's
// does not need encoding, then the string is appended in its
// entirety to the byte slice.
// If we encounter a byte that does need encoding, switch up
// the operation and perform a byte-by-byte read-encode-append.
@@ -56,7 +56,7 @@ func (Encoder) AppendString(dst []byte, s string) []byte {
return append(dst, '"')
}
}
// The string has no need for encoding an therefore is directly
// The string has no need for encoding and therefore is directly
// appended to the byte slice.
dst = append(dst, s...)
// End with a double quote
@@ -99,7 +99,7 @@ func appendStringComplex(dst []byte, s string, i int) []byte {
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 remplacement character code
// 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]...)

View File

@@ -7,9 +7,10 @@ import (
const (
// Import from zerolog/global.go
timeFormatUnix = ""
timeFormatUnixMs = "UNIXMS"
timeFormatUnix = ""
timeFormatUnixMs = "UNIXMS"
timeFormatUnixMicro = "UNIXMICRO"
timeFormatUnixNano = "UNIXNANO"
)
// AppendTime formats the input time with the given format
@@ -22,6 +23,8 @@ func (e Encoder) AppendTime(dst []byte, t time.Time, format string) []byte {
return e.AppendInt64(dst, t.UnixNano()/1000000)
case timeFormatUnixMicro:
return e.AppendInt64(dst, t.UnixNano()/1000)
case timeFormatUnixNano:
return e.AppendInt64(dst, t.UnixNano())
}
return append(t.AppendFormat(append(dst, '"'), format), '"')
}
@@ -33,7 +36,11 @@ func (Encoder) AppendTimes(dst []byte, vals []time.Time, format string) []byte {
case timeFormatUnix:
return appendUnixTimes(dst, vals)
case timeFormatUnixMs:
return appendUnixMsTimes(dst, vals)
return appendUnixNanoTimes(dst, vals, 1000000)
case timeFormatUnixMicro:
return appendUnixNanoTimes(dst, vals, 1000)
case timeFormatUnixNano:
return appendUnixNanoTimes(dst, vals, 1)
}
if len(vals) == 0 {
return append(dst, '[', ']')
@@ -64,15 +71,15 @@ func appendUnixTimes(dst []byte, vals []time.Time) []byte {
return dst
}
func appendUnixMsTimes(dst []byte, vals []time.Time) []byte {
func appendUnixNanoTimes(dst []byte, vals []time.Time, div int64) []byte {
if len(vals) == 0 {
return append(dst, '[', ']')
}
dst = append(dst, '[')
dst = strconv.AppendInt(dst, vals[0].UnixNano()/1000000, 10)
dst = strconv.AppendInt(dst, vals[0].UnixNano()/div, 10)
if len(vals) > 1 {
for _, t := range vals[1:] {
dst = strconv.AppendInt(append(dst, ','), t.UnixNano()/1000000, 10)
dst = strconv.AppendInt(append(dst, ','), t.UnixNano()/div, 10)
}
}
dst = append(dst, ']')

View File

@@ -278,7 +278,7 @@ func (Encoder) 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 (Encoder) AppendUint64(dst []byte, val uint64) []byte {
return strconv.AppendUint(dst, uint64(val), 10)
return strconv.AppendUint(dst, val, 10)
}
// AppendUints64 encodes the input uint64s to json and
@@ -300,7 +300,7 @@ func (Encoder) AppendUints64(dst []byte, vals []uint64) []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
// with an error, but a logging library wants the data to get through so we
// make a tradeoff and store those types as string.
switch {
case math.IsNaN(val):

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

@@ -99,6 +99,7 @@
package zerolog
import (
"errors"
"fmt"
"io"
"io/ioutil"
@@ -189,6 +190,21 @@ func ParseLevel(levelStr string) (Level, error) {
return Level(i), nil
}
// UnmarshalText implements encoding.TextUnmarshaler to allow for easy reading from toml/yaml/json formats
func (l *Level) UnmarshalText(text []byte) error {
if l == nil {
return errors.New("can't unmarshal a nil *Level")
}
var err error
*l, err = ParseLevel(string(text))
return err
}
// MarshalText implements encoding.TextMarshaler to allow for easy writing into toml/yaml/json formats
func (l Level) MarshalText() ([]byte, error) {
return []byte(LevelFieldMarshalFunc(l)), nil
}
// A Logger represents an active logging object that generates lines
// of JSON output to an io.Writer. Each logging operation makes a single
// call to the Writer's Write method. There is no guarantee on access
@@ -361,7 +377,7 @@ func (l *Logger) Panic() *Event {
// 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.
// flow of a goroutine when used with their respective levels.
//
// You must call Msg on the returned event in order to send the event.
func (l *Logger) WithLevel(level Level) *Event {
@@ -428,6 +444,9 @@ func (l Logger) Write(p []byte) (n int, err error) {
func (l *Logger) newEvent(level Level, done func(string)) *Event {
enabled := l.should(level)
if !enabled {
if done != nil {
done("")
}
return nil
}
e := newEvent(l.w, level)