diff --git a/api/decode.go b/api/decode.go index 5dbddc3..2452572 100644 --- a/api/decode.go +++ b/api/decode.go @@ -9,7 +9,7 @@ import ( // Decode decodes the body of a request into the specified object. // If the object implements the OK interface, that method is called // to validate the object. -func Decode(r *http.Request, v interface{}) error { +func Decode(r *http.Request, v any) error { err := json.NewDecoder(r.Body).Decode(v) if err != nil { return &ErrJSON{err} diff --git a/api/respond.go b/api/respond.go index 00a4e8f..040b125 100644 --- a/api/respond.go +++ b/api/respond.go @@ -3,14 +3,13 @@ package api import ( "bytes" "encoding/json" + "fmt" "io" "net/http" gmerrors "github.com/graymeta/gmkit/errors" "github.com/graymeta/gmkit/http/middleware" "github.com/graymeta/gmkit/logger" - - "github.com/pkg/errors" ) // Responder writes API responses. @@ -49,7 +48,7 @@ func Header(key, value string) Option { const HeaderAPIVersion = `X-Api-Version` // With responds with the specified data. -func (r *Responder) With(w http.ResponseWriter, req *http.Request, status int, data interface{}, opts ...Option) { +func (r *Responder) With(w http.ResponseWriter, req *http.Request, status int, data any, opts ...Option) { var buf bytes.Buffer // cannot write to buf if data is nil, in case of StatusNoContent, this write will fail // so we need an escape hatch here. @@ -58,7 +57,7 @@ func (r *Responder) With(w http.ResponseWriter, req *http.Request, status int, d enc.SetIndent("", "\t") err := enc.Encode(data) if err != nil { - err = errors.Wrap(err, "failed to encode response object") + err = fmt.Errorf("failed to encode response object: %w", err) r.Err(w, req, err) return } @@ -74,7 +73,7 @@ func (r *Responder) With(w http.ResponseWriter, req *http.Request, status int, d } w.WriteHeader(status) if _, err := io.Copy(w, &buf); err != nil { - err = errors.Wrap(err, "failed to copy response bytes") + err = fmt.Errorf("failed to copy response bytes: %w", err) r.log.Err("api_response", err) } } diff --git a/backoff/runners.go b/backoff/runners.go index 42b0955..2da0354 100644 --- a/backoff/runners.go +++ b/backoff/runners.go @@ -35,10 +35,11 @@ type Runner struct { // New returns a runner with the defined options. If no options are given, // then the new runner is given the defaults for initial and max backoff as well // as max calls. The defaults being: -// InitBackoff: 1 second -// MaxBackoff: 1 minute -// MaxCalls: 10 -// Jitter: false +// +// InitBackoff: 1 second +// MaxBackoff: 1 minute +// MaxCalls: 10 +// Jitter: false func New(opts ...RunnerOptFn) Runner { r := Runner{ initDur: defaultInitialBackoff, diff --git a/crypter/aes_crypter.go b/crypter/aes_crypter.go index c598ad7..a7a4b8d 100644 --- a/crypter/aes_crypter.go +++ b/crypter/aes_crypter.go @@ -2,14 +2,15 @@ package crypter import ( "encoding/base64" + "errors" + "fmt" "github.com/gtank/cryptopasta" - "github.com/pkg/errors" ) // ErrInvalidAESKeyLength is the error returned when the encryption key isn't // the correct length -var ErrInvalidAESKeyLength = errors.New("Invalid key length") +var ErrInvalidAESKeyLength = errors.New("invalid key length") type aesCrypter struct { key *[32]byte @@ -42,12 +43,12 @@ func (c *aesCrypter) Encrypt(data string) (string, error) { func (c *aesCrypter) Decrypt(ciphertext string) (string, error) { unencoded, err := base64.StdEncoding.DecodeString(ciphertext) if err != nil { - return "", errors.Wrap(err, "decoding base64 ciphertext") + return "", fmt.Errorf("decoding base64 ciphertext: %w", err) } plaintext, err := cryptopasta.Decrypt([]byte(unencoded), c.key) if err != nil { - return "", errors.Wrap(err, "decrypting ciphertext") + return "", fmt.Errorf("decrypting ciphertext: %w", err) } return string(plaintext), nil diff --git a/errors/client.go b/errors/client.go index f058a03..1b887af 100644 --- a/errors/client.go +++ b/errors/client.go @@ -3,7 +3,7 @@ package errors import ( "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "strings" @@ -53,7 +53,7 @@ func NewClientErr(op string, err error, resp *http.Response, opts ...ClientOptFn newClientErr.method = req.Method if req.Header != nil && strings.Contains(req.Header.Get("Content-Type"), "application/json") { - if body, err := ioutil.ReadAll(req.Body); err == nil { + if body, err := io.ReadAll(req.Body); err == nil { newClientErr.respBody = string(body) } } @@ -61,7 +61,7 @@ func NewClientErr(op string, err error, resp *http.Response, opts ...ClientOptFn newClientErr.StatusCode = resp.StatusCode newClientErr.reqID = resp.Header.Get(middleware.RequestHeader) - if body, err := ioutil.ReadAll(resp.Body); err == nil { + if body, err := io.ReadAll(resp.Body); err == nil { newClientErr.respBody = string(body) } diff --git a/errors/service.go b/errors/service.go index 0f7fb9a..ad5aa13 100644 --- a/errors/service.go +++ b/errors/service.go @@ -1,6 +1,8 @@ package errors -import "fmt" +import ( + "fmt" +) var ( // NewExistsSVCErrGen is a generator function for building ExistsSVCErrs with the specified diff --git a/go.mod b/go.mod index bc14a89..b5f9938 100644 --- a/go.mod +++ b/go.mod @@ -3,40 +3,57 @@ module github.com/graymeta/gmkit replace gopkg.in/russross/blackfriday.v2 => github.com/russross/blackfriday/v2 v2.0.1 require ( - github.com/Masterminds/goutils v1.1.0 // indirect - github.com/Masterminds/semver v1.4.2 // indirect - github.com/Masterminds/sprig v2.20.0+incompatible // indirect github.com/aws/aws-sdk-go v1.23.4 github.com/carlosdp/twiliogo v0.0.0-20161027183705-b26045ebb9d1 github.com/ernesto-jimenez/httplogger v0.0.0-20150224132909-86cc44f6150a github.com/garyburd/redigo v1.6.0 github.com/go-kit/kit v0.9.0 - github.com/go-logfmt/logfmt v0.4.0 // indirect github.com/go-stack/stack v1.8.0 - github.com/google/uuid v1.1.1 // indirect github.com/gorilla/mux v1.7.3 github.com/graymeta/env v0.0.2 github.com/gtank/cryptopasta v0.0.0-20170601214702-1f550f6f2f69 github.com/hashicorp/go-multierror v1.0.0 - github.com/huandu/xstrings v1.2.0 // indirect github.com/hyperboloide/lk v0.0.0-20190531110207-c022f7a15f5a - github.com/imdario/mergo v0.3.7 // indirect - github.com/jaytaylor/html2text v0.0.0-20190408195923-01ec452cbe43 // indirect github.com/jmoiron/sqlx v1.2.0 github.com/lib/pq v1.2.0 github.com/matcornic/hermes v1.2.0 - github.com/mattn/go-runewidth v0.0.4 // indirect - github.com/olekukonko/tablewriter v0.0.1 // indirect github.com/pkg/errors v0.8.1 github.com/quipo/statsd v0.0.0-20180118161217-3d6a5565f314 github.com/reiver/go-pqerror v0.0.0-20160209202356-63f13fe5516a - github.com/sendgrid/rest v2.4.1+incompatible // indirect github.com/sendgrid/sendgrid-go v3.5.0+incompatible + github.com/stretchr/testify v1.5.1 + golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 + gopkg.in/olivere/elastic.v5 v5.0.81 +) + +require ( + github.com/Masterminds/goutils v1.1.0 // indirect + github.com/Masterminds/semver v1.4.2 // indirect + github.com/Masterminds/sprig v2.20.0+incompatible // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dchest/uniuri v1.2.0 // indirect + github.com/go-logfmt/logfmt v0.4.0 // indirect + github.com/google/uuid v1.1.1 // indirect + github.com/hashicorp/errwrap v1.0.0 // indirect + github.com/huandu/xstrings v1.2.0 // indirect + github.com/imdario/mergo v0.3.7 // indirect + github.com/jaytaylor/html2text v0.0.0-20190408195923-01ec452cbe43 // indirect + github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af // indirect + github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515 // indirect + github.com/mailru/easyjson v0.0.0-20180730094502-03f2033d19d5 // indirect + github.com/mattn/go-runewidth v0.0.4 // indirect + github.com/olekukonko/tablewriter v0.0.1 // indirect + github.com/onsi/ginkgo v1.16.5 // indirect + github.com/onsi/gomega v1.27.6 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/sendgrid/rest v2.4.1+incompatible // indirect github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect - github.com/stretchr/testify v1.4.0 - golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 - gopkg.in/olivere/elastic.v5 v5.0.81 + github.com/stretchr/objx v0.1.0 // indirect + golang.org/x/net v0.8.0 // indirect + google.golang.org/appengine v1.6.7 // indirect + gopkg.in/russross/blackfriday.v2 v2.0.0-00010101000000-000000000000 // indirect + gopkg.in/yaml.v2 v2.3.0 // indirect ) -go 1.13 +go 1.20 diff --git a/go.sum b/go.sum index 1336b3e..452d183 100644 --- a/go.sum +++ b/go.sum @@ -8,20 +8,41 @@ github.com/aws/aws-sdk-go v1.23.4 h1:F6f/iQRhuSfrpUdy80q29898H0NYN27pX+95tkJ+BIY github.com/aws/aws-sdk-go v1.23.4/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/carlosdp/twiliogo v0.0.0-20161027183705-b26045ebb9d1 h1:hXakhQtPnXH839q1pBl/GqfTSchqE+R5Fqn98Iu7UQM= github.com/carlosdp/twiliogo v0.0.0-20161027183705-b26045ebb9d1/go.mod h1:pAxCBpjl/0JxYZlWGP/Dyi8f/LQSCQD2WAsG/iNzqQ8= -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dchest/uniuri v1.2.0 h1:koIcOUdrTIivZgSLhHQvKgqdWZq5d7KdMEWF1Ud6+5g= +github.com/dchest/uniuri v1.2.0/go.mod h1:fSzm4SLHzNZvWLvWJew423PhAzkpNQYq+uNLq4kxhkY= github.com/ernesto-jimenez/httplogger v0.0.0-20150224132909-86cc44f6150a h1:XTdOK/wISWQFdWj1D9c3DagauL22s0eMPL70K0pMuw4= github.com/ernesto-jimenez/httplogger v0.0.0-20150224132909-86cc44f6150a/go.mod h1:zroVJTjbZUlS0lcewJlcPsS6JQIoFWePhxjOF0/n0f4= +github.com/fortytw2/leaktest v1.2.0 h1:cj6GCiwJDH7l3tMHLjZDo0QqPtrXJiWSI9JgpeQKw+Q= github.com/fortytw2/leaktest v1.2.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/garyburd/redigo v1.6.0 h1:0VruCpn7yAIIu7pWVClQC8wxCJEcG3nyzpMSHKi1PQc= github.com/garyburd/redigo v1.6.0/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY= github.com/go-kit/kit v0.9.0 h1:wDJmvq38kDhkVxi50ni9ykkdUr1PKgqKOoi01fa0Mdk= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.4.0 h1:MP4Eh7ZCb31lleYCFuwm0oe4/YGak+5l1vA2NOE80nA= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-sql-driver/mysql v1.4.0 h1:7LxgVwFb2hIQtMm87NdgAVfXjnt4OePseqT1tKx+opk= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw= @@ -34,6 +55,7 @@ github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/U github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/huandu/xstrings v1.2.0 h1:yPeWdRnmynF7p+lLYz0H2tthW9lqhMJrQV/U7yy4wX0= github.com/huandu/xstrings v1.2.0/go.mod h1:DvyZB1rfVYsBIigL8HwpZgxHwXozlTgGqn63UyNX5k4= github.com/hyperboloide/lk v0.0.0-20190531110207-c022f7a15f5a h1:p6uuFlnCDvdXNXi/xcJVffaALk+Yj6VkgIha4ymZhwM= @@ -46,6 +68,7 @@ github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5i github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmoiron/sqlx v1.2.0 h1:41Ip0zITnmWNR/vHV+S4m+VoUivnWY5E4OJfLZjCJMA= github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515 h1:T+h1c/A9Gawja4Y9mFVWj2vyii2bbUNDw3kt9VxK2EY= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0= @@ -56,9 +79,21 @@ github.com/matcornic/hermes v1.2.0 h1:AuqZpYcTOtTB7cahdevLfnhIpfzmpqw5Czv8vpdnFD github.com/matcornic/hermes v1.2.0/go.mod h1:lujJomb016Xjv8wBnWlNvUdtmvowjjfkqri5J/+1hYc= github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y= github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-sqlite3 v1.9.0 h1:pDRiWfl+++eC2FEFRy6jXmQlvp4Yh3z1MJKg4UeYM/4= github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/olekukonko/tablewriter v0.0.1 h1:b3iUnf1v+ppJiOfNX4yxxqfWKMQPZR5yoh8urCTFX88= github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE= +github.com/onsi/gomega v1.27.6/go.mod h1:PIQNjfQwkP3aQAH7lf7j87O/5FiNr+ZR8+ipb+qQlhg= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -81,18 +116,64 @@ github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cma github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 h1:HuIa8hRrWRSrqYzx1qI49NNxhdi2PrY7gxVSq1JjLDc= -golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/olivere/elastic.v5 v5.0.81 h1:21Vu9RMT2qXVLqXINtiOhwVPYz/87+Omsxh/Re+gK4k= gopkg.in/olivere/elastic.v5 v5.0.81/go.mod h1:uhHoB4o3bvX5sorxBU29rPcmBQdV2Qfg0FBrx5D6pV0= -gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/http/basic_auth_transport.go b/http/basic_auth_transport.go index 177d10a..767b94f 100644 --- a/http/basic_auth_transport.go +++ b/http/basic_auth_transport.go @@ -1,6 +1,8 @@ package http -import "net/http" +import ( + "net/http" +) // BasicAuthTransport is an http.RoundTripper that adds basic auth credentials to each request. type BasicAuthTransport struct { diff --git a/http/header_range.go b/http/header_range.go index 25bc18e..f38ce11 100644 --- a/http/header_range.go +++ b/http/header_range.go @@ -1,11 +1,10 @@ package http import ( + "errors" "fmt" "strconv" "strings" - - "github.com/pkg/errors" ) var ( @@ -30,12 +29,12 @@ func ParseHeaderRange(h string) (int64, int64, error) { start, err := strconv.ParseInt(pieces[0], 10, 64) if err != nil { - return 0, 0, errors.Wrap(err, "parsing start value") + return 0, 0, fmt.Errorf("parsing start value: %w", err) } end, err := strconv.ParseInt(pieces[1], 10, 64) if err != nil { - return 0, 0, errors.Wrap(err, "parsing end value") + return 0, 0, fmt.Errorf("parsing end value: %w", err) } return start, end, nil diff --git a/http/httpc/auth.go b/http/httpc/auth.go index ad82633..7125483 100644 --- a/http/httpc/auth.go +++ b/http/httpc/auth.go @@ -1,6 +1,8 @@ package httpc -import "net/http" +import ( + "net/http" +) // AuthFn adds authorization to an http request. type AuthFn func(*http.Request) *http.Request diff --git a/http/httpc/client_test.go b/http/httpc/client_test.go index 2d9b7a4..6be8ebc 100644 --- a/http/httpc/client_test.go +++ b/http/httpc/client_test.go @@ -5,7 +5,7 @@ import ( "context" "encoding/json" stderrors "errors" - "io/ioutil" + "io" "net/http" "net/http/httptest" "strings" @@ -1104,7 +1104,7 @@ type foo struct { Method string } -func stubRespNBody(t *testing.T, status int, v interface{}) *http.Response { +func stubRespNBody(t *testing.T, status int, v any) *http.Response { t.Helper() var buf bytes.Buffer @@ -1113,7 +1113,7 @@ func stubRespNBody(t *testing.T, status int, v interface{}) *http.Response { } return &http.Response{ StatusCode: status, - Body: ioutil.NopCloser(&buf), + Body: io.NopCloser(&buf), } } @@ -1125,7 +1125,7 @@ func stubRespHeaders(status int, headers map[string]string) *http.Response { return &http.Response{ StatusCode: status, - Body: ioutil.NopCloser(new(bytes.Buffer)), + Body: io.NopCloser(new(bytes.Buffer)), Header: respHeader, } } @@ -1133,7 +1133,7 @@ func stubRespHeaders(status int, headers map[string]string) *http.Response { func stubResp(status int) *http.Response { return &http.Response{ StatusCode: status, - Body: ioutil.NopCloser(new(bytes.Buffer)), + Body: io.NopCloser(new(bytes.Buffer)), } } diff --git a/http/httpc/encoding.go b/http/httpc/encoding.go index 5ccb6c2..5d4cf60 100644 --- a/http/httpc/encoding.go +++ b/http/httpc/encoding.go @@ -9,7 +9,7 @@ import ( type ( // EncodeFn is an encoder func. - EncodeFn func(interface{}) (io.Reader, error) + EncodeFn func(any) (io.Reader, error) // DecodeFn is a decoder func. DecodeFn func(r io.Reader) error @@ -17,14 +17,14 @@ type ( // JSONEncode sets the client's encodeFn to a json encoder. func JSONEncode() EncodeFn { - return func(v interface{}) (io.Reader, error) { + return func(v any) (io.Reader, error) { var buf bytes.Buffer return &buf, json.NewEncoder(&buf).Encode(v) } } // JSONDecode sets the client's decodeFn to a json decoder. -func JSONDecode(v interface{}) DecodeFn { +func JSONDecode(v any) DecodeFn { return func(r io.Reader) error { return json.NewDecoder(r).Decode(v) } @@ -32,14 +32,14 @@ func JSONDecode(v interface{}) DecodeFn { // GobEncode sets the client's encodeFn to a gob encoder. func GobEncode() EncodeFn { - return func(v interface{}) (io.Reader, error) { + return func(v any) (io.Reader, error) { var buf bytes.Buffer return &buf, gob.NewEncoder(&buf).Encode(v) } } // GobDecode sets the client's decodeFn to a gob decoder. -func GobDecode(v interface{}) DecodeFn { +func GobDecode(v any) DecodeFn { return func(r io.Reader) error { return gob.NewDecoder(r).Decode(v) } diff --git a/http/httpc/httpcfakes/fake_doer.go b/http/httpc/httpcfakes/fake_doer.go index 32b0c84..d1d286c 100644 --- a/http/httpc/httpcfakes/fake_doer.go +++ b/http/httpc/httpcfakes/fake_doer.go @@ -20,7 +20,7 @@ type FakeDoer struct { result1 *http.Response result2 error } - invocations map[string][][]interface{} + invocations map[string][][]any invocationsMutex sync.RWMutex } @@ -30,7 +30,7 @@ func (fake *FakeDoer) Do(r *http.Request) (*http.Response, error) { fake.doArgsForCall = append(fake.doArgsForCall, struct { r *http.Request }{r}) - fake.recordInvocation("Do", []interface{}{r}) + fake.recordInvocation("Do", []any{r}) fake.doMutex.Unlock() if fake.DoStub != nil { return fake.DoStub(r) @@ -75,26 +75,26 @@ func (fake *FakeDoer) DoReturnsOnCall(i int, result1 *http.Response, result2 err }{result1, result2} } -func (fake *FakeDoer) Invocations() map[string][][]interface{} { +func (fake *FakeDoer) Invocations() map[string][][]any { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.doMutex.RLock() defer fake.doMutex.RUnlock() - copiedInvocations := map[string][][]interface{}{} + copiedInvocations := map[string][][]any{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } -func (fake *FakeDoer) recordInvocation(key string, args []interface{}) { +func (fake *FakeDoer) recordInvocation(key string, args []any) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { - fake.invocations = map[string][][]interface{}{} + fake.invocations = map[string][][]any{} } if fake.invocations[key] == nil { - fake.invocations[key] = [][]interface{}{} + fake.invocations[key] = [][]any{} } fake.invocations[key] = append(fake.invocations[key], args) } diff --git a/http/httpc/httpcfakes/fake_read_seeker.go b/http/httpc/httpcfakes/fake_read_seeker.go index 7ed231b..2e2b59e 100644 --- a/http/httpc/httpcfakes/fake_read_seeker.go +++ b/http/httpc/httpcfakes/fake_read_seeker.go @@ -34,7 +34,7 @@ type FakeReadSeeker struct { result1 int64 result2 error } - invocations map[string][][]interface{} + invocations map[string][][]any invocationsMutex sync.RWMutex } @@ -49,7 +49,7 @@ func (fake *FakeReadSeeker) Read(arg1 []byte) (int, error) { fake.readArgsForCall = append(fake.readArgsForCall, struct { arg1 []byte }{arg1Copy}) - fake.recordInvocation("Read", []interface{}{arg1Copy}) + fake.recordInvocation("Read", []any{arg1Copy}) fake.readMutex.Unlock() if fake.ReadStub != nil { return fake.ReadStub(arg1) @@ -113,7 +113,7 @@ func (fake *FakeReadSeeker) Seek(arg1 int64, arg2 int) (int64, error) { arg1 int64 arg2 int }{arg1, arg2}) - fake.recordInvocation("Seek", []interface{}{arg1, arg2}) + fake.recordInvocation("Seek", []any{arg1, arg2}) fake.seekMutex.Unlock() if fake.SeekStub != nil { return fake.SeekStub(arg1, arg2) @@ -170,28 +170,28 @@ func (fake *FakeReadSeeker) SeekReturnsOnCall(i int, result1 int64, result2 erro }{result1, result2} } -func (fake *FakeReadSeeker) Invocations() map[string][][]interface{} { +func (fake *FakeReadSeeker) Invocations() map[string][][]any { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.readMutex.RLock() defer fake.readMutex.RUnlock() fake.seekMutex.RLock() defer fake.seekMutex.RUnlock() - copiedInvocations := map[string][][]interface{}{} + copiedInvocations := map[string][][]any{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } -func (fake *FakeReadSeeker) recordInvocation(key string, args []interface{}) { +func (fake *FakeReadSeeker) recordInvocation(key string, args []any) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { - fake.invocations = map[string][][]interface{}{} + fake.invocations = map[string][][]any{} } if fake.invocations[key] == nil { - fake.invocations[key] = [][]interface{}{} + fake.invocations[key] = [][]any{} } fake.invocations[key] = append(fake.invocations[key], args) } diff --git a/http/httpc/options.go b/http/httpc/options.go index 5e714c5..dc15f68 100644 --- a/http/httpc/options.go +++ b/http/httpc/options.go @@ -1,6 +1,8 @@ package httpc -import "github.com/graymeta/gmkit/backoff" +import ( + "github.com/graymeta/gmkit/backoff" +) // ClientOptFn sets keys on a client type. type ClientOptFn func(Client) Client diff --git a/http/httpc/request.go b/http/httpc/request.go index 8a945ec..297fc03 100644 --- a/http/httpc/request.go +++ b/http/httpc/request.go @@ -5,7 +5,6 @@ import ( "context" "errors" "io" - "io/ioutil" "net/http" "github.com/graymeta/gmkit/backoff" @@ -37,7 +36,7 @@ type seekParams struct { type Request struct { method, addr string doer Doer - body interface{} + body any headers []kvPair params []kvPair logMeta []kvPair @@ -72,7 +71,7 @@ func (r *Request) Backoff(b backoff.Backoffer) *Request { } // Body sets the body of the Request. -func (r *Request) Body(v interface{}) *Request { +func (r *Request) Body(v any) *Request { r.body = v return r } @@ -112,7 +111,7 @@ func (r *Request) SeekParams(offset int64, whence int) *Request { } // DecodeJSON is is a short hand for decoding to JSON. -func (r *Request) DecodeJSON(v interface{}) *Request { +func (r *Request) DecodeJSON(v any) *Request { return r.Decode(JSONDecode(v)) } @@ -249,7 +248,7 @@ func (r *Request) DoAndGetReader(ctx context.Context) (*http.Response, error) { var buf bytes.Buffer tee := io.TeeReader(resp.Body, &buf) err = r.onErrorFn(tee) - resp.Body = ioutil.NopCloser(&buf) + resp.Body = io.NopCloser(&buf) } return gmerrors.NewClientErr("status code", err, resp, r.statusErrOpts(status)...) } @@ -320,7 +319,7 @@ func (r *Request) do(ctx context.Context) error { var buf bytes.Buffer tee := io.TeeReader(resp.Body, &buf) err = r.onErrorFn(tee) - resp.Body = ioutil.NopCloser(&buf) + resp.Body = io.NopCloser(&buf) } return gmerrors.NewClientErr("status code", err, resp, r.statusErrOpts(status)...) } @@ -416,7 +415,7 @@ func toKVPairs(pairs []string) []kvPair { // drain reads everything from the ReadCloser and closes it func drain(r io.ReadCloser) error { - if _, err := io.Copy(ioutil.Discard, r); err != nil { + if _, err := io.Copy(io.Discard, r); err != nil { return err } return r.Close() diff --git a/http/httpc/status.go b/http/httpc/status.go index 77c38ff..72de0a1 100644 --- a/http/httpc/status.go +++ b/http/httpc/status.go @@ -1,6 +1,8 @@ package httpc -import "net/http" +import ( + "net/http" +) // StatusFn is func for comparing expected status code against // an expected status code. diff --git a/http/middleware/frames.go b/http/middleware/frames.go index c8c3300..48ded71 100644 --- a/http/middleware/frames.go +++ b/http/middleware/frames.go @@ -1,6 +1,8 @@ package middleware -import "net/http" +import ( + "net/http" +) // constants for the X-Frame-Options header const ( diff --git a/http/middleware/gzip.go b/http/middleware/gzip.go index 5298230..9c7e8e6 100644 --- a/http/middleware/gzip.go +++ b/http/middleware/gzip.go @@ -17,11 +17,6 @@ func (gzw gzipWriter) Write(b []byte) (int, error) { } func (gzw gzipWriter) WriterHeader(statusCode int) { - // gzw.w.Close() (gzip writer) will write a footer even if no data has been written. - // StatusNotModified and StatusNoContent expect an empty body so swap for generic ResponseWriter instead - if statusCode == http.StatusNoContent || statusCode == http.StatusNotModified { - gzw.w = gzw.ResponseWriter - } gzw.ResponseWriter.WriteHeader(statusCode) } diff --git a/http/middleware/gzip_test.go b/http/middleware/gzip_test.go index cb83984..8c6fe98 100644 --- a/http/middleware/gzip_test.go +++ b/http/middleware/gzip_test.go @@ -3,7 +3,7 @@ package middleware import ( "bytes" "compress/gzip" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -21,7 +21,7 @@ func TestNoGzip(t *testing.T) { require.NoError(t, err) res, err := http.DefaultClient.Do(req) require.NoError(t, err) - b, err := ioutil.ReadAll(res.Body) + b, err := io.ReadAll(res.Body) require.NoError(t, err) require.Equal(t, body, b) } @@ -39,11 +39,11 @@ func TestGzip(t *testing.T) { require.NoError(t, err) h := res.Header.Get("Content-Encoding") require.Contains(t, h, "gzip") - b, err := ioutil.ReadAll(res.Body) + b, err := io.ReadAll(res.Body) require.NoError(t, err) gr, err := gzip.NewReader(bytes.NewReader(b)) require.NoError(t, err) - uncompressed, err := ioutil.ReadAll(gr) + uncompressed, err := io.ReadAll(gr) require.NoError(t, err) require.Equal(t, body, uncompressed) require.Less(t, len(b), len(body)) @@ -61,7 +61,7 @@ func TestNoContent(t *testing.T) { require.NoError(t, err) h := res.Header.Get("Content-Encoding") require.Contains(t, h, "gzip") - b, err := ioutil.ReadAll(res.Body) + b, err := io.ReadAll(res.Body) require.NoError(t, err) require.Len(t, b, 0) } diff --git a/http/middleware/nocache.go b/http/middleware/nocache.go index 9148143..9d49976 100644 --- a/http/middleware/nocache.go +++ b/http/middleware/nocache.go @@ -32,10 +32,11 @@ var etagHeaders = []string{ // a router (or subrouter) from being cached by an upstream proxy and/or client. // // As per http://wiki.nginx.org/HttpProxyModule - NoCache sets: -// Expires: Thu, 01 Jan 1970 00:00:00 UTC -// Cache-Control: no-cache, private, max-age=0 -// X-Accel-Expires: 0 -// Pragma: no-cache (for HTTP/1.0 proxies/clients) +// +// Expires: Thu, 01 Jan 1970 00:00:00 UTC +// Cache-Control: no-cache, private, max-age=0 +// X-Accel-Expires: 0 +// Pragma: no-cache (for HTTP/1.0 proxies/clients) func NoCache(h http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { diff --git a/icinga/active-checks.go b/icinga/active-checks.go index cbd1b91..620023d 100644 --- a/icinga/active-checks.go +++ b/icinga/active-checks.go @@ -2,9 +2,8 @@ package icinga import ( "encoding/json" + "fmt" "net/http" - - "github.com/pkg/errors" ) // ActiveCheck Basic body to disable active check on a host @@ -19,11 +18,11 @@ type ActiveCheck struct { func (c *Client) SetAllActiveChecks(hostname string, check bool) error { err := c.SetActiveChecks(hostname, "/objects/hosts", check) if err != nil { - return errors.Wrap(err, "SetActiveCheck on host") + return fmt.Errorf("SetActiveCheck on host: %w", err) } err = c.SetActiveChecks(hostname, "/objects/services", check) if err != nil { - return errors.Wrap(err, "SetActiveCheck on services") + return fmt.Errorf("SetActiveCheck on services: %w", err) } return nil } diff --git a/icinga/api.go b/icinga/api.go index 8e0538e..2b71dca 100644 --- a/icinga/api.go +++ b/icinga/api.go @@ -3,9 +3,9 @@ package icinga import ( "bytes" "encoding/json" + "errors" + "fmt" "net/http" - - "github.com/pkg/errors" ) // APIResults response from icinga API @@ -20,7 +20,7 @@ type APIResults struct { Name string `json:"name"` Type string `json:"type"` Attrs struct { - AttrsInfo map[string]interface{} `json:"-,"` + AttrsInfo map[string]any `json:"-,"` } `json:"attrs"` Joins struct{} `json:"joins"` Meta struct{} `json:"meta"` @@ -61,7 +61,7 @@ func (c *Client) APIRequest(method, APICall string, jsonString []byte) (APIResul // On http failure return results if !(response.StatusCode >= 200 && response.StatusCode <= 299) { - return results, errors.Errorf("HTTP Status code: %d results: %v", response.StatusCode, results.Results) + return results, fmt.Errorf("http status code: %d results: %v", response.StatusCode, results.Results) } // If the results is empty and GET means object does not exists. If other method means no changes took affect @@ -69,7 +69,7 @@ func (c *Client) APIRequest(method, APICall string, jsonString []byte) (APIResul if method == http.MethodGet { return results, nil } - return results, errors.New("Icinga API results is empty") + return results, errors.New("icinga API results is empty") } results.Exists = true @@ -77,7 +77,7 @@ func (c *Client) APIRequest(method, APICall string, jsonString []byte) (APIResul if method != http.MethodGet { for _, result := range results.Results { if result.Code != 200 { - return results, errors.New("Icinga API error on one of the results") + return results, errors.New("icinga API error on one of the results") } } } diff --git a/icinga/client.go b/icinga/client.go index 364d910..753d386 100644 --- a/icinga/client.go +++ b/icinga/client.go @@ -3,11 +3,11 @@ package icinga import ( "crypto/tls" "crypto/x509" - "io/ioutil" + "errors" + "fmt" "net/http" + "os" "time" - - "github.com/pkg/errors" ) // Client holds the icinga2 http client @@ -34,7 +34,7 @@ func (cfg *Config) Client() (*Client, error) { tlsConfig, err := cfg.setupTLSConfig() if err != nil { - return nil, errors.Wrap(err, "setupTLSConfig error") + return nil, fmt.Errorf("setupTLSConfig error: %w", err) } return &Client{ @@ -57,13 +57,13 @@ func (cfg *Config) setupTLSConfig() (*tls.Config, error) { // Load client cert cert, err := tls.LoadX509KeyPair(cfg.TLSClientCert, cfg.TLSClientKey) if err != nil { - return nil, errors.Wrap(err, "load tls cert and key") + return nil, fmt.Errorf("load tls cert and key: %w", err) } // Load CA cert - caCert, err := ioutil.ReadFile(cfg.TLSCACert) + caCert, err := os.ReadFile(cfg.TLSCACert) if err != nil { - return nil, errors.Wrap(err, "Read ca cert") + return nil, fmt.Errorf("read ca cert: %w", err) } caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert) diff --git a/icinga/notifications.go b/icinga/notifications.go index 37ed969..2a16a3f 100644 --- a/icinga/notifications.go +++ b/icinga/notifications.go @@ -2,9 +2,8 @@ package icinga import ( "encoding/json" + "fmt" "net/http" - - "github.com/pkg/errors" ) // Notifications Basic body to disable notifications for a host or service @@ -19,11 +18,11 @@ type Notifications struct { func (c *Client) SetAllNotifications(hostname string, check bool) error { err := c.SetNotifications(hostname, "/objects/hosts", check) if err != nil { - return errors.Wrap(err, "SetNotifications on host") + return fmt.Errorf("SetNotifications on host: %w", err) } err = c.SetNotifications(hostname, "/objects/services", check) if err != nil { - return errors.Wrap(err, "SetNotifications on services") + return fmt.Errorf("SetNotifications on services: %w", err) } return nil } diff --git a/icinga/schedule-downtime.go b/icinga/schedule-downtime.go index ac0e3f2..cc84c7f 100644 --- a/icinga/schedule-downtime.go +++ b/icinga/schedule-downtime.go @@ -2,10 +2,9 @@ package icinga import ( "encoding/json" + "fmt" "net/http" "time" - - "github.com/pkg/errors" ) // ScheduleDowntime Basic body to schedule downtime for a host @@ -22,11 +21,11 @@ type ScheduleDowntime struct { func (c *Client) SetAllDowntime(hostname, author, comment string, start, end time.Time) error { err := c.SetDowntime(hostname, "Host", author, comment, start, end) if err != nil { - return errors.Wrap(err, "SetAllDowntime on host") + return fmt.Errorf("SetAllDowntime on host: %w", err) } err = c.SetDowntime(hostname, "Service", author, comment, start, end) if err != nil { - return errors.Wrap(err, "SetAllDowntime on services") + return fmt.Errorf("SetAllDowntime on services: %w", err) } return nil } @@ -65,11 +64,11 @@ type ResetDowntime struct { func (c *Client) ResetAllDowntime(hostname string) error { err := c.ResetDowntime(hostname, "Host") if err != nil { - return errors.Wrap(err, "ResetAllDowntime on host") + return fmt.Errorf("ResetAllDowntime on host: %w", err) } err = c.ResetDowntime(hostname, "Service") if err != nil { - return errors.Wrap(err, "ResetAllDowntime on services") + return fmt.Errorf("ResetAllDowntime on services: %w", err) } return nil } diff --git a/licensing/license.go b/licensing/license.go index 6ff72cf..9fb925b 100644 --- a/licensing/license.go +++ b/licensing/license.go @@ -2,10 +2,11 @@ package licensing import ( "encoding/json" + "errors" + "fmt" "time" "github.com/hyperboloide/lk" - "github.com/pkg/errors" ) // ErrLicenseInvalidSignature is the error returned when the license has an invalid signature @@ -22,47 +23,51 @@ func IsExpired(l License) bool { } // Sign signs a license and returns the base32 encoded license key -func Sign(privateKey string, l interface{}) (string, error) { +func Sign(privateKey string, l any) (string, error) { b, err := json.Marshal(l) if err != nil { - return "", errors.Wrap(err, "marshaling json") + return "", fmt.Errorf("marshaling json: %w", err) } key, err := lk.PrivateKeyFromB32String(privateKey) if err != nil { - return "", errors.Wrap(err, "unmarshaling key") + return "", fmt.Errorf("unmarshaling key: %w", err) } lic, err := lk.NewLicense(key, b) if err != nil { - return "", errors.Wrap(err, "generating license") + return "", fmt.Errorf("generating license: %w", err) } licenseB32, err := lic.ToB32String() - return licenseB32, errors.Wrap(err, "transforming license to base32 string") + if err != nil { + return "", fmt.Errorf("transforming license to base32 string: %w", err) + } + + return licenseB32, nil } // LicenseFromKey takes a licenseKey and a public key and rehydrates it into a // the destination. -func LicenseFromKey(licenseKey, publicKey string, dest interface{}) error { +func LicenseFromKey(licenseKey, publicKey string, dest any) error { key, err := lk.PublicKeyFromB32String(publicKey) if err != nil { - return errors.Wrap(err, "unpacking base32 public key") + return fmt.Errorf("unpacking base32 public key: %w", err) } license, err := lk.LicenseFromB32String(licenseKey) if err != nil { - return errors.Wrap(err, "unmarshalling license from b32 string") + return fmt.Errorf("unmarshalling license from b32 string: %w", err) } if ok, err := license.Verify(key); err != nil { - return errors.Wrap(err, "verifying license") + return fmt.Errorf("verifying license: %w", err) } else if !ok { return ErrLicenseInvalidSignature } if err := json.Unmarshal(license.Data, &dest); err != nil { - return errors.Wrap(err, "unmarshaling license payload json") + return fmt.Errorf("unmarshaling license payload json: %w", err) } return nil } diff --git a/licensing/mf2.go b/licensing/mf2.go index aee0599..45f3b03 100644 --- a/licensing/mf2.go +++ b/licensing/mf2.go @@ -9,8 +9,6 @@ import ( "fmt" "net/http" "time" - - "github.com/pkg/errors" ) // Canonical HTTP header names for the HMAC key ID and signature headers @@ -98,7 +96,7 @@ type PingerMF2 struct { func (p PingerMF2) Ping() (PingResponseMF2, error) { bodyBytes, err := json.Marshal(PingRequestMF2{CurrentTime: time.Now()}) if err != nil { - return PingResponseMF2{}, errors.Wrap(err, "marshaling request body") + return PingResponseMF2{}, fmt.Errorf("marshaling request body: %w", err) } // namespace the ping url with the app name (mf2) in case we ever have to add @@ -106,7 +104,7 @@ func (p PingerMF2) Ping() (PingResponseMF2, error) { url := fmt.Sprintf("https://%s/mf2/ping", p.license.LicenseHost) req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(bodyBytes)) if err != nil { - return PingResponseMF2{}, errors.Wrap(err, "constructing request") + return PingResponseMF2{}, fmt.Errorf("constructing request: %w", err) } // sign the request, add the HTTP headers @@ -117,17 +115,17 @@ func (p PingerMF2) Ping() (PingResponseMF2, error) { resp, err := p.client.Do(req) if err != nil { - return PingResponseMF2{}, errors.Wrap(err, "executing request") + return PingResponseMF2{}, fmt.Errorf("executing request: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return PingResponseMF2{}, errors.Errorf("non-200 status received: %d", resp.StatusCode) + return PingResponseMF2{}, fmt.Errorf("non-200 status received: %d", resp.StatusCode) } var envelope EnvelopePingResponse if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil { - return PingResponseMF2{}, errors.Wrap(err, "decoding envelope") + return PingResponseMF2{}, fmt.Errorf("decoding envelope: %w", err) } // Validate the signature of the response. The payload inside the envelope is @@ -136,7 +134,7 @@ func (p PingerMF2) Ping() (PingResponseMF2, error) { // license server. var pingResponse PingResponseMF2 if err := LicenseFromKey(envelope.Payload, p.licensePublicKey, &pingResponse); err != nil { - return PingResponseMF2{}, errors.Wrap(err, "extracting signed content into response") + return PingResponseMF2{}, fmt.Errorf("extracting signed content into response: %w", err) } return pingResponse, nil diff --git a/licensing/mf2_test.go b/licensing/mf2_test.go index 1a02e97..f7261d9 100644 --- a/licensing/mf2_test.go +++ b/licensing/mf2_test.go @@ -6,7 +6,7 @@ import ( "crypto/sha256" "encoding/base64" "encoding/json" - "io/ioutil" + "io" "net/http" "testing" "time" @@ -27,7 +27,7 @@ func TestPingerMF2(t *testing.T) { require.Len(t, keyID, 32) require.NotEqual(t, "", sig) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { return nil, err } @@ -49,7 +49,7 @@ func TestPingerMF2(t *testing.T) { require.NoError(t, err) return &http.Response{ - Body: ioutil.NopCloser(bytes.NewReader(b)), + Body: io.NopCloser(bytes.NewReader(b)), StatusCode: http.StatusOK, }, nil }, diff --git a/licensing/mock_doer_test.go b/licensing/mock_doer_test.go index 520f928..7c75e9f 100644 --- a/licensing/mock_doer_test.go +++ b/licensing/mock_doer_test.go @@ -18,19 +18,19 @@ var _ Doer = &DoerMock{} // DoerMock is a mock implementation of Doer. // -// func TestSomethingThatUsesDoer(t *testing.T) { +// func TestSomethingThatUsesDoer(t *testing.T) { // -// // make and configure a mocked Doer -// mockedDoer := &DoerMock{ -// DoFunc: func(in1 *http.Request) (*http.Response, error) { -// panic("mock out the Do method") -// }, -// } +// // make and configure a mocked Doer +// mockedDoer := &DoerMock{ +// DoFunc: func(in1 *http.Request) (*http.Response, error) { +// panic("mock out the Do method") +// }, +// } // -// // use mockedDoer in code that requires Doer -// // and then make assertions. +// // use mockedDoer in code that requires Doer +// // and then make assertions. // -// } +// } type DoerMock struct { // DoFunc mocks the Do method. DoFunc func(in1 *http.Request) (*http.Response, error) @@ -63,7 +63,8 @@ func (mock *DoerMock) Do(in1 *http.Request) (*http.Response, error) { // DoCalls gets all the calls that were made to Do. // Check the length with: -// len(mockedDoer.DoCalls()) +// +// len(mockedDoer.DoCalls()) func (mock *DoerMock) DoCalls() []struct { In1 *http.Request } { diff --git a/lock/locker.go b/lock/locker.go index b54c0ae..c9e1104 100644 --- a/lock/locker.go +++ b/lock/locker.go @@ -1,6 +1,8 @@ package lock -import "time" +import ( + "time" +) // Locker defines the interface for the backend lock system. type Locker interface { diff --git a/lock/mock_locker_test.go b/lock/mock_locker_test.go index 5d36a6e..b7a3dff 100644 --- a/lock/mock_locker_test.go +++ b/lock/mock_locker_test.go @@ -19,22 +19,22 @@ var _ Locker = &LockerMock{} // LockerMock is a mock implementation of Locker. // -// func TestSomethingThatUsesLocker(t *testing.T) { +// func TestSomethingThatUsesLocker(t *testing.T) { // -// // make and configure a mocked Locker -// mockedLocker := &LockerMock{ -// LockFunc: func(name string, uniqueID string, duration time.Duration) (bool, error) { -// panic("mock out the Lock method") -// }, -// UnlockFunc: func(name string, uniqueID string) error { -// panic("mock out the Unlock method") -// }, -// } +// // make and configure a mocked Locker +// mockedLocker := &LockerMock{ +// LockFunc: func(name string, uniqueID string, duration time.Duration) (bool, error) { +// panic("mock out the Lock method") +// }, +// UnlockFunc: func(name string, uniqueID string) error { +// panic("mock out the Unlock method") +// }, +// } // -// // use mockedLocker in code that requires Locker -// // and then make assertions. +// // use mockedLocker in code that requires Locker +// // and then make assertions. // -// } +// } type LockerMock struct { // LockFunc mocks the Lock method. LockFunc func(name string, uniqueID string, duration time.Duration) (bool, error) @@ -85,7 +85,8 @@ func (mock *LockerMock) Lock(name string, uniqueID string, duration time.Duratio // LockCalls gets all the calls that were made to Lock. // Check the length with: -// len(mockedLocker.LockCalls()) +// +// len(mockedLocker.LockCalls()) func (mock *LockerMock) LockCalls() []struct { Name string UniqueID string @@ -122,7 +123,8 @@ func (mock *LockerMock) Unlock(name string, uniqueID string) error { // UnlockCalls gets all the calls that were made to Unlock. // Check the length with: -// len(mockedLocker.UnlockCalls()) +// +// len(mockedLocker.UnlockCalls()) func (mock *LockerMock) UnlockCalls() []struct { Name string UniqueID string diff --git a/lock/redis_test.go b/lock/redis_test.go index c3be4d7..eaec66a 100644 --- a/lock/redis_test.go +++ b/lock/redis_test.go @@ -1,3 +1,4 @@ +//go:build int // +build int package lock diff --git a/lock/unique_test.go b/lock/unique_test.go index 5481359..6da30d0 100644 --- a/lock/unique_test.go +++ b/lock/unique_test.go @@ -1,3 +1,4 @@ +//go:build int // +build int package lock diff --git a/logger/config.go b/logger/config.go index 5caf55d..394dd38 100644 --- a/logger/config.go +++ b/logger/config.go @@ -1,13 +1,13 @@ package logger import ( + "errors" "flag" "io" "log" "os" "github.com/graymeta/env" - "github.com/pkg/errors" ) // Config is used to parse CLI flags related to logging @@ -37,7 +37,7 @@ func NewConfig(flag *flag.FlagSet, appName string) *Config { } // Logger gets the logger -func (cfg *Config) Logger(w io.Writer, keyvals ...interface{}) (*L, error) { +func (cfg *Config) Logger(w io.Writer, keyvals ...any) (*L, error) { if cfg.flag != nil && !cfg.flag.Parsed() { return nil, errors.New("must parse flags before calling Logger") } diff --git a/logger/elastic.go b/logger/elastic.go index 750eba1..b434666 100644 --- a/logger/elastic.go +++ b/logger/elastic.go @@ -20,7 +20,7 @@ func NewElasticLogger(l *L) *ElasticLogger { } // Printf logs the message to the wrapped logger at the debug level -func (el *ElasticLogger) Printf(format string, v ...interface{}) { +func (el *ElasticLogger) Printf(format string, v ...any) { // The ES library logs lots of stuff with newlines and other junk...this escapes // all that so it's a single line with the message el.l.Debug(fmt.Sprintf("%q", fmt.Sprintf(format, v...))) diff --git a/logger/http.go b/logger/http.go index 97d0a4c..4fadc09 100644 --- a/logger/http.go +++ b/logger/http.go @@ -10,7 +10,7 @@ import ( // HTTPLogger wraps a L and satisfys the interface required by // https://godoc.org/github.com/ernesto-jimenez/httplogger#HTTPLogger type HTTPLogger struct { - fn func(msg interface{}, keyvals ...interface{}) error + fn func(msg any, keyvals ...any) error } var _ httplogger.HTTPLogger = (*HTTPLogger)(nil) diff --git a/logger/logger.go b/logger/logger.go index 42a8434..bd9bc28 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -3,7 +3,6 @@ package logger import ( "fmt" "io" - "io/ioutil" "os" "strings" @@ -60,7 +59,7 @@ type L struct { } // New initializes a new logger. If w is nil, logs will be sent to stdout. -func New(w io.Writer, name, level string, keyvals ...interface{}) *L { +func New(w io.Writer, name, level string, keyvals ...any) *L { if w == nil { w = os.Stdout } @@ -84,7 +83,7 @@ func New(w io.Writer, name, level string, keyvals ...interface{}) *L { // Caller returns a log.Valuer that returns a file and line from a specified depth // in the callstack. func caller(depth int) log.Valuer { - return func() interface{} { + return func() any { c := stack.Caller(depth) // The format string here has special meaning. See // https://godoc.org/github.com/go-stack/stack#Call.Format @@ -102,7 +101,7 @@ func (l *L) New(name string) *L { } // With returns a logger with the keyvals appended to the existing logger -func (l *L) With(keyvals ...interface{}) *L { +func (l *L) With(keyvals ...any) *L { return &L{ src: l.src, Level: l.Level, @@ -111,28 +110,28 @@ func (l *L) With(keyvals ...interface{}) *L { } // Debug logs a message at the debug level -func (l *L) Debug(msg interface{}, keyvals ...interface{}) error { +func (l *L) Debug(msg any, keyvals ...any) error { return l.log(Debug, log.With(l.logger, "src", l.source(), "level", Debug.String(), "msg", msg), keyvals...) } // Info logs a message at the info level -func (l *L) Info(msg interface{}, keyvals ...interface{}) error { +func (l *L) Info(msg any, keyvals ...any) error { return l.log(Info, log.With(l.logger, "src", l.source(), "level", Info.String(), "msg", msg), keyvals...) } // Warn logs a message at the warning level -func (l *L) Warn(msg interface{}, keyvals ...interface{}) error { +func (l *L) Warn(msg any, keyvals ...any) error { return l.log(Warn, log.With(l.logger, "src", l.source(), "level", Warn.String(), "msg", msg), keyvals...) } // Err logs a message at the error level -func (l *L) Err(msg interface{}, keyvals ...interface{}) error { +func (l *L) Err(msg any, keyvals ...any) error { return l.log(Err, log.With(l.logger, "src", l.source(), "level", Err.String(), "msg", msg), keyvals...) } // Fatal logs a message at the fatal level and also exits the program by calling // os.Exit -func (l *L) Fatal(msg interface{}, keyvals ...interface{}) { +func (l *L) Fatal(msg any, keyvals ...any) { l.log(Fatal, log.With(l.logger, "src", l.source(), "level", Fatal.String(), "msg", msg), keyvals...) os.Exit(1) } @@ -141,7 +140,7 @@ func (l *L) source() string { return strings.Join(l.src, ".") } -func (l *L) log(level Level, lvl log.Logger, keyvals ...interface{}) error { +func (l *L) log(level Level, lvl log.Logger, keyvals ...any) error { if l == nil { return nil } @@ -160,5 +159,5 @@ func Default() *L { // Silence returns a logger that writes everything to /dev/null. Useful for // silencing log output from tests func Silence() *L { - return New(ioutil.Discard, "discard", "") + return New(io.Discard, "discard", "") } diff --git a/logger/nsq.go b/logger/nsq.go index 4149d37..094a04f 100644 --- a/logger/nsq.go +++ b/logger/nsq.go @@ -3,7 +3,7 @@ package logger // NSQLogger is a thin wrapper around our the Logger that bends it to // the interface uses by the go-nsq library type NSQLogger struct { - fn func(msg interface{}, keyvals ...interface{}) error + fn func(msg any, keyvals ...any) error } // NewNSQLogger initializes a new Logger diff --git a/logger/stripe.go b/logger/stripe.go index 1785983..3ff6795 100644 --- a/logger/stripe.go +++ b/logger/stripe.go @@ -1,11 +1,13 @@ package logger -import "fmt" +import ( + "fmt" +) // StripeLogger is a thin wrapper around our the Logger that bends it to // the interface uses by the stripe library type StripeLogger struct { - fn func(msg interface{}, keyvals ...interface{}) error + fn func(msg any, keyvals ...any) error } // NewStripeLogger initializes a new Logger @@ -25,6 +27,6 @@ func NewStripeLogger(l *L, level string) *StripeLogger { } // Printf prints a message to the logs -func (l *StripeLogger) Printf(format string, v ...interface{}) { +func (l *StripeLogger) Printf(format string, v ...any) { l.fn(fmt.Sprintf(format, v...)) } diff --git a/metrics/helpers.go b/metrics/helpers.go index e716716..99ac9c9 100644 --- a/metrics/helpers.go +++ b/metrics/helpers.go @@ -1,6 +1,8 @@ package metrics -import "time" +import ( + "time" +) // Timer returns a function which returns an int64 that represents the difference // in time between Time being called and the returning function being called diff --git a/metrics/logging.go b/metrics/logging.go index 1042fed..a3b1def 100644 --- a/metrics/logging.go +++ b/metrics/logging.go @@ -10,7 +10,7 @@ import ( // LoggingClient is a client that dumps stats to a Logger type LoggingClient struct { - fn func(msg interface{}, keyvals ...interface{}) error + fn func(msg any, keyvals ...any) error } // NewLoggingClient creates a new logging client that will log to logger diff --git a/metrics/routes.go b/metrics/routes.go index c17ca72..aca9416 100644 --- a/metrics/routes.go +++ b/metrics/routes.go @@ -1,11 +1,11 @@ package metrics import ( + "fmt" "sort" "strings" "github.com/gorilla/mux" - "github.com/pkg/errors" ) // SanitizeRoute cleans up a route for the Gorilla Mux to be used as a metric name @@ -41,5 +41,5 @@ func InstrumentRouter(r *mux.Router) error { return nil }) - return errors.Wrap(err, "instrumenting router") + return fmt.Errorf("instrumenting router: %w", err) } diff --git a/metrics/statsd.go b/metrics/statsd.go index 57a1220..4c11498 100644 --- a/metrics/statsd.go +++ b/metrics/statsd.go @@ -62,6 +62,7 @@ func Statsd(service string) statsd.Statsd { type StopFunc func() // NewTimer convenience function start and publish Timing stat, typical use is: +// // stop := metrics.NewTimer("my_metric") // defer stop() func NewTimer(name string) StopFunc { @@ -116,6 +117,7 @@ func Range(size int64) string { } // NewTimerBySize convenience function start and publish Timing stat bucketed by byte size, typical use is: +// // stop := metrics.NewTimerBySize("my_metric", size) // defer stop() func NewTimerBySize(name string, size int64) StopFunc { diff --git a/notification/amazonses/ses.go b/notification/amazonses/ses.go index 7c87beb..7bec51c 100644 --- a/notification/amazonses/ses.go +++ b/notification/amazonses/ses.go @@ -1,6 +1,8 @@ package amazonses import ( + "fmt" + "github.com/graymeta/gmkit/notification" "github.com/aws/aws-sdk-go/aws" @@ -8,7 +10,6 @@ import ( "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ses" "github.com/aws/aws-sdk-go/service/ses/sesiface" - "github.com/pkg/errors" ) // The environment variable names for the various SES configuration keys. @@ -28,7 +29,7 @@ func New(accessKeyID, secretKey, region string) (notification.Sender, error) { sess, err := session.NewSession(config) if err != nil { - return nil, errors.Wrap(err, "creating SES session") + return nil, fmt.Errorf("creating SES session: %w", err) } service := ses.New(sess) @@ -78,7 +79,7 @@ func (c *Sender) Send(msg notification.Message) error { _, err := c.sess.SendEmail(input) if err != nil { - return errors.Wrap(err, "sending email with Amazon SES") + return fmt.Errorf("sending email with Amazon SES: %w", err) } return nil } diff --git a/notification/config/config.go b/notification/config/config.go index 58c4e8b..a73318e 100644 --- a/notification/config/config.go +++ b/notification/config/config.go @@ -1,6 +1,7 @@ package config import ( + "errors" "flag" "os" @@ -9,8 +10,6 @@ import ( ses "github.com/graymeta/gmkit/notification/amazonses" "github.com/graymeta/gmkit/notification/noop" "github.com/graymeta/gmkit/notification/sendgrid" - - "github.com/pkg/errors" ) // Config used to setup the sender diff --git a/notification/http_previewer.go b/notification/http_previewer.go index 1693931..01a2593 100644 --- a/notification/http_previewer.go +++ b/notification/http_previewer.go @@ -2,13 +2,13 @@ package notification import ( "bytes" + "fmt" "html/template" "log" "net/http" "github.com/gorilla/mux" "github.com/matcornic/hermes" - "github.com/pkg/errors" ) // DefaultPreviewer is the default previewer. @@ -55,14 +55,14 @@ func (p *Previewer) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (p *Previewer) emailPreviewList(w http.ResponseWriter, r *http.Request) { tmpl, err := template.New("").Parse(tmplList) if err != nil { - log.Println(errors.Wrap(err, "parsing template")) + log.Println(fmt.Errorf("parsing template: %w", err)) w.WriteHeader(http.StatusInternalServerError) return } var buf bytes.Buffer if err := tmpl.Execute(&buf, p); err != nil { - log.Println(errors.Wrap(err, "executing template")) + log.Println(fmt.Errorf("executing template: %w", err)) w.WriteHeader(http.StatusInternalServerError) return } @@ -85,7 +85,7 @@ func (p *Previewer) emailPreview(w http.ResponseWriter, r *http.Request) { txt, html, err := p.Renderer.Render(email) if err != nil { - log.Println(errors.Wrap(err, "rendering email template")) + log.Println(fmt.Errorf("rendering email template: %w", err)) w.WriteHeader(http.StatusInternalServerError) return } diff --git a/notification/render.go b/notification/render.go index 9007d19..67e341e 100644 --- a/notification/render.go +++ b/notification/render.go @@ -1,8 +1,9 @@ package notification import ( + "fmt" + "github.com/matcornic/hermes" - "github.com/pkg/errors" ) // Renderer is an interface for rendering emails. @@ -20,11 +21,11 @@ type HermesRenderer struct { func (r *HermesRenderer) Render(tmpl hermes.Email) (string, string, error) { html, err := r.Template.GenerateHTML(tmpl) if err != nil { - return "", "", errors.Wrap(err, "generating html email") + return "", "", fmt.Errorf("generating html email: %w", err) } text, err := r.Template.GeneratePlainText(tmpl) if err != nil { - return "", "", errors.Wrap(err, "generating plaintext email") + return "", "", fmt.Errorf("generating plaintext email: %w", err) } return text, html, nil diff --git a/notification/sender_mock.go b/notification/sender_mock.go index 6813410..240117a 100644 --- a/notification/sender_mock.go +++ b/notification/sender_mock.go @@ -13,19 +13,19 @@ var ( // SenderMock is a mock implementation of Sender. // -// func TestSomethingThatUsesSender(t *testing.T) { +// func TestSomethingThatUsesSender(t *testing.T) { // -// // make and configure a mocked Sender -// mockedSender := &SenderMock{ -// SendFunc: func(msg Message) error { -// panic("TODO: mock out the Send method") -// }, -// } +// // make and configure a mocked Sender +// mockedSender := &SenderMock{ +// SendFunc: func(msg Message) error { +// panic("TODO: mock out the Send method") +// }, +// } // -// // TODO: use mockedSender in code that requires Sender -// // and then make assertions. +// // TODO: use mockedSender in code that requires Sender +// // and then make assertions. // -// } +// } type SenderMock struct { // SendFunc mocks the Send method. SendFunc func(msg Message) error @@ -58,7 +58,8 @@ func (mock *SenderMock) Send(msg Message) error { // SendCalls gets all the calls that were made to Send. // Check the length with: -// len(mockedSender.SendCalls()) +// +// len(mockedSender.SendCalls()) func (mock *SenderMock) SendCalls() []struct { Msg Message } { diff --git a/notification/sendgrid/sendgrid.go b/notification/sendgrid/sendgrid.go index 9bd7d08..4d69f21 100644 --- a/notification/sendgrid/sendgrid.go +++ b/notification/sendgrid/sendgrid.go @@ -1,9 +1,10 @@ package sendgrid import ( + "fmt" + "github.com/graymeta/gmkit/notification" - "github.com/pkg/errors" sendgridlib "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" ) @@ -33,7 +34,7 @@ func (s *Sender) Send(msg notification.Message) error { m := mail.NewSingleEmail(from, msg.Subject, to, msg.Body, msg.BodyHTML) _, err := s.client.Send(m) if err != nil { - return errors.Wrap(err, "sending email with SendGrid") + return fmt.Errorf("sending email with SendGrid: %w", err) } } return nil diff --git a/notification/smtp/smtp.go b/notification/smtp/smtp.go index 01ebe00..b8fd38a 100644 --- a/notification/smtp/smtp.go +++ b/notification/smtp/smtp.go @@ -7,8 +7,6 @@ import ( "strings" "github.com/graymeta/gmkit/notification" - - "github.com/pkg/errors" ) // Environment variable keys controlling configuration @@ -46,27 +44,27 @@ func (c Client) Send(msg notification.Message) error { conn, err := tls.Dial("tcp", c.host+":"+c.port, &tlsConfig) if err != nil { - return errors.Wrap(err, "couldn't dial SMTP server") + return fmt.Errorf("couldn't dial SMTP server: %w", err) } smtpClient, err := smtp.NewClient(conn, c.host) if err != nil { - return errors.Wrap(err, "cannot create new SMTP client") + return fmt.Errorf("cannot create new SMTP client: %w", err) } err = smtpClient.Auth(auth) if err != nil { - return errors.Wrap(err, "cannot authenticate against SMTP server") + return fmt.Errorf("cannot authenticate against SMTP server: %w", err) } err = smtpClient.Mail(msg.From) if err != nil { - return errors.Wrap(err, "preparing new mail") + return fmt.Errorf("preparing new mail: %w", err) } for _, r := range msg.To { if err = smtpClient.Rcpt(r); err != nil { - return errors.Wrap(err, "setting receivers mails") + return fmt.Errorf("setting receivers mails: %w", err) } } @@ -83,7 +81,7 @@ func (c Client) Send(msg notification.Message) error { m := buildEmail(msg) _, err = w.Write(m) - return errors.Wrap(err, "sending email") + return fmt.Errorf("sending email: %w", err) } func buildEmail(msg notification.Message) []byte { diff --git a/notification/twilio/twilio.go b/notification/twilio/twilio.go index 3b9d28d..e48157c 100644 --- a/notification/twilio/twilio.go +++ b/notification/twilio/twilio.go @@ -1,10 +1,11 @@ package twilio import ( + "fmt" + "github.com/graymeta/gmkit/notification" twiliolib "github.com/carlosdp/twiliogo" - "github.com/pkg/errors" ) // Envioronment variable keys for configuration. @@ -32,7 +33,7 @@ func (t *Sender) Send(msg notification.Message) error { for _, r := range msg.To { _, err := twiliolib.NewMessage(t.client, msg.From, r, twiliolib.Body(msg.Body)) if err != nil { - return errors.Wrap(err, "sending Twilio SMS message") + return fmt.Errorf("sending Twilio SMS message: %w", err) } } diff --git a/pagetoken/next_page_token_test.go b/pagetoken/next_page_token_test.go index 56f0a43..5ed0626 100644 --- a/pagetoken/next_page_token_test.go +++ b/pagetoken/next_page_token_test.go @@ -104,7 +104,7 @@ func Test_GetTokenDeets(t *testing.T) { tests := []struct { name string params map[string]string - expected map[string]interface{} + expected map[string]any }{ { name: "simple1", @@ -112,7 +112,7 @@ func Test_GetTokenDeets(t *testing.T) { "bool": "true", "param1": "value 1", }, - expected: map[string]interface{}{ + expected: map[string]any{ "bool": true, "param1": "value 1", }, @@ -124,7 +124,7 @@ func Test_GetTokenDeets(t *testing.T) { "param1": "value 1", "param2": "value 2", }, - expected: map[string]interface{}{ + expected: map[string]any{ "bool": true, "param1": "value 1", "param2": "value 2", @@ -138,7 +138,7 @@ func Test_GetTokenDeets(t *testing.T) { "param2": "value 2", "param3": "value 3", }, - expected: map[string]interface{}{ + expected: map[string]any{ "bool": true, "param1": "value 1", "param2": "value 2", @@ -154,7 +154,7 @@ func Test_GetTokenDeets(t *testing.T) { "param3": "value 3", "param4": "value 4", }, - expected: map[string]interface{}{ + expected: map[string]any{ "bool": false, "param1": "value 1", "param2": "value 2", @@ -172,7 +172,7 @@ func Test_GetTokenDeets(t *testing.T) { "param4": "value 4", "param5": "value 5", }, - expected: map[string]interface{}{ + expected: map[string]any{ "bool": false, "param1": "value 1", "param2": "value 2", @@ -192,7 +192,7 @@ func Test_GetTokenDeets(t *testing.T) { "param5": "value 5", "param6": "value 6", }, - expected: map[string]interface{}{ + expected: map[string]any{ "bool": false, "param1": "value 1", "param2": "value 2", @@ -209,7 +209,7 @@ func Test_GetTokenDeets(t *testing.T) { "param1": "", "param2": "", }, - expected: map[string]interface{}{ + expected: map[string]any{ "bool": false, "param1": "", "param2": "", @@ -218,7 +218,7 @@ func Test_GetTokenDeets(t *testing.T) { { name: "no Params", params: map[string]string{}, - expected: map[string]interface{}{"bool": false}, + expected: map[string]any{"bool": false}, }, } for _, tt := range tests { diff --git a/postgres/bulk.go b/postgres/bulk.go index 32b772f..9d13d26 100644 --- a/postgres/bulk.go +++ b/postgres/bulk.go @@ -1,13 +1,15 @@ package postgres -import "context" +import ( + "context" +) // Bulker is an interface that defines the behavior a type needs to // implement to be bulk insert/updated into PG. type Bulker interface { Len() int PrepareStatement() string - KeyedArgsAtIndex(index int) (key string, arguments []interface{}) + KeyedArgsAtIndex(index int) (key string, arguments []any) TableName() string } @@ -34,7 +36,6 @@ func BulkInsert(ctx context.Context, tx CRUD, itemsToInsert Bulker) (rowsInserte return 0, Err(itemsToInsert.TableName(), err) } } - idsMap = nil if _, err := stmt.ExecContext(ctx); err != nil { return 0, Err(itemsToInsert.TableName(), err) diff --git a/postgres/cube.go b/postgres/cube.go index 2f2235a..7553e4f 100644 --- a/postgres/cube.go +++ b/postgres/cube.go @@ -47,7 +47,7 @@ func (c Cube) Value() (driver.Value, error) { // Scan converts the postgesql cube bytes into a valid cube type. This // again was inspired by github.com/lib/pq.FloatArray type. -func (c *Cube) Scan(src interface{}) error { +func (c *Cube) Scan(src any) error { switch src := src.(type) { case []byte: return c.scanBytes(src) diff --git a/postgres/tx.go b/postgres/tx.go index efbf32c..0d6b1ac 100644 --- a/postgres/tx.go +++ b/postgres/tx.go @@ -3,9 +3,9 @@ package postgres import ( "context" "database/sql" + "fmt" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" ) // NewTx creates a new database transaction with default isolation levels and @@ -29,7 +29,7 @@ func Commit(tx *sqlx.Tx, resource string) error { // Rollback undoes the supplied transaction. func Rollback(tx *sqlx.Tx, resource string, err error) error { if commitErr := tx.Rollback(); commitErr != nil { - return errors.Wrap(err, Err(resource, commitErr).Error()) + return fmt.Errorf(Err(resource, commitErr).Error()+": %w", err) } return err } diff --git a/postgres/types.go b/postgres/types.go index 11d0d68..fea4629 100644 --- a/postgres/types.go +++ b/postgres/types.go @@ -26,7 +26,7 @@ type Preparer interface { // Execer provides the exec behavior. type Execer interface { - ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) + ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) } // ExecRebinder is an interface that is agnostic for database transactions for the @@ -38,35 +38,35 @@ type ExecRebinder interface { // NamedExecer preforms an operating that returns an sql.Result and error. type NamedExecer interface { - NamedExecContext(ctx context.Context, query string, args interface{}) (sql.Result, error) + NamedExecContext(ctx context.Context, query string, args any) (sql.Result, error) } // Querier preforms an operating that returns a pointer sql.Rows and possible error. type Querier interface { - QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error) + QueryxContext(ctx context.Context, query string, args ...any) (*sqlx.Rows, error) } // RowQueryBinder preforms an operating that returns a pointer sql.Result. type RowQueryBinder interface { - QueryRowxContext(ctx context.Context, query string, args ...interface{}) *sqlx.Row + QueryRowxContext(ctx context.Context, query string, args ...any) *sqlx.Row Rebinder } // QueryBinder preforms an operating that returns a pointer sql.Result. type QueryBinder interface { - QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error) + QueryxContext(ctx context.Context, query string, args ...any) (*sqlx.Rows, error) Rebinder } // NamedRowQuerier allows you to use the named query arguments with a row query. type NamedRowQuerier interface { - QueryRowxContext(ctx context.Context, query string, args ...interface{}) *sqlx.Row + QueryRowxContext(ctx context.Context, query string, args ...any) *sqlx.Row NameBinder } // NamedQuerier allows you to use the named query arguments with a query. type NamedQuerier interface { - QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error) + QueryxContext(ctx context.Context, query string, args ...any) (*sqlx.Rows, error) NameBinder } @@ -79,7 +79,7 @@ type NamedGetBinder interface { // Getter provides get functionality. type Getter interface { - GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error + GetContext(ctx context.Context, dest any, query string, args ...any) error } // GetRebinder provides the get and rebinding functionality. @@ -90,7 +90,7 @@ type GetRebinder interface { // NameBinder preforms an operating that returns a pointer sql.Result. type NameBinder interface { - BindNamed(query string, v interface{}) (bindedQuery string, args []interface{}, err error) + BindNamed(query string, v any) (bindedQuery string, args []any, err error) } // Rebinder preforms a strings altering operation. @@ -100,7 +100,7 @@ type Rebinder interface { // Selecter performs select behavior with contexts. type Selecter interface { - SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error + SelectContext(ctx context.Context, dest any, query string, args ...any) error } // SelectBinder preforms a query with a context. diff --git a/postgres/wherables.go b/postgres/wherables.go index bd21881..080aec9 100644 --- a/postgres/wherables.go +++ b/postgres/wherables.go @@ -10,7 +10,7 @@ import ( // Whereable is a way of creating a functional query statement for different lookups. type Whereable interface { - Clause(rebinder Rebinder) (query string, args []interface{}, err error) + Clause(rebinder Rebinder) (query string, args []any, err error) } // All provides a nil that indicates no Where clause is provided. @@ -21,17 +21,17 @@ func All() Whereable { // Equals is a struct used to represent a part of a where clause type Equals struct { Key string - Val interface{} + Val any } // Clause prints out a sql ready statement for the Rebinder to repackage. -func (e Equals) Clause(rb Rebinder) (string, []interface{}, error) { +func (e Equals) Clause(rb Rebinder) (string, []any, error) { query := fmt.Sprintf("%s = %s", e.Key, rb.Rebind("?")) - return query, []interface{}{e.Val}, nil + return query, []any{e.Val}, nil } // ByFieldEquals creates a `{field} = ?` argument for a Where clause. -func ByFieldEquals(field string, value interface{}) Whereable { +func ByFieldEquals(field string, value any) Whereable { return Equals{ Key: field, Val: value, @@ -41,17 +41,17 @@ func ByFieldEquals(field string, value interface{}) Whereable { // notEquals is a struct used to represent a part of a where clause type notEquals struct { Key string - Val interface{} + Val any } // Clause prints out a sql ready statement for the Rebinder to repackage. -func (ne notEquals) Clause(rb Rebinder) (string, []interface{}, error) { +func (ne notEquals) Clause(rb Rebinder) (string, []any, error) { query := fmt.Sprintf("%s != %s", ne.Key, rb.Rebind("?")) - return query, []interface{}{ne.Val}, nil + return query, []any{ne.Val}, nil } // ByFieldNotEquals creates a `{field} = ?` argument for a Where clause. -func ByFieldNotEquals(field string, value interface{}) Whereable { +func ByFieldNotEquals(field string, value any) Whereable { return notEquals{ Key: field, Val: value, @@ -59,7 +59,7 @@ func ByFieldNotEquals(field string, value interface{}) Whereable { } // ToWhereClause adds WHERE prefix to a whereable's clause output if the whereable is not nil -func ToWhereClause(rebinder Rebinder, wherable Whereable) (clause string, args []interface{}, err error) { +func ToWhereClause(rebinder Rebinder, wherable Whereable) (clause string, args []any, err error) { if wherable == nil { return "", nil, nil } @@ -85,9 +85,9 @@ func (group) Rebind(q string) string { return sqlx.Rebind(sqlx.QUESTION, q) } -func (g group) Clause(rb Rebinder) (string, []interface{}, error) { +func (g group) Clause(rb Rebinder) (string, []any, error) { var qParts []string - var args []interface{} + var args []any for _, w := range g.wheres { if w == nil { continue @@ -129,7 +129,7 @@ func Or(first Whereable, second Whereable, rest ...Whereable) Whereable { } // ByItemID creates a `id = ?` argument for a Where clause. -func ByItemID(id interface{}) Whereable { +func ByItemID(id any) Whereable { return Equals{ Key: "item_id", Val: id, @@ -137,7 +137,7 @@ func ByItemID(id interface{}) Whereable { } // ByID creates a `id = ?` argument for a Where clause. -func ByID(id interface{}) Whereable { +func ByID(id any) Whereable { return Equals{ Key: "id", Val: id, @@ -145,7 +145,7 @@ func ByID(id interface{}) Whereable { } // ByLocationID creates a `location_id = ?` arugment for a Where clause. -func ByLocationID(id interface{}) Whereable { +func ByLocationID(id any) Whereable { return Equals{ Key: "location_id", Val: id, @@ -154,10 +154,10 @@ func ByLocationID(id interface{}) Whereable { type is struct { key string - val interface{} + val any } -func (i is) Clause(rb Rebinder) (string, []interface{}, error) { +func (i is) Clause(rb Rebinder) (string, []any, error) { query := fmt.Sprintf("%s IS %s", i.key, i.val) return query, nil, nil } @@ -173,11 +173,11 @@ func IDsNotNull() Whereable { // In is a struct used to represent an IN clause type In struct { Key string - Vals []interface{} + Vals []any } // Clause prints out a sql ready statement for the Rebinder to repackage. -func (i In) Clause(rb Rebinder) (string, []interface{}, error) { +func (i In) Clause(rb Rebinder) (string, []any, error) { query := fmt.Sprintf("%s IN (?)", i.Key) query, args, err := sqlx.In(query, i.Vals) if err != nil { @@ -187,7 +187,7 @@ func (i In) Clause(rb Rebinder) (string, []interface{}, error) { } // ByFieldIn creates a `{field} = (?, ?, ...)` argument for a Where clause. -func ByFieldIn(field string, values ...interface{}) Whereable { +func ByFieldIn(field string, values ...any) Whereable { return In{ Key: field, Vals: values, @@ -196,7 +196,7 @@ func ByFieldIn(field string, values ...interface{}) Whereable { // ByIDsIn provides a where clause with the IN syntax, matching many rows potentially. func ByIDsIn(ids ...string) Whereable { - var vals []interface{} + var vals []any for _, id := range ids { vals = append(vals, id) } @@ -208,7 +208,7 @@ func ByIDsIn(ids ...string) Whereable { // ByItemIDsIn provides a where clause with the IN syntax, matching many rows potentially. func ByItemIDsIn(ids ...string) Whereable { - var vals []interface{} + var vals []any for _, id := range ids { vals = append(vals, id) } @@ -220,12 +220,12 @@ func ByItemIDsIn(ids ...string) Whereable { type like struct { key string - val interface{} + val any } -func (l like) Clause(rb Rebinder) (string, []interface{}, error) { +func (l like) Clause(rb Rebinder) (string, []any, error) { query := fmt.Sprintf("%s LIKE %s", l.key, rb.Rebind("?")) - return query, []interface{}{l.val}, nil + return query, []any{l.val}, nil } // Like creates a where clause that uses a like matcher. diff --git a/postgres/wherables_test.go b/postgres/wherables_test.go index ce4f9ed..b024c07 100644 --- a/postgres/wherables_test.go +++ b/postgres/wherables_test.go @@ -14,7 +14,7 @@ func TestWherables(t *testing.T) { tests := []struct { name string expectedQuery string - expectedArgs []interface{} + expectedArgs []any whereable postgres.Whereable }{ { @@ -26,55 +26,55 @@ func TestWherables(t *testing.T) { { "ByFieldEquals", "WHERE test = $1", - []interface{}{"test"}, + []any{"test"}, postgres.ByFieldEquals("test", "test"), }, { "ByItemID", "WHERE item_id = $1", - []interface{}{"test"}, + []any{"test"}, postgres.ByItemID("test"), }, { "ByID", "WHERE id = $1", - []interface{}{"test"}, + []any{"test"}, postgres.ByID("test"), }, { "ByLocationID", "WHERE location_id = $1", - []interface{}{"test"}, + []any{"test"}, postgres.ByLocationID("test"), }, { "In", "WHERE test IN ($1, $2, $3)", - []interface{}{"one", "two", "three"}, + []any{"one", "two", "three"}, postgres.ByFieldIn("test", "one", "two", "three"), }, { "ByIDsIn", "WHERE id IN ($1, $2, $3)", - []interface{}{"one", "two", "three"}, + []any{"one", "two", "three"}, postgres.ByIDsIn("one", "two", "three"), }, { "ByItemIDsIn", "WHERE item_id IN ($1, $2, $3)", - []interface{}{"one", "two", "three"}, + []any{"one", "two", "three"}, postgres.ByItemIDsIn("one", "two", "three"), }, { "Like", "WHERE test LIKE $1", - []interface{}{"test"}, + []any{"test"}, postgres.Like("test", "test"), }, { "And", "WHERE (id = $1 AND item_id = $2)", - []interface{}{"one", "two"}, + []any{"one", "two"}, postgres.And( postgres.ByID("one"), postgres.ByItemID("two"), @@ -83,7 +83,7 @@ func TestWherables(t *testing.T) { { "Or", "WHERE (id = $1 OR item_id = $2)", - []interface{}{"one", "two"}, + []any{"one", "two"}, postgres.Or( postgres.ByID("one"), postgres.ByItemID("two"), @@ -92,7 +92,7 @@ func TestWherables(t *testing.T) { { "And and Or", "WHERE (id = $1 AND (item_id = $2 OR item_id = $3))", - []interface{}{"one", "two", "three"}, + []any{"one", "two", "three"}, postgres.And( postgres.ByID("one"), postgres.Or( diff --git a/testhelpers/http.go b/testhelpers/http.go index 39f57a7..8e42118 100644 --- a/testhelpers/http.go +++ b/testhelpers/http.go @@ -3,6 +3,7 @@ package testhelpers import ( "bytes" "encoding/json" + "fmt" "io" "net" "net/http" @@ -11,7 +12,6 @@ import ( "testing" "time" - "github.com/pkg/errors" "github.com/stretchr/testify/require" ) @@ -172,14 +172,14 @@ func Do(t *testing.T, method, addr string, body io.Reader) *http.Response { t.Helper() req, err := http.NewRequest(method, addr, body) - require.NoError(t, errors.Wrap(err, "new request")) + require.NoError(t, fmt.Errorf("new request: %w", err)) client := http.Client{ Timeout: 2 * time.Second, } resp, err := client.Do(req) - require.NoError(t, errors.Wrap(err, "do")) + require.NoError(t, fmt.Errorf("do: %w", err)) return resp } @@ -198,7 +198,7 @@ func GetURL(t *testing.T, addr string) *url.URL { // EncodeBody is a helper func for encoding a type into an bytes.Buffer type. // Can be used for a response body or whatever else. The returned buffer can // be written or read from as needed. -func EncodeBody(t *testing.T, v interface{}) *bytes.Buffer { +func EncodeBody(t *testing.T, v any) *bytes.Buffer { t.Helper() var buf bytes.Buffer @@ -210,7 +210,7 @@ func EncodeBody(t *testing.T, v interface{}) *bytes.Buffer { // DecodeBody is a helper for decoding an io.reader (i.e. response body) // into the destination type (v). -func DecodeBody(t *testing.T, r io.Reader, v interface{}) { +func DecodeBody(t *testing.T, r io.Reader, v any) { t.Helper() if err := json.NewDecoder(r).Decode(v); err != nil { @@ -219,7 +219,7 @@ func DecodeBody(t *testing.T, r io.Reader, v interface{}) { } // JSONPrettyPrint pretty prints a json body in all its glory. -func JSONPrettyPrint(t *testing.T, v interface{}) { +func JSONPrettyPrint(t *testing.T, v any) { t.Helper() b, err := json.MarshalIndent(v, "", "\t") diff --git a/testhelpers/working_dir.go b/testhelpers/working_dir.go index 41521b2..bd84260 100644 --- a/testhelpers/working_dir.go +++ b/testhelpers/working_dir.go @@ -1,11 +1,9 @@ package testhelpers import ( - "io/ioutil" + "fmt" "os" "path/filepath" - - "github.com/pkg/errors" ) // WorkDir creates a new temporary working directory while storing @@ -20,19 +18,16 @@ func NewWorkingDir() (*WorkDir, error) { twd := &WorkDir{} var err error - twd.tmp, err = ioutil.TempDir("", "") - if err != nil { - return nil, errors.Wrap(err, "creating directory") - } + twd.tmp = os.TempDir() twd.cwd, err = os.Getwd() if err != nil { - return nil, errors.Wrap(err, "getting current wd") + return nil, fmt.Errorf("getting current wd: %w", err) } err = os.Chdir(twd.tmp) if err != nil { - return nil, errors.Wrap(err, "changing cwd") + return nil, fmt.Errorf("changing cwd: %w", err) } return twd, nil diff --git a/uuid/uuid.go b/uuid/uuid.go index 7b2b742..6724045 100644 --- a/uuid/uuid.go +++ b/uuid/uuid.go @@ -10,10 +10,9 @@ import ( // TimestampUUID generates timestamp UUID, 32 bits are a timestamp in hexadecimal and 96 random // for example: // -// 56d43a23c379031f51b2bb406b8703dc -// --------|----------------------- -// time random -// +// 56d43a23c379031f51b2bb406b8703dc +// --------|----------------------- +// time random func TimestampUUID() (string, error) { now := uint32(time.Now().UTC().Unix()) b := make([]byte, 12)