Skip to content

Commit

Permalink
Enable usestdlibvars linter (#3299)
Browse files Browse the repository at this point in the history
* Enable usestdlibvars linter

This linter recommends using standard library variables rather than
magic constants, so for example 200 is replaced by http.StatusOK.

Signed-off-by: Edu Gómez Escandell <egomez@redhat.com>

* Replace magic values with standard library constants

Signed-off-by: Edu Gómez Escandell <egomez@redhat.com>

---------

Signed-off-by: Edu Gómez Escandell <egomez@redhat.com>
  • Loading branch information
EduardGomezEscandell authored Jun 2, 2024
1 parent 71493fe commit dd518e7
Show file tree
Hide file tree
Showing 18 changed files with 50 additions and 49 deletions.
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ linters:
- nakedret
- revive
- unconvert
- usestdlibvars
- whitespace

run:
Expand Down
2 changes: 1 addition & 1 deletion cmd/cdi-cloner/clone-source.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ func main() {

client := createHTTPClient(clientKey, clientCert, serverCert)

req, _ := http.NewRequest("POST", url, reader)
req, _ := http.NewRequest(http.MethodPost, url, reader)

if contentType != "" {
req.Header.Set("x-cdi-content-type", contentType)
Expand Down
4 changes: 2 additions & 2 deletions pkg/apiserver/apiserver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ func doGetRequest(url string) *httptest.ResponseRecorder {
app := &cdiAPIApp{}
app.composeUploadTokenAPI()

req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequest(http.MethodGet, url, nil)
Expect(err).ToNot(HaveOccurred())
rr := httptest.NewRecorder()

Expand Down Expand Up @@ -351,7 +351,7 @@ var _ = Describe("API server tests", func() {
tokenGenerator: newUploadTokenGenerator(signingKey)}
app.composeUploadTokenAPI()

req, err := http.NewRequest("POST",
req, err := http.NewRequest(http.MethodPost,
"/apis/upload.cdi.kubevirt.io/v1beta1/namespaces/default/uploadtokenrequests",
bytes.NewReader(serializedRequest))
Expect(err).ToNot(HaveOccurred())
Expand Down
2 changes: 1 addition & 1 deletion pkg/apiserver/auth-config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ var _ = Describe("Auth config tests", func() {
Expect(secret.Labels[common.AppKubernetesComponentLabel]).To(Equal("storage"))
Expect(secret.Labels[common.AppKubernetesVersionLabel]).To(Equal(installerLabels[common.AppKubernetesVersionLabel]))

req, err := http.NewRequest("GET", "/apis", nil)
req, err := http.NewRequest(http.MethodGet, "/apis", nil)
Expect(err).ToNot(HaveOccurred())
rr := httptest.NewRecorder()

Expand Down
2 changes: 1 addition & 1 deletion pkg/apiserver/webhooks/datavolume-validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1259,7 +1259,7 @@ func validateAdmissionReview(ar *admissionv1.AdmissionReview, objects ...runtime

func serve(ar *admissionv1.AdmissionReview, handler http.Handler) *admissionv1.AdmissionResponse {
reqBytes, _ := json.Marshal(ar)
req, err := http.NewRequest("POST", "/foobar", bytes.NewReader(reqBytes))
req, err := http.NewRequest(http.MethodPost, "/foobar", bytes.NewReader(reqBytes))
Expect(err).ToNot(HaveOccurred())

req.Header.Set("Content-Type", "application/json")
Expand Down
4 changes: 2 additions & 2 deletions pkg/controller/datavolume/import-controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1660,7 +1660,7 @@ var _ = Describe("All DataVolume Tests", func() {
dv.SetUID("b856691e-1038-11e9-a5ab-525500d15501")
ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "import_progress{ownerUID=\"%v\"} 13.45", dv.GetUID()) // ignore error here
w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()
ep, err := url.Parse(ts.URL)
Expand All @@ -1679,7 +1679,7 @@ var _ = Describe("All DataVolume Tests", func() {
dv.Status.Progress = cdiv1.DataVolumeProgress("2.3%")
ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(fmt.Sprintf("import_progress{ownerUID=\"%v\"} 13.45", "b856691e-1038-11e9-a5ab-55500d15501")))
w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()
ep, err := url.Parse(ts.URL)
Expand Down
2 changes: 1 addition & 1 deletion pkg/controller/populators/forklift-populator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ var _ = Describe("Forklift populator tests", func() {

ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(fmt.Sprintf("kubevirt_cdi_openstack_populator_progress_total{ownerUID=\"%v\"} 13.45", targetPvc.GetUID())))
w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()
ep, err := url.Parse(ts.URL)
Expand Down
2 changes: 1 addition & 1 deletion pkg/controller/populators/import-populator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -571,7 +571,7 @@ var _ = Describe("Import populator tests", func() {

ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(fmt.Sprintf("import_progress{ownerUID=\"%v\"} 13.45", targetPvc.GetUID())))
w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()
ep, err := url.Parse(ts.URL)
Expand Down
18 changes: 9 additions & 9 deletions pkg/importer/http-datasource.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ func createHTTPReader(ctx context.Context, ep *url.URL, accessKey, secKey, certD
brokenForQemuImg = true
}
// http.NewRequest can only return error on invalid METHOD, or invalid url. Here the METHOD is always GET, and the url is always valid, thus error cannot happen.
req, _ := http.NewRequest("GET", ep.String(), nil)
req, _ := http.NewRequest(http.MethodGet, ep.String(), nil)

addExtraheaders(req, allExtraHeaders)

Expand All @@ -344,9 +344,9 @@ func createHTTPReader(ctx context.Context, ep *url.URL, accessKey, secKey, certD
if err != nil {
return nil, uint64(0), true, errors.Wrap(err, "HTTP request errored")
}
if resp.StatusCode != 200 {
klog.Errorf("http: expected status code 200, got %d", resp.StatusCode)
return nil, uint64(0), true, errors.Errorf("expected status code 200, got %d. Status: %s", resp.StatusCode, resp.Status)
if want := http.StatusOK; resp.StatusCode != want {
klog.Errorf("http: expected status code %d, got %d", want, resp.StatusCode)
return nil, uint64(0), true, errors.Errorf("expected status code %d, got %d. Status: %s", want, resp.StatusCode, resp.Status)
}

if contentType == cdiv1.DataVolumeKubeVirt {
Expand Down Expand Up @@ -404,7 +404,7 @@ func (hs *HTTPDataSource) pollProgress(reader *util.CountingReader, idleTime, po
}

func getContentLength(client *http.Client, ep *url.URL, accessKey, secKey string, extraHeaders []string) (uint64, error) {
req, err := http.NewRequest("HEAD", ep.String(), nil)
req, err := http.NewRequest(http.MethodHead, ep.String(), nil)
if err != nil {
return uint64(0), errors.Wrap(err, "could not create HTTP request")
}
Expand All @@ -420,9 +420,9 @@ func getContentLength(client *http.Client, ep *url.URL, accessKey, secKey string
return uint64(0), errors.Wrap(err, "HTTP request errored")
}

if resp.StatusCode != 200 {
klog.Errorf("http: expected status code 200, got %d", resp.StatusCode)
return uint64(0), errors.Errorf("expected status code 200, got %d. Status: %s", resp.StatusCode, resp.Status)
if want := http.StatusOK; resp.StatusCode != want {
klog.Errorf("http: expected status code %d, got %d", want, resp.StatusCode)
return uint64(0), errors.Errorf("expected status code %d, got %d. Status: %s", want, resp.StatusCode, resp.Status)
}

for k, v := range resp.Header {
Expand Down Expand Up @@ -512,7 +512,7 @@ func getExtraHeadersFromSecrets() ([]string, error) {
}

func getServerInfo(ctx context.Context, infoURL string) (*common.ServerInfo, error) {
req, err := http.NewRequestWithContext(ctx, "GET", infoURL, nil)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, infoURL, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to construct request for containerimage-server info")
}
Expand Down
12 changes: 6 additions & 6 deletions pkg/importer/http-datasource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ var _ = Describe("Http data source", func() {
Expect(err).NotTo(HaveOccurred())
_, _ = w.Write(body)
} else {
w.WriteHeader(500)
w.WriteHeader(http.StatusInternalServerError)
}
}))
dp, err = NewHTTPDataSource(ts2.URL+"/"+tinyCoreGz, "", "", "", cdiv1.DataVolumeKubeVirt)
Expand Down Expand Up @@ -294,7 +294,7 @@ var _ = Describe("Http reader", func() {
It("should pass auth info in request if set", func() {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
defer w.WriteHeader(200)
defer w.WriteHeader(http.StatusOK)
Expect(ok).To(BeTrue())
Expect("user").To(Equal(user))
Expect("password").To(Equal(pass))
Expand Down Expand Up @@ -378,7 +378,7 @@ var _ = Describe("Http reader", func() {

It("should continue even if HEAD is rejected, but mark broken for qemu-img", func() {
redirTs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "HEAD" {
if r.Method == http.MethodHead {
w.WriteHeader(http.StatusForbidden)
} else {
defer w.WriteHeader(http.StatusOK)
Expand Down Expand Up @@ -423,7 +423,7 @@ var _ = Describe("Http reader", func() {

It("should fail if server returns error code", func() {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
w.WriteHeader(http.StatusInternalServerError)
}))
defer ts.Close()
ep, err := url.Parse(ts.URL)
Expand All @@ -437,9 +437,9 @@ var _ = Describe("Http reader", func() {
It("should pass through extra headers", func() {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, exists := r.Header["Extra-Header"]; exists {
w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(500)
w.WriteHeader(http.StatusInternalServerError)
}
}))
defer ts.Close()
Expand Down
6 changes: 3 additions & 3 deletions pkg/importer/imageio-datasource.go
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ func (reader *extentReader) GetRange(start, end int64) (io.ReadCloser, error) {
klog.Infof("Range request extends past end of image, trimming to %d", end)
}

request, err := http.NewRequest("GET", reader.transferURL, nil)
request, err := http.NewRequest(http.MethodGet, reader.transferURL, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to create range request")
}
Expand Down Expand Up @@ -562,7 +562,7 @@ func createImageioReader(ctx context.Context, ep string, accessKey string, secKe

var reader io.ReadCloser
if extentsFeature {
req, err := http.NewRequest("GET", transferURL+"/extents", nil)
req, err := http.NewRequest(http.MethodGet, transferURL+"/extents", nil)
if err != nil {
return nil, uint64(0), it, conn, err
}
Expand Down Expand Up @@ -598,7 +598,7 @@ func createImageioReader(ctx context.Context, ep string, accessKey string, secKe
size: int64(total),
}
} else {
req, err := http.NewRequest("GET", transferURL, nil)
req, err := http.NewRequest(http.MethodGet, transferURL, nil)
if err != nil {
return nil, uint64(0), it, conn, errors.Wrap(err, "Sending request failed")
}
Expand Down
8 changes: 4 additions & 4 deletions pkg/uploadproxy/uploadproxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func getHTTPClientConfig() *httpClientConfig {
}

func newProxyRequest(path, authHeaderValue string) *http.Request {
req, err := http.NewRequest("POST", path, strings.NewReader("data"))
req, err := http.NewRequest(http.MethodPost, path, strings.NewReader("data"))
Expect(err).ToNot(HaveOccurred())

if authHeaderValue != "" {
Expand All @@ -85,7 +85,7 @@ func newProxyRequest(path, authHeaderValue string) *http.Request {
}

func newProxyHeadRequest(authHeaderValue string) *http.Request {
req, err := http.NewRequest("HEAD", common.UploadPathSync, nil)
req, err := http.NewRequest(http.MethodHead, common.UploadPathSync, nil)
Expect(err).ToNot(HaveOccurred())

if authHeaderValue != "" {
Expand Down Expand Up @@ -245,7 +245,7 @@ var _ = Describe("submit request and check status", func() {
Entry("Malformed auth header: invalid prefix", "Beereer valid", http.StatusBadRequest),
)
It("Test healthz", func() {
req, err := http.NewRequest("GET", healthzPath, nil)
req, err := http.NewRequest(http.MethodGet, healthzPath, nil)
Expect(err).ToNot(HaveOccurred())
submitRequestAndCheckStatus(req, http.StatusOK, nil)
})
Expand All @@ -264,7 +264,7 @@ var _ = Describe("submit request and check status", func() {
)

It("Test healthz", func() {
req, err := http.NewRequest("GET", healthzPath, nil)
req, err := http.NewRequest(http.MethodGet, healthzPath, nil)
Expect(err).ToNot(HaveOccurred())
submitRequestAndCheckStatus(req, http.StatusOK, nil)
})
Expand Down
4 changes: 2 additions & 2 deletions pkg/uploadserver/uploadserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ func (app *uploadServerApp) healthzHandler(w http.ResponseWriter, r *http.Reques
}

func (app *uploadServerApp) validateShouldHandleRequest(w http.ResponseWriter, r *http.Request) bool {
if r.Method != "POST" {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusNotFound)
return false
}
Expand Down Expand Up @@ -323,7 +323,7 @@ func (app *uploadServerApp) validateShouldHandleRequest(w http.ResponseWriter, r

func (app *uploadServerApp) uploadHandlerAsync(irc imageReadCloser) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == "HEAD" {
if r.Method == http.MethodHead {
w.WriteHeader(http.StatusOK)
return
}
Expand Down
14 changes: 7 additions & 7 deletions pkg/uploadserver/uploadserver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ func replaceAsyncProcessorFunc(replacement func(io.ReadCloser, string, string, f
var _ = Describe("Upload server tests", func() {
It("GET fails", func() {
withProcessorSuccess(func() {
req, err := http.NewRequest("GET", common.UploadPathSync, nil)
req, err := http.NewRequest(http.MethodGet, common.UploadPathSync, nil)
Expect(err).ToNot(HaveOccurred())

rr := httptest.NewRecorder()
Expand All @@ -200,7 +200,7 @@ var _ = Describe("Upload server tests", func() {
})

It("healthz", func() {
req, err := http.NewRequest("GET", healthzPath, nil)
req, err := http.NewRequest(http.MethodGet, healthzPath, nil)
Expect(err).ToNot(HaveOccurred())

rr := httptest.NewRecorder()
Expand All @@ -216,7 +216,7 @@ var _ = Describe("Upload server tests", func() {

DescribeTable("Process unavailable", func(uploadPath string) {
withProcessorSuccess(func() {
req, err := http.NewRequest("POST", uploadPath, strings.NewReader("data"))
req, err := http.NewRequest(http.MethodPost, uploadPath, strings.NewReader("data"))
Expect(err).ToNot(HaveOccurred())

rr := httptest.NewRecorder()
Expand All @@ -238,7 +238,7 @@ var _ = Describe("Upload server tests", func() {

DescribeTable("Completion conflict", func(uploadPath string) {
withAsyncProcessorSuccess(func() {
req, err := http.NewRequest("POST", uploadPath, strings.NewReader("data"))
req, err := http.NewRequest(http.MethodPost, uploadPath, strings.NewReader("data"))
Expect(err).ToNot(HaveOccurred())

rr := httptest.NewRecorder()
Expand All @@ -260,7 +260,7 @@ var _ = Describe("Upload server tests", func() {

It("Success", func() {
withProcessorSuccess(func() {
req, err := http.NewRequest("POST", common.UploadPathSync, strings.NewReader("data"))
req, err := http.NewRequest(http.MethodPost, common.UploadPathSync, strings.NewReader("data"))
Expect(err).ToNot(HaveOccurred())

rr := httptest.NewRecorder()
Expand Down Expand Up @@ -309,7 +309,7 @@ var _ = Describe("Upload server tests", func() {

DescribeTable("Stream fail", func(processorFunc func(func()), uploadPath string) {
processorFunc(func() {
req, err := http.NewRequest("POST", uploadPath, strings.NewReader("data"))
req, err := http.NewRequest(http.MethodPost, uploadPath, strings.NewReader("data"))
Expect(err).ToNot(HaveOccurred())

rr := httptest.NewRecorder()
Expand Down Expand Up @@ -396,7 +396,7 @@ func newFormRequest(path string) *http.Request {
err = w.Close()
Expect(err).ToNot(HaveOccurred())

req, err := http.NewRequest("POST", path, &b)
req, err := http.NewRequest(http.MethodPost, path, &b)
Expect(err).ToNot(HaveOccurred())

req.Header.Set("Content-Type", w.FormDataContentType())
Expand Down
4 changes: 2 additions & 2 deletions tests/apiserver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ var _ = Describe("cdi-apiserver tests", Serial, func() {
}

Eventually(func() error {
req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequest(http.MethodGet, url, nil)
Expect(err).ToNot(HaveOccurred())

resp, err := client.Do(req)
Expand Down Expand Up @@ -130,7 +130,7 @@ var _ = Describe("cdi-apiserver tests", Serial, func() {
},
}
requestFunc := func() string {
req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return err.Error()
}
Expand Down
2 changes: 1 addition & 1 deletion tests/framework/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func (f *Framework) MakePrometheusHTTPRequest(endpoint string) *http.Response {
},
}
gomega.Eventually(func() bool {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/v1/%s", url, endpoint), nil)
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/%s", url, endpoint), nil)
if err != nil {
return false
}
Expand Down
6 changes: 3 additions & 3 deletions tests/upload_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -791,7 +791,7 @@ func formRequestFunc(url, fileName string) (*http.Request, error) {
pipeReader, pipeWriter := io.Pipe()
multipartWriter := multipart.NewWriter(pipeWriter)

req, err := http.NewRequest("POST", url, pipeReader)
req, err := http.NewRequest(http.MethodPost, url, pipeReader)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -830,7 +830,7 @@ func binaryRequestFunc(url, fileName string) (*http.Request, error) {
return nil, err
}

req, err := http.NewRequest("POST", url, f)
req, err := http.NewRequest(http.MethodPost, url, f)
if err != nil {
return nil, err
}
Expand All @@ -846,7 +846,7 @@ func testBadRequestFunc(url, fileName string) (*http.Request, error) {
return nil, err
}
lr := LimitThenErrorReader(f, 2048)
req, err := http.NewRequest("POST", url, lr)
req, err := http.NewRequest(http.MethodPost, url, lr)
if err != nil {
return nil, err
}
Expand Down
Loading

0 comments on commit dd518e7

Please sign in to comment.