net/http
基本
code:go
type Handler intterface {
ServeHTTP(ResponseWriter, *Request)
}
//Handleの第二引数であるHandlerはServeHTTP(ResponseWriter, *Request)を実装することで
//レシーバーにHandlerを付与することが出来るハンドル
func Handle(pattern string, handler Handler)
//第二引数に関数型を渡すことが出来るハンドル
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
//Serverを起動する
func ListenAndServe(addr string, handler Handler) error
共通処理
Content-Type: application/jsonはJSONタイプのデータしか受け取らないという制限をつける
code: respond.go
func Respond(w http.ResponseWriter, data mapstring interface{}) {
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(data)
}
parameter
code:request.go
func Request(w http.ResponseWriter, r *http.Reaquest) {
b, _ := ioutil.ReadAll(r.Body)
defer r.Body.Close()
var params mapstringinterface{}
_ = json.Unmarshal(b, &params)
fmt.Println(params) // Post request parameter
}
net/http/test
code:http_test.go
var client = new(http.Client)
func TestHTTP(t *testing.T){
s := NewServer()
s.Router()
//テストサーバーを構築
testServer := httptest.NewServer(s.service)
defer testServer.Close()
//testServerのportとテストしたいパスを合わせる
path := testServer.URL + tt.args.path
req, _ := http.NewRequest(tt.args.req, path, nil)
//リクエストをテストサーバーに送るとレスポンスが返ってくる
resp, _ := client.Do(req)
respBody, _ := ioutil.ReadAll(resp.Body)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, tt.want, string(respBody))
}