github.com/mhilton/juju-juju@v0.0.0-20150901100907-a94dd2c73455/apiserver/http/testing/response.go (about) 1 // Copyright 2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package testing 5 6 import ( 7 "bytes" 8 "encoding/json" 9 "fmt" 10 "io/ioutil" 11 "net/http" 12 13 apihttp "github.com/juju/juju/apiserver/http" 14 "github.com/juju/juju/apiserver/params" 15 ) 16 17 // HTTPResponse is an HTTP response for use in testing. 18 type HTTPResponse struct { 19 http.Response 20 // Buffer is the file underlying Body. 21 Buffer bytes.Buffer 22 } 23 24 // NewHTTPResponse returns an HTTP response with an OK status, 25 // no headers set, and an empty body. 26 func NewHTTPResponse() *HTTPResponse { 27 resp := HTTPResponse{ 28 Response: http.Response{ 29 StatusCode: http.StatusOK, 30 Header: make(http.Header), 31 }, 32 } 33 resp.Body = ioutil.NopCloser(&resp.Buffer) 34 return &resp 35 } 36 37 // NewErrorResponse returns an HTTP response with the status and 38 // body set to the provided values. 39 func NewErrorResponse(statusCode int, msg string) *HTTPResponse { 40 resp := NewHTTPResponse() 41 resp.StatusCode = statusCode 42 if _, err := resp.Buffer.WriteString(msg); err != nil { 43 panic(fmt.Sprintf("could not write to buffer: %v", err)) 44 } 45 return resp 46 } 47 48 // NewFailureResponse returns an HTTP response with the status set 49 // to 500 (Internal Server Error) and the body set to the JSON-encoded 50 // error. 51 func NewFailureResponse(failure *params.Error) *HTTPResponse { 52 resp := NewHTTPResponse() 53 resp.StatusCode = http.StatusInternalServerError 54 resp.Header.Set("Content-Type", apihttp.CTypeJSON) 55 if err := json.NewEncoder(&resp.Buffer).Encode(failure); err != nil { 56 panic(fmt.Sprintf("could not JSON-encode failure: %v", err)) 57 } 58 return resp 59 }