Skip to content

Commit 31358ac

Browse files
authored
chore: add golangci-lint (#132)
1 parent 861005c commit 31358ac

File tree

9 files changed

+95
-38
lines changed

9 files changed

+95
-38
lines changed

.github/workflows/lint.yaml

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -40,22 +40,21 @@ jobs:
4040
} catch (e) {
4141
console.log('Failed to remove label. Another job may have already removed it!');
4242
}
43-
4443
- name: Setup Go
4544
uses: actions/setup-go@v3
4645
with:
4746
go-version: "1.19"
48-
49-
- name: Install goimports
50-
run: go install golang.org/x/tools/cmd/goimports@latest
51-
5247
- name: Checkout code
5348
uses: actions/checkout@v3
5449
with:
5550
ref: ${{ github.event.pull_request.head.sha }}
5651
repository: ${{ github.event.pull_request.head.repo.full_name }}
57-
58-
- run: goimports -w .
59-
- run: go mod tidy
60-
- name: Verify no changes from goimports and go mod tidy. If you're reading this and the check has failed, run `goimports -w . && go mod tidy`.
61-
run: git diff --exit-code
52+
- name: >
53+
Verify go mod tidy. If you're reading this and the check has
54+
failed, run `goimports -w . && go mod tidy && golangci-lint run`
55+
run: |
56+
go mod tidy && git diff --exit-code
57+
- name: golangci-lint
58+
uses: golangci/golangci-lint-action@v3
59+
with:
60+
version: latest

.golangci.yml

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Copyright 2022 Google LLC.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
# .golangci.yml
15+
linters:
16+
disable-all: true
17+
enable:
18+
- goimports
19+
- revive
20+
issues:
21+
exclude-use-default: false
22+
linters-settings:
23+
revive:
24+
rules:
25+
- name: blank-imports
26+
- name: context-as-argument
27+
- name: context-keys-type
28+
- name: dot-imports
29+
- name: error-return
30+
- name: error-strings
31+
- name: error-naming
32+
- name: exported
33+
- name: if-return
34+
- name: increment-decrement
35+
- name: var-naming
36+
- name: var-declaration
37+
- name: range
38+
- name: receiver-naming
39+
- name: time-naming
40+
- name: unexported-return
41+
- name: indent-error-flow
42+
- name: errorf
43+
- name: empty-block
44+
- name: superfluous-else
45+
- name: unused-parameter
46+
- name: unreachable-code
47+
- name: redefines-builtin-id
48+
- name: range-val-in-closure
49+
- name: range-val-address
50+
- name: import-shadowing

dialer_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ package alloydbconn
1717
import (
1818
"context"
1919
"errors"
20-
"io/ioutil"
20+
"io"
2121
"net"
2222
"os"
2323
"strings"
@@ -69,7 +69,7 @@ func TestDialerCanConnectToInstance(t *testing.T) {
6969
}
7070
defer conn.Close()
7171

72-
data, err := ioutil.ReadAll(conn)
72+
data, err := io.ReadAll(conn)
7373
if err != nil {
7474
t.Fatalf("expected ReadAll to succeed, got error %v", err)
7575
}

driver/pgxv4/postgres_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import (
2323
)
2424

2525
// Example shows how to use the AlloyDB driver
26-
func ExamplePostgresConnection() {
26+
func ExampleRegisterDriver() {
2727
// Note that sslmode=disable is required it does not mean that the connection
2828
// is unencrypted. All connections via the proxy are completely encrypted.
2929
pgxv4.RegisterDriver("alloydb")

internal/alloydb/instance.go

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,6 @@ func parseInstURI(cn string) (instanceURI, error) {
6767
return c, nil
6868
}
6969

70-
type metadata struct {
71-
ipAddrs map[string]string
72-
version string
73-
}
74-
7570
// refreshOperation is a pending result of a refresh operation of data used to connect securely. It should
7671
// only be initialized by the Instance struct as part of a refresh cycle.
7772
type refreshOperation struct {

internal/alloydb/refresh_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,8 @@ func TestRefreshFailsFast(t *testing.T) {
114114
}
115115

116116
// force the rate limiter to throttle with a timed out context
117-
ctx, _ = context.WithTimeout(context.Background(), time.Millisecond)
117+
ctx, cancel = context.WithTimeout(context.Background(), time.Millisecond)
118+
defer cancel()
118119
_, err = r.performRefresh(ctx, cn, RSAKey)
119120

120121
var wantErr *errtype.DialError

internal/alloydbapi/client.go

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,25 +19,30 @@ import (
1919
"context"
2020
"encoding/json"
2121
"fmt"
22-
"io/ioutil"
22+
"io"
2323
"net/http"
2424

2525
"google.golang.org/api/googleapi"
2626
"google.golang.org/api/option"
2727
htransport "google.golang.org/api/transport/http"
2828
)
2929

30+
// ConnectionInfoResponse is the response from the connection info endpoint.
3031
type ConnectionInfoResponse struct {
3132
ServerResponse googleapi.ServerResponse
3233
IPAddress string `json:"ipAddress"`
3334
InstanceUID string `json:"instanceUid"`
3435
}
3536

37+
// GenerateClientCertificateRequest is the request to generate a client
38+
// certificate.
3639
type GenerateClientCertificateRequest struct {
3740
PemCSR string `json:"pemCsr"`
3841
CertificateDuration string `json:"certDuration"`
3942
}
4043

44+
// GenerateClientCertificateResponse is the response from the certificate
45+
// endpoint.
4146
type GenerateClientCertificateResponse struct {
4247
ServerResponse googleapi.ServerResponse
4348
PemCertificate string `json:"pemCertificate"`
@@ -47,13 +52,15 @@ type GenerateClientCertificateResponse struct {
4752
// baseURL is the production API endpoint of the AlloyDB Admin API
4853
const baseURL = "https://alloydb.googleapis.com/v1beta"
4954

55+
// Client is an API client to the AlloyDB Rest API
5056
type Client struct {
5157
client *http.Client
5258
// endpoint is the base URL for the AlloyDB Admin API (e.g.
5359
// https://alloydb.googleapis.com/v1beta)
5460
endpoint string
5561
}
5662

63+
// NewClient initializes a Client.
5764
func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
5865
os := append([]option.ClientOption{
5966
option.WithEndpoint(baseURL),
@@ -69,6 +76,7 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error
6976
return &Client{client: client, endpoint: endpoint}, nil
7077
}
7178

79+
// ConnectionInfo retrieves connection info for the provided instance.
7280
func (c *Client) ConnectionInfo(ctx context.Context, project, region, cluster, instance string) (ConnectionInfoResponse, error) {
7381
u := fmt.Sprintf(
7482
"%s/projects/%s/locations/%s/clusters/%s/instances/%s/connectionInfo",
@@ -87,7 +95,7 @@ func (c *Client) ConnectionInfo(ctx context.Context, project, region, cluster, i
8795
// If the status code is 300 or greater, capture any information in the
8896
// response and return it as part of the error.
8997
if res.StatusCode >= http.StatusMultipleChoices {
90-
body, err := ioutil.ReadAll(res.Body)
98+
body, err := io.ReadAll(res.Body)
9199
if err != nil {
92100
return ConnectionInfoResponse{}, err
93101
}
@@ -110,6 +118,7 @@ func (c *Client) ConnectionInfo(ctx context.Context, project, region, cluster, i
110118
return ret, nil
111119
}
112120

121+
// GenerateClientCert creates a client certificate using the provided CSR.
113122
func (c *Client) GenerateClientCert(ctx context.Context, project, region, cluster string, csr []byte) (GenerateClientCertificateResponse, error) {
114123
u := fmt.Sprintf(
115124
"%s/projects/%s/locations/%s/clusters/%s:generateClientCertificate",
@@ -134,7 +143,7 @@ func (c *Client) GenerateClientCert(ctx context.Context, project, region, cluste
134143
// If the status code is 300 or greater, capture any information in the
135144
// response and return it as part of the error.
136145
if res.StatusCode >= http.StatusMultipleChoices {
137-
body, err := ioutil.ReadAll(res.Body)
146+
body, err := io.ReadAll(res.Body)
138147
if err != nil {
139148
return GenerateClientCertificateResponse{}, err
140149
}

internal/mock/alloydbadmin.go

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import (
2525
"encoding/json"
2626
"encoding/pem"
2727
"fmt"
28-
"io/ioutil"
28+
"io"
2929
"math/big"
3030
"net"
3131
"net/http"
@@ -37,26 +37,32 @@ import (
3737
"cloud.google.com/go/alloydbconn/internal/alloydbapi"
3838
)
3939

40+
// Option configures a FakeAlloyDBInstance
4041
type Option func(*FakeAlloyDBInstance)
4142

43+
// WithIPAddr sets the IP address of the instance.
4244
func WithIPAddr(addr string) Option {
4345
return func(f *FakeAlloyDBInstance) {
4446
f.ipAddr = addr
4547
}
4648
}
4749

50+
// WithServerName sets the name that server uses to identify itself in the TLS
51+
// handshake.
4852
func WithServerName(name string) Option {
4953
return func(f *FakeAlloyDBInstance) {
5054
f.serverName = name
5155
}
5256
}
5357

58+
// WithCertExpiry sets the expiration time of the fake instance
5459
func WithCertExpiry(expiry time.Time) Option {
5560
return func(f *FakeAlloyDBInstance) {
5661
f.certExpiry = expiry
5762
}
5863
}
5964

65+
// FakeAlloyDBInstance represents the server side proxy.
6066
type FakeAlloyDBInstance struct {
6167
project string
6268
region string
@@ -92,6 +98,7 @@ var (
9298
serverKey = mustGenerateKey()
9399
)
94100

101+
// NewFakeInstance creates a Fake AlloyDB instance.
95102
func NewFakeInstance(proj, reg, clust, name string, opts ...Option) FakeAlloyDBInstance {
96103
f := FakeAlloyDBInstance{
97104
project: proj,
@@ -167,6 +174,9 @@ func NewFakeInstance(proj, reg, clust, name string, opts ...Option) FakeAlloyDBI
167174
}
168175
signedServer, err := x509.CreateCertificate(
169176
rand.Reader, serverTemplate, rootCert, &serverKey.PublicKey, rootCAKey)
177+
if err != nil {
178+
panic(err)
179+
}
170180
serverCert, err := x509.ParseCertificate(signedServer)
171181
if err != nil {
172182
panic(err)
@@ -183,18 +193,6 @@ func NewFakeInstance(proj, reg, clust, name string, opts ...Option) FakeAlloyDBI
183193
return f
184194
}
185195

186-
func (f FakeAlloyDBInstance) clientCert() *x509.Certificate {
187-
return &x509.Certificate{
188-
SerialNumber: &big.Int{},
189-
Subject: pkix.Name{
190-
CommonName: "alloydb-client",
191-
},
192-
NotBefore: time.Now(),
193-
NotAfter: time.Now().AddDate(0, 0, 1),
194-
BasicConstraintsValid: true,
195-
}
196-
}
197-
198196
// Request represents a HTTP request for a test Server to mock responses for.
199197
//
200198
// Use NewRequest to initialize new Requests.
@@ -252,7 +250,7 @@ func CreateEphemeralSuccess(i FakeAlloyDBInstance, ct int) *Request {
252250
reqCt: ct,
253251
handle: func(resp http.ResponseWriter, req *http.Request) {
254252
// Read the body from the request.
255-
b, err := ioutil.ReadAll(req.Body)
253+
b, err := io.ReadAll(req.Body)
256254
defer req.Body.Close()
257255
if err != nil {
258256
http.Error(resp, fmt.Errorf("unable to read body: %w", err).Error(), http.StatusBadRequest)
@@ -291,6 +289,10 @@ func CreateEphemeralSuccess(i FakeAlloyDBInstance, ct int) *Request {
291289

292290
cert, err := x509.CreateCertificate(
293291
rand.Reader, template, i.intermedCert, template.PublicKey, i.intermedKey)
292+
if err != nil {
293+
http.Error(resp, fmt.Errorf("unable to create certificate: %w", err).Error(), http.StatusBadRequest)
294+
return
295+
}
294296

295297
certPEM := &bytes.Buffer{}
296298
pem.Encode(certPEM, &pem.Block{Type: "CERTIFICATE", Bytes: cert})

options.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ package alloydbconn
1717
import (
1818
"context"
1919
"crypto/rsa"
20-
"io/ioutil"
2120
"net"
2221
"net/http"
22+
"os"
2323
"time"
2424

2525
"cloud.google.com/go/alloydbconn/errtype"
@@ -28,6 +28,7 @@ import (
2828
apiopt "google.golang.org/api/option"
2929
)
3030

31+
// CloudPlatformScope is the default OAuth2 scope set on the API client.
3132
const CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"
3233

3334
// An Option is an option for configuring a Dialer.
@@ -59,7 +60,7 @@ func WithOptions(opts ...Option) Option {
5960
// authentication.
6061
func WithCredentialsFile(filename string) Option {
6162
return func(d *dialerConfig) {
62-
b, err := ioutil.ReadFile(filename)
63+
b, err := os.ReadFile(filename)
6364
if err != nil {
6465
d.err = errtype.NewConfigError(err.Error(), "n/a")
6566
return

0 commit comments

Comments
 (0)