Skip to content

Commit f3bc3b7

Browse files
committed
Add golangci lint config
- fix lint warnings - fix tests - fix other
1 parent 798b522 commit f3bc3b7

File tree

10 files changed

+88
-63
lines changed

10 files changed

+88
-63
lines changed

.golangci.yaml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
linters-settings:
2+
govet:
3+
check-shadowing: true

main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,6 @@ import (
77
)
88

99
func main() {
10-
godotenv.Load()
10+
_ = godotenv.Load()
1111
src.InitServer()
1212
}

src/filter.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ func getCachedSSAs(ctx appContext, uris []string) ([]*ImageAnnotation, []string,
1717
return nil, nil, err
1818
}
1919

20-
uncachedURIs := make([]string, 0)
20+
uncachedURIs := make([]string, 0, len(uris))
2121

2222
for _, uri := range uris {
2323
found := false
@@ -59,7 +59,7 @@ func filterImages(ctx appContext, uris []string, licenseID string) ([]*ImageAnno
5959
uris = uris[:remainingUsage]
6060
}
6161
if remainingUsage <= 0 { // return early if trial license is expired
62-
license, err := ctx.licenseStore.ExpireTrial(license)
62+
license, err = ctx.licenseStore.ExpireTrial(license)
6363
if err != nil {
6464
return res, fmt.Errorf("failed to mark trial license as expired: %s", err.Error())
6565
} else {
@@ -78,21 +78,21 @@ func filterImages(ctx appContext, uris []string, licenseID string) ([]*ImageAnno
7878
if err = ctx.licenseStore.UpdateLicense(license); err != nil {
7979
ctx.logger.Error().Msgf("failed to update license request count: %s", err)
8080
}
81-
if err := IncrementSubscriptionMeter(ctx.config.StripeKey, license, int64(len(annotateImageResponses))); err != nil {
81+
if err = IncrementSubscriptionMeter(ctx.config.StripeKey, license, int64(len(annotateImageResponses))); err != nil {
8282
ctx.logger.Error().Msgf("failed to update stripe subscription usage: %s", err.Error())
8383
}
8484
}
8585

8686
var buildSSARes = func(annotations []*pb.AnnotateImageResponse) []*ImageAnnotation {
87-
var res []*ImageAnnotation
87+
var annoRes []*ImageAnnotation
8888
for i, annotation := range annotations {
8989
if annotation == nil {
9090
continue
9191
}
9292
uri := uris[i]
93-
res = append(res, annotationToSafeSearchResponseRes(uri, annotation))
93+
annoRes = append(annoRes, annotationToSafeSearchResponseRes(uri, annotation))
9494
}
95-
return res
95+
return annoRes
9696
}
9797

9898
safeSearchAnnotationsRes := buildSSARes(annotateImageResponses)

src/handlers.go

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,19 @@ import (
1616
"github.com/stripe/stripe-go/v74/webhook"
1717
)
1818

19-
func health(w http.ResponseWriter, req *http.Request) {
19+
func handleHealth(ctx appContext, w http.ResponseWriter, req *http.Request) (int, error) {
2020
w.WriteHeader(200)
21-
w.Write([]byte("All Good ☮️"))
21+
if _, err := w.Write([]byte("All Good ☮️")); err != nil {
22+
return http.StatusInternalServerError, fmt.Errorf("failed to write response: %v", err)
23+
}
24+
25+
return http.StatusOK, nil
2226
}
2327

2428
const MAX_IMAGES_PER_REQUEST = 16
2529

2630
func removeDuplicates(logger zerolog.Logger, vals []string) []string {
27-
res := make([]string, 0)
31+
res := make([]string, 0, len(vals))
2832
strMap := make(map[string]bool, 0)
2933

3034
for _, v := range vals {
@@ -81,7 +85,9 @@ func handleBatchFilter(ctx appContext, w http.ResponseWriter, req *http.Request)
8185
}
8286

8387
w.Header().Set("Content-Type", "application/json")
84-
json.NewEncoder(w).Encode(res)
88+
if err := json.NewEncoder(w).Encode(res); err != nil {
89+
return http.StatusInternalServerError, err
90+
}
8591
return http.StatusOK, nil
8692
}
8793

@@ -123,7 +129,7 @@ func handleWebhook(ctx appContext, w http.ResponseWriter, req *http.Request) (in
123129
if license != nil {
124130
ctx.logger.Debug().Msg("existing license found, ensuring IsValid is true")
125131
license.IsValid = true
126-
if err := ctx.licenseStore.UpdateLicense(license); err != nil {
132+
if err = ctx.licenseStore.UpdateLicense(license); err != nil {
127133
return http.StatusInternalServerError, errors.New("")
128134
}
129135
// TODO: email person to remind them their subscription is renewed.
@@ -152,7 +158,7 @@ func handleWebhook(ctx appContext, w http.ResponseWriter, req *http.Request) (in
152158
metadata := map[string]string{
153159
"license": licenseID,
154160
}
155-
if _, err := customer.Update(session.Customer.ID, &stripe.CustomerParams{
161+
if _, err = customer.Update(session.Customer.ID, &stripe.CustomerParams{
156162
Params: stripe.Params{Metadata: metadata},
157163
}); err != nil {
158164
return http.StatusInternalServerError, fmt.Errorf("error adding license to customer metadata: %v", err)
@@ -219,7 +225,9 @@ func handleGetLicense(ctx appContext, w http.ResponseWriter, req *http.Request)
219225
// return
220226
// }
221227

222-
json.NewEncoder(w).Encode(license)
228+
if err := json.NewEncoder(w).Encode(license); err != nil {
229+
return http.StatusInternalServerError, err
230+
}
223231
return http.StatusOK, nil
224232
}
225233

src/images.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,9 @@ func FindAnnotationsByURI(conn pg.DB, uris []string) ([]ImageAnnotation, error)
4242
return nil, fmt.Errorf("imgURIList cannot be empty")
4343
}
4444

45-
conn.Model(&annotations).Where("uri IN (?)", pg.In(uris)).Select()
45+
if err := conn.Model(&annotations).Where("uri IN (?)", pg.In(uris)).Select(); err != nil {
46+
return nil, err
47+
}
4648

4749
return annotations, nil
4850
}

src/images_test.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package src
22

33
import (
44
"database/sql"
5+
"fmt"
56
"os"
67
"testing"
78
"time"
@@ -18,6 +19,7 @@ func getTestCtx() (appContext, error) {
1819
return ctx, err
1920
}
2021
config.DBName = "purity_test"
22+
config.DBHost = "localhost"
2123
conn, err := InitDB(config)
2224
if err != nil {
2325
return ctx, err
@@ -31,10 +33,14 @@ func getTestCtx() (appContext, error) {
3133
}
3234

3335
func TestMain(m *testing.M) {
34-
godotenv.Load()
36+
if err := godotenv.Load("../.env"); err != nil {
37+
fmt.Println(err)
38+
}
39+
m.Run()
3540
}
3641

3742
func TestImages(t *testing.T) {
43+
// t.FailNow()
3844
ctx, err := getTestCtx()
3945
if err != nil {
4046
t.Fatal(err)

src/remove_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ func TestStringSliceRemove(t *testing.T) {
2525
t.Fatalf("result array should be empty")
2626
}
2727

28-
if _, err := StringSliceRemove(arr, 100); err == nil {
28+
if _, err = StringSliceRemove(arr, 100); err == nil {
2929
t.Fatal("an error should have been thrown")
3030
}
3131

src/safe_search.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ func batchAnnotateURIs(uris []string) (*pb.BatchAnnotateImagesResponse, error) {
1717
}
1818
defer client.Close()
1919

20-
requests := make([]*pb.AnnotateImageRequest, 0)
20+
requests := make([]*pb.AnnotateImageRequest, 0, len(uris))
2121
for _, uri := range uris {
2222
requests = append(requests, &pb.AnnotateImageRequest{
2323
Image: vision.NewImageFromURI(uri),

src/server.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ func (ah appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
4444
// Updated to pass ah.appContext as a parameter to our handler type.
4545
status, err := ah.H(ah.appContext, w, r)
4646
if err != nil {
47-
log.Printf("HTTP %d: %q", status, err)
47+
ah.appContext.logger.Printf("HTTP %d: %q", status, err)
4848
switch status {
4949
case http.StatusNotFound:
5050
http.NotFound(w, r)
@@ -96,7 +96,7 @@ func InitServer() {
9696

9797
r.Use(addCorsHeaders)
9898
r.Handle("/", http.FileServer(http.Dir("./"))).Methods("GET")
99-
r.HandleFunc("/health", health).Methods("GET", "OPTIONS")
99+
r.Handle("/health", &appHandler{ctx, handleHealth}).Methods("GET", "OPTIONS")
100100
r.Handle("/license/{id}", &appHandler{ctx, handleGetLicense}).Methods("GET", "OPTIONS")
101101
r.Handle("/webhook", &appHandler{ctx, handleWebhook}).Methods("POST")
102102
// r.HandleFunc("/trial-register", handleTrialRegister).Methods("POST", "OPTIONS")

src/server_test.go

Lines changed: 49 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -33,68 +33,74 @@ type FilterTest struct {
3333
Expect FilterTestExpect
3434
}
3535

36-
func testHealthNoBody(t *testing.T) {
37-
req, err := http.NewRequest("GET", "/health", nil)
38-
if err != nil {
39-
t.Error("Failed to create test HTTP request")
40-
}
41-
42-
rr := httptest.NewRecorder()
43-
handler := http.HandlerFunc(health)
44-
45-
handler.ServeHTTP(rr, req)
46-
47-
if rr.Code != 200 {
48-
t.Errorf("Health endpoint expected response 200 but got %d", rr.Code)
49-
}
50-
}
51-
5236
type junkData struct {
5337
Name string
5438
Color int
5539
}
5640

57-
// The health endpoint given junk POST data should still simply return a 200 code.
58-
func testHealthJunkBody(t *testing.T) {
59-
someData := junkData{
60-
Name: "pil",
61-
Color: 221,
62-
}
63-
b, err := json.Marshal(someData)
64-
if err != nil {
65-
t.Error("Failed to marshal request body struct")
66-
}
67-
r := bytes.NewReader(b)
68-
req, err := http.NewRequest("POST", "/health", r)
41+
func TestHealthEndpoint(t *testing.T) {
42+
ctx, err := getTestCtx()
6943
if err != nil {
70-
t.Error("Failed to create test HTTP request")
44+
t.Error(err)
7145
}
7246

73-
rr := httptest.NewRecorder()
74-
handler := http.HandlerFunc(health)
47+
t.Run("returns 200 if there is no POST body", func(t *testing.T) {
48+
req, err := http.NewRequest("GET", "/health", nil)
49+
if err != nil {
50+
t.Error("Failed to create test HTTP request")
51+
}
7552

76-
handler.ServeHTTP(rr, req)
53+
rr := httptest.NewRecorder()
7754

78-
if rr.Code != 200 {
79-
t.Errorf("Health endpoint expected response 200 but got %d", rr.Code)
80-
}
81-
}
55+
code, err := handleHealth(ctx, rr, req)
56+
if err != nil {
57+
t.Error(err)
58+
}
59+
if code != 200 {
60+
t.Errorf("Health endpoint expected response 200 but got %d", rr.Code)
61+
}
62+
})
63+
64+
t.Run("returns 200 if there is a junk POST body", func(t *testing.T) {
65+
someData := junkData{
66+
Name: "pil",
67+
Color: 221,
68+
}
69+
b, err := json.Marshal(someData)
70+
if err != nil {
71+
t.Error("Failed to marshal request body struct")
72+
}
73+
r := bytes.NewReader(b)
74+
req, err := http.NewRequest("POST", "/health", r)
75+
if err != nil {
76+
t.Error("Failed to create test HTTP request")
77+
}
78+
79+
rr := httptest.NewRecorder()
8280

83-
func TestHealthHandler(t *testing.T) {
84-
testHealthNoBody(t)
85-
testHealthJunkBody(t)
81+
code, err := handleHealth(ctx, rr, req)
82+
if err != nil {
83+
t.Error(err)
84+
}
85+
if code != 200 {
86+
t.Errorf("Health endpoint expected response 200 but got %d", rr.Code)
87+
}
88+
})
8689
}
8790

88-
func TestServer(t *testing.T) {
91+
func TestFilterEndpoint(t *testing.T) {
8992
ctx, err := getTestCtx()
9093
if err != nil {
9194
t.Fatal(err)
9295
}
9396
ctx.logger = zerolog.Logger{}
9497

9598
t.Cleanup(func() {
96-
ctx.db.Model(&ImageAnnotation{}).Where("1=1").Delete()
97-
_, err := ctx.db.Model(&License{}).Where("1=1").Delete()
99+
_, err := ctx.db.Model(&ImageAnnotation{}).Where("1=1").Delete()
100+
if err != nil {
101+
fmt.Println("error: ", err)
102+
}
103+
_, err = ctx.db.Model(&License{}).Where("1=1").Delete()
98104
if err != nil {
99105
fmt.Println("error: ", err)
100106
}
@@ -231,7 +237,7 @@ func TestServer(t *testing.T) {
231237
t.Errorf("expected status %d but got %d", test.Expect.Code, rec.Code)
232238
}
233239
var annotations []*ImageAnnotation
234-
json.Unmarshal(rec.Body.Bytes(), &annotations)
240+
_ = json.Unmarshal(rec.Body.Bytes(), &annotations)
235241

236242
if len(annotations) != len(test.Expect.Res) {
237243
t.Errorf("expected %d annotation results but got %d", len(test.Expect.Res), len(annotations))

0 commit comments

Comments
 (0)