emahiro/b.log

Drastically Repeat Yourself !!!!

go で簡易HTTPサーバー立てる

http.HandlerFuncを使う場合

package main

import (
  "fmt"
  "net/http"
)

func main () {
  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
    w.Writer([]bytes(`表示内容`))
  }
}

if err := http.ListenAndServe(":8080", nil); err ! = nil{
  fmt.Printf("エラー表示")
}

http.Handleを使う

package main

import (
  "fmt"
  "net/http"
)

type AppHandler struct{
  appName string
}

func (h *AppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  fmt.Printf(h.appName)
}

func main () {
  http.Handler("/", &AppHandler{appName: "myApp"})
  if err := http.ListenAndSerce(":8080", nil); err ! = nil {
    fmt.Printf("エラー発生")
  }
}

Linterのエラーが発生する

exported type AppHandler should have comment or be unexported (golint)  というエラーが発生。これはキャメルケースの構造体(外部からアクセス可能)なのにコメントが無いよっていうエラー

// AppHandler
type AppHandler struct{
  appName string
}

とコメントをつける

comment on exported type AppHandler should be of the form "AppHandler ..." (with optional leading article) (golint) というLinterのエラーがまだ発生。これはコメントの形式の警告。 構造体名 (半角スペース) 説明 みたいな書き方が必要になる。

// AppHandler アプリケーションに関わる〜
type AppHandler struct{
  appName string
}

というコメントに説明箇所を半角スペースで追加する。