responses.go 1.3 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. resp.Status = http.StatusText(status)
  23. buf := bytes.NewBufferString(body)
  24. resp.ContentLength = int64(buf.Len())
  25. resp.Body = ioutil.NopCloser(buf)
  26. return resp
  27. }
  28. const (
  29. ContentTypeText = "text/plain"
  30. ContentTypeHtml = "text/html"
  31. )
  32. // Alias for NewResponse(r,ContentTypeText,http.StatusAccepted,text)
  33. func TextResponse(r *http.Request, text string) *http.Response {
  34. return NewResponse(r, ContentTypeText, http.StatusAccepted, text)
  35. }