responses.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package goproxy
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "net/http"
  6. )
  7. // Will generate a valid http response to the given request the response will have
  8. // the given contentType, and http status.
  9. // Typical usage, refuse to process requests to local addresses:
  10. //
  11. // proxy.OnRequest(IsLocalHost()).DoFunc(func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request,*http.Response) {
  12. // return nil,NewResponse(r,goproxy.ContentTypeHtml,http.StatusUnauthorized,
  13. // `<!doctype html><html><head><title>Can't use proxy for local addresses</title></head><body/></html>`)
  14. // })
  15. func NewResponse(r *http.Request, contentType string, status int, body string) *http.Response {
  16. resp := &http.Response{}
  17. resp.Request = r
  18. resp.TransferEncoding = r.TransferEncoding
  19. resp.Header = make(http.Header)
  20. resp.Header.Add("Content-Type", contentType)
  21. resp.StatusCode = status
  22. buf := bytes.NewBufferString(body)
  23. resp.ContentLength = int64(buf.Len())
  24. resp.Body = ioutil.NopCloser(buf)
  25. return resp
  26. }
  27. const (
  28. ContentTypeText = "text/plain"
  29. ContentTypeHtml = "text/html"
  30. )
  31. // Alias for NewResponse(r,ContentTypeText,http.StatusAccepted,text)
  32. func TextResponse(r *http.Request, text string) *http.Response {
  33. return NewResponse(r, ContentTypeText, http.StatusAccepted, text)
  34. }