0
0

はじめに

goでプログラミングした際に、文法間違いやエラーチェックが抜けている箇所を指摘してくれるgolangci-lintを使ってみます。

golangci-lint インストール

brew install golangci-lint
brew upgrade golangci-lint

Goを書く

package main

import (
	"net/http"
)

func middleware1(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("before middleware\n"))
		next.ServeHTTP(w, r)
	})
}

func middleware2(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		next.ServeHTTP(w, r)
		w.Write([]byte("after middleware\n"))
	})
}

func main() {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello World\n"))
	})

	http.Handle("/", middleware1(middleware2(handler)))

	http.ListenAndServe(":8080", nil)
}

golangci-lintを実行する

メソッドがerrorを返してくるけど、実際にエラーチェックしてない箇所を指摘してくれています。

golangci-lint run main.go 

main.go:9:10: Error return value of `w.Write` is not checked (errcheck)
                w.Write([]byte("before middleware\n"))
                       ^
main.go:17:10: Error return value of `w.Write` is not checked (errcheck)
                w.Write([]byte("after middleware\n"))
                       ^
main.go:23:10: Error return value of `w.Write` is not checked (errcheck)
                w.Write([]byte("Hello World\n"))
                       ^
main.go:28:21: Error return value of `http.ListenAndServe` is not checked (errcheck)
        http.ListenAndServe(":8080", nil)

プログラムを修正

package main

import (
	"net/http"
)

func middleware1(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, err := w.Write([]byte("before middleware\n"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		next.ServeHTTP(w, r)
	})
}

func middleware2(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		next.ServeHTTP(w, r)
		_, err := w.Write([]byte("after middleware\n"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	})
}

func main() {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, err := w.Write([]byte("Hello World\n"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	})

	http.Handle("/", middleware1(middleware2(handler)))

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic(err)
	}
}

再度golangci-lintを実行

何も指摘がないので、OKそう。

golangci-lint run main.go

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0