本文整理汇总了Golang中net/http.Response.Write方法的典型用法代码示例。如果您正苦于以下问题:Golang Response.Write方法的具体用法?Golang Response.Write怎么用?Golang Response.Write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Response
的用法示例。
在下文中一共展示了Response.Write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: streamAndCache
// Code to stream the result in lock-step to the client and to a cache file.
// If conn terminates, continue streaming the response into the cache.
func streamAndCache(res *http.Response, conn net.Conn, cache_path string) int64 {
response_reader, cache_writer := io.Pipe()
defer func() {
err := cache_writer.Close()
if err != nil {
panic(err)
}
}()
n_recvd := make(chan int64)
go func() {
n_recvd <- CacheResponse(cache_path, response_reader)
}()
// Swallow write errors to `conn` since we want it to keep writing to the
// cache even if conn goes away
w := io.MultiWriter(cache_writer, writeErrorSwallower{conn})
err := res.Write(w)
if err != nil {
panic(err)
}
// Wait until CacheResponse is done copying the response to a file.
n := <-n_recvd
return n
}
示例2: DumpResponse
// DumpResponse is like DumpRequest but dumps a response.
func DumpResponse(resp *http.Response, body bool) (dump []byte, err error) {
var b bytes.Buffer
save := resp.Body
savecl := resp.ContentLength
if !body {
// For content length of zero. Make sure the body is an empty
// reader, instead of returning error through failureToReadBody{}.
if resp.ContentLength == 0 {
resp.Body = emptyBody
} else {
resp.Body = failureToReadBody{}
}
} else if resp.Body == nil {
resp.Body = emptyBody
} else {
save, resp.Body, err = drainBody(resp.Body)
if err != nil {
return nil, err
}
}
err = resp.Write(&b)
if err == errNoBody {
err = nil
}
resp.Body = save
resp.ContentLength = savecl
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
示例3: handlerWriteResponse
func (srv *Server) handlerWriteResponse(request *Request, res *http.Response, c net.Conn, bw *bufio.Writer) error {
// Setup write stage
request.startPipelineStage("server.ResponseWrite")
request.CurrentStage.Type = PipelineStageTypeOverhead
// cleanup
defer func() {
request.finishPipelineStage()
request.finishRequest()
srv.requestFinished(request, res)
if res.Body != nil {
res.Body.Close()
}
}()
// Cycle nodelay flag on socket
// Note: defers for FILO so this will happen before the write
// phase is complete, which is what we want.
if nodelay := srv.setNoDelay(c, false); nodelay {
defer srv.setNoDelay(c, true)
}
var err error
// Write response
if err = res.Write(bw); err != nil {
return err
}
// Flush any remaining buffer
err = bw.Flush()
return err
}
示例4: DumpResponse
// DumpResponse is like DumpRequest but dumps a response.
func DumpResponse(resp *http.Response, body bool) (dump []byte, err error) { // dump出响应内容
var b bytes.Buffer
save := resp.Body
savecl := resp.ContentLength
if !body {
resp.Body = failureToReadBody{}
} else if resp.Body == nil {
resp.Body = emptyBody
} else {
save, resp.Body, err = drainBody(resp.Body)
if err != nil {
return
}
}
err = resp.Write(&b)
if err == errNoBody {
err = nil
}
resp.Body = save
resp.ContentLength = savecl
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
示例5: putCache
// putCache puts the supplied http.Response into the cache.
func putCache(c *Context, req *http.Request, resp *http.Response) error {
defer resp.Body.Close()
filename := cacheEntryFilename(c, req.URL.String())
f, err := os.Create(filename)
if err != nil {
return err
}
if err := resp.Write(f); err != nil {
f.Close()
return err
}
f.Close()
if log.V(1) {
log.Infof("wrote %q to response cache", req.URL.String())
}
// TODO(spencer): this sucks, but we must re-read the response as
// the body is closed during the call to resp.Write().
if readResp, err := readCachedResponse(filename, req); err != nil {
log.Errorf("failed reading cached response: %s", err)
return err
} else {
resp.Body = readResp.Body
}
return nil
}
示例6: logResponse
func (c *Client) logResponse(resp *http.Response) error {
if c.logHTTP {
var err error
save := resp.Body
savecl := resp.ContentLength
body := true
if !body {
resp.Body = failureToReadBody{}
} else if resp.Body == nil {
resp.Body = emptyBody
} else {
save, resp.Body, err = drainBody(resp.Body)
if err != nil {
return err
}
}
fmt.Println("----------- response start -----------")
err = resp.Write(os.Stderr)
if err == errNoBody {
err = nil
}
resp.Body = save
resp.ContentLength = savecl
if err != nil {
return err
}
fmt.Println("----------- response end -----------")
}
return nil
}
示例7: handleRequest
// handleRequest runs the request and response modifiers and performs the roundtrip to the destination server.
func (p *Proxy) handleRequest(ctx *Context, rw *bufio.ReadWriter, req *http.Request) (closing bool) {
if err := proxyutil.FixBadFraming(req.Header); err != nil {
Errorf("proxyutil.FixBadFraming(): %v", err)
proxyutil.NewErrorResponse(400, err, req).Write(rw)
}
proxyutil.SetForwardedHeaders(req)
proxyutil.SetViaHeader(req.Header, "1.1 martian")
if err := p.ModifyRequest(ctx, req); err != nil {
Errorf("martian.ModifyRequest(): %v", err)
proxyutil.NewErrorResponse(400, err, req).Write(rw)
return
}
if shouldCloseAfterReply(req.Header) {
Debugf("closing after reply")
closing = true
}
proxyutil.RemoveHopByHopHeaders(req.Header)
var res *http.Response
var err error
if !ctx.SkipRoundTrip {
Debugf("proceed to round trip for %s", req.URL)
res, err = p.RoundTripper.RoundTrip(req)
if err != nil {
Errorf("RoundTripper.RoundTrip(%s): %v", req.URL, err)
proxyutil.NewErrorResponse(502, err, req).Write(rw)
return
}
} else {
Debugf("skipped round trip for %s", req.URL)
res = proxyutil.NewResponse(200, nil, req)
}
proxyutil.RemoveHopByHopHeaders(res.Header)
if err := p.ModifyResponse(ctx, res); err != nil {
Errorf("martian.ModifyResponse(): %v", err)
proxyutil.NewErrorResponse(400, err, req).Write(rw)
return
}
if closing {
res.Header.Set("Connection", "close")
res.Close = true
}
if err := res.Write(rw); err != nil {
Errorf("res.Write(): %v", err)
}
return
}
示例8: TestResponse
func TestResponse(t *testing.T) {
var resp http.Response
resp.StatusCode = http.StatusOK
resp.Header = make(http.Header)
resp.Header["SID"] = []string{"uuid:1337"}
var buf bytes.Buffer
resp.Write(&buf)
t.Logf("%q", buf.String())
}
示例9: handler
func (srv *Server) handler(c net.Conn) {
startTime := time.Now()
defer srv.connectionFinished(c)
bpe := srv.bufferPool.take(c)
defer srv.bufferPool.give(bpe)
var err error
var req *http.Request
// no keepalive (for now)
reqCount := 0
keepAlive := true
for err == nil && keepAlive {
if req, err = http.ReadRequest(bpe.br); err == nil {
if req.Header.Get("Connection") != "Keep-Alive" {
keepAlive = false
}
request := newRequest(req, c, startTime)
reqCount++
var res *http.Response
pssInit := new(PipelineStageStat)
pssInit.Name = "server.Init"
pssInit.StartTime = startTime
pssInit.EndTime = time.Now()
request.appendPipelineStage(pssInit)
// execute the pipeline
if res = srv.Pipeline.execute(request); res == nil {
res = SimpleResponse(req, 404, nil, "Not Found")
}
// cleanup
request.startPipelineStage("server.ResponseWrite")
req.Body.Close()
if srv.sendfile {
res.Write(c)
} else {
wbuf := bufio.NewWriter(c)
res.Write(wbuf)
wbuf.Flush()
}
if res.Body != nil {
res.Body.Close()
}
request.finishPipelineStage()
request.finishRequest()
srv.requestFinished(request)
} else {
// EOF is socket closed
if err != io.ErrUnexpectedEOF {
Error("%s %v ERROR reading request: %v", srv.serverLogPrefix(), c.RemoteAddr(), err)
}
}
}
//Debug("%s Processed %v requests on connection %v", srv.serverLogPrefix(), reqCount, c.RemoteAddr())
}
示例10: Write
// Write writes resp in response to req. To close the connection gracefully, set the
// Response.Close field to true. Write should be considered operational until
// it returns an error, regardless of any errors returned on the Read side.
func (sc *ServerConn) Write(req *http.Request, resp *http.Response) error {
// Retrieve the pipeline ID of this request/response pair
sc.lk.Lock()
id, ok := sc.pipereq[req]
delete(sc.pipereq, req)
if !ok {
sc.lk.Unlock()
return ErrPipeline
}
sc.lk.Unlock()
// Ensure pipeline order
sc.pipe.StartResponse(id)
defer sc.pipe.EndResponse(id)
sc.lk.Lock()
if sc.we != nil {
defer sc.lk.Unlock()
return sc.we
}
if sc.c == nil { // connection closed by user in the meantime
defer sc.lk.Unlock()
return os.EBADF
}
c := sc.c
if sc.nread <= sc.nwritten {
defer sc.lk.Unlock()
return errors.New("persist server pipe count")
}
if resp.Close {
// After signaling a keep-alive close, any pipelined unread
// requests will be lost. It is up to the user to drain them
// before signaling.
sc.re = ErrPersistEOF
}
sc.lk.Unlock()
err := resp.Write(c)
sc.lk.Lock()
defer sc.lk.Unlock()
if err != nil {
sc.we = err
return err
}
sc.nwritten++
return nil
}
示例11: CmdWatch
func (c *Cli) CmdWatch(issue string, watcher string, remove bool) error {
log.Debug("watch called: watcher: %q, remove: %n", watcher, remove)
var uri string
json, err := jsonEncode(watcher)
if err != nil {
return err
}
if c.getOptBool("dryrun", false) {
if !remove {
log.Debug("POST: %s", json)
log.Debug("Dryrun mode, skipping POST")
} else {
log.Debug("DELETE: %s", watcher)
log.Debug("Dryrun mode, skipping POST")
}
return nil
}
var resp *http.Response
if !remove {
uri = fmt.Sprintf("%s/rest/api/2/issue/%s/watchers", c.endpoint, issue)
resp, err = c.post(uri, json)
} else {
uri = fmt.Sprintf("%s/rest/api/2/issue/%s/watchers?username=%s", c.endpoint, issue, watcher)
resp, err = c.delete(uri)
}
if err != nil {
return err
}
if resp.StatusCode == 204 {
c.Browse(issue)
if !c.opts["quiet"].(bool) {
fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue)
}
} else {
logBuffer := bytes.NewBuffer(make([]byte, 0))
resp.Write(logBuffer)
if !remove {
err = fmt.Errorf("Unexpected Response From POST")
} else {
err = fmt.Errorf("Unexpected Response From DELETE")
}
log.Error("%s:\n%s", err, logBuffer)
return err
}
return nil
}
示例12: makeServe
func makeServe(connectionClose bool, processTime time.Duration, bodyLength int, slow *SlowReaderWriter) ConnectionHandler {
return func(t *testing.T, conn net.Conn) {
defer conn.Close()
var br *bufio.Reader = bufio.NewReader(conn)
var w io.Writer = conn
body := strings.Repeat("x", bodyLength)
if slow != nil {
slow.R = conn
slow.W = conn
br = bufio.NewReader(slow)
w = io.Writer(slow)
}
for i := 1; i < 10; i++ {
request, err := http.ReadRequest(br)
if err != nil {
t.Error("Read:", err.Error())
}
response := http.Response{
Status: "200 OK",
StatusCode: 200,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
// No RDelay, used only to provide Close method to strings.Reader.
Body: &SlowReaderWriter{R: strings.NewReader(body), Size: bodyLength},
ContentLength: int64(bodyLength),
Close: connectionClose,
Header: make(http.Header),
Request: request,
}
response.Header.Set("Content-Type", "text/plain")
response.Header.Set("Content-Length", fmt.Sprintf("%d", bodyLength))
// dw := bytes.NewBuffer(make([]byte, 100000))
// response.Write(dw)
// println("Write:", dw.String())
err = response.Write(w)
if err != nil {
t.Error("Write:", err.Error())
}
}
t.Fatal("Too many requests on one connection")
}
}
示例13: updateRateHandler
func updateRateHandler(w http.ResponseWriter, r *http.Request) {
if DEBUG_WEB_SERVER {
fmt.Println("GET AN UPDATE RATE REQUEST")
}
rateValueStr := r.FormValue("rate")
rateValue, err := strconv.ParseInt(rateValueStr, 0, 0)
var response http.Response
if err == nil && rateValue > 0 {
updateRate(int(rateValue))
if DEBUG_WEB_SERVER {
fmt.Println("Update lambda, new value =", rate)
}
response.StatusCode = 200
} else {
response.StatusCode = 400
}
response.Write(w)
}
示例14: CmdVote
func (c *Cli) CmdVote(issue string, up bool) error {
log.Debug("vote called, with up: %n", up)
uri := fmt.Sprintf("%s/rest/api/2/issue/%s/votes", c.endpoint, issue)
if c.getOptBool("dryrun", false) {
if up {
log.Debug("POST: %s", "")
log.Debug("Dryrun mode, skipping POST")
} else {
log.Debug("DELETE: %s", "")
log.Debug("Dryrun mode, skipping DELETE")
}
return nil
}
var resp *http.Response
var err error
if up {
resp, err = c.post(uri, "")
} else {
resp, err = c.delete(uri)
}
if err != nil {
return err
}
if resp.StatusCode == 204 {
c.Browse(issue)
if !c.opts["quiet"].(bool) {
fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue)
}
} else {
logBuffer := bytes.NewBuffer(make([]byte, 0))
resp.Write(logBuffer)
if up {
err = fmt.Errorf("Unexpected Response From POST")
} else {
err = fmt.Errorf("Unexpected Response From DELETE")
}
log.Error("%s:\n%s", err, logBuffer)
return err
}
return nil
}
示例15: handlerWriteResponse
func (srv *Server) handlerWriteResponse(request *Request, res *http.Response, c net.Conn, bw *bufio.Writer) {
request.startPipelineStage("server.ResponseWrite")
request.CurrentStage.Type = PipelineStageTypeOverhead
var nodelay = srv.setNoDelay(c, false)
if nodelay {
res.Write(bw)
bw.Flush()
srv.setNoDelay(c, true)
} else {
res.Write(bw)
bw.Flush()
}
if res.Body != nil {
res.Body.Close()
}
request.finishPipelineStage()
request.finishRequest()
srv.requestFinished(request, res)
}