github.com/coreos/goproxy@v0.0.0-20190513173959-f8dc2d7ba04e/responses.go (about) 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 buf := bytes.NewBufferString(body) 25 resp.ContentLength = int64(buf.Len()) 26 resp.Body = ioutil.NopCloser(buf) 27 return resp 28 } 29 30 const ( 31 ContentTypeText = "text/plain" 32 ContentTypeHtml = "text/html" 33 ) 34 35 // Alias for NewResponse(r,ContentTypeText,http.StatusAccepted,text) 36 func TextResponse(r *http.Request, text string) *http.Response { 37 return NewResponse(r, ContentTypeText, http.StatusAccepted, text) 38 }