Debian Codegraph @

responses.go

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