Created
September 18, 2012 08:45
-
-
Save vmihailenco/3742087 to your computer and use it in GitHub Desktop.
httptest.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package httptest | |
import ( | |
"bytes" | |
"io" | |
"net/http" | |
"appengine" | |
) | |
type responseWriter struct { | |
Buf bytes.Buffer | |
StatusCode int | |
} | |
func newResponseWriter() *responseWriter { | |
return &responseWriter{ | |
StatusCode: 200, | |
} | |
} | |
func (w *responseWriter) Header() http.Header { | |
return make(http.Header) | |
} | |
func (w *responseWriter) Write(b []byte) (int, error) { | |
return w.Buf.Write(b) | |
} | |
func (w *responseWriter) WriteHeader(statusCode int) { | |
w.StatusCode = statusCode | |
} | |
func Post(c appengine.Context, urlStr string, bodyType string, body io.Reader) (*responseWriter, error) { | |
return do(c, "POST", urlStr, bodyType, body) | |
} | |
func Put(c appengine.Context, urlStr string, bodyType string, body io.Reader) (*responseWriter, error) { | |
return do(c, "PUT", urlStr, bodyType, body) | |
} | |
func Get(c appengine.Context, urlStr string) (*responseWriter, error) { | |
return do(c, "GET", urlStr, "", nil) | |
} | |
func do(c appengine.Context, method, urlStr string, bodyType string, body io.Reader) (*responseWriter, error) { | |
r, err := http.NewRequest(method, urlStr, body) | |
if err != nil { | |
return nil, err | |
} | |
if bodyType != "" { | |
r.Header.Set("Content-Type", bodyType) | |
} | |
return RoundTrip(c, r) | |
} | |
func RoundTrip(c appengine.Context, r *http.Request) (*responseWriter, error) { | |
r.Header.Set("X-AppEngine-Inbound-AppId", "dev~"+appengine.AppID(c)) | |
w := newResponseWriter() | |
http.DefaultServeMux.ServeHTTP(w, r) | |
return w, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment