本文整理汇总了Golang中net/http.Response.Status方法的典型用法代码示例。如果您正苦于以下问题:Golang Response.Status方法的具体用法?Golang Response.Status怎么用?Golang Response.Status使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Response
的用法示例。
在下文中一共展示了Response.Status方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Fetch
// FileFetcher's Fetch() implementation
func (this *fileFetcherExtender) Fetch(u *url.URL, userAgent string, headRequest bool) (*http.Response, error) {
var res *http.Response = new(http.Response)
var req *http.Request
var e error
if req, e = http.NewRequest("GET", u.String(), nil); e != nil {
panic(e)
}
// Prepare the pseudo-request
req.Header.Add("User-Agent", userAgent)
// Open the file specified as path in u, relative to testdata/[host]/
f, e := os.Open(path.Join(FileFetcherBasePath, u.Host, u.Path))
if e != nil {
// Treat errors as 404s - file not found
res.Status = "404 Not Found"
res.StatusCode = 404
} else {
res.Status = "200 OK"
res.StatusCode = 200
res.Body = f
}
res.Request = req
return res, e
}
示例2: Restore
func (c *URLCache) Restore(res *http.Response) {
res.Status = c.CachedResponse.Status
res.StatusCode = c.CachedResponse.StatusCode
res.Header = c.CachedResponse.Header
res.ContentLength = c.CachedResponse.ContentLength
res.TransferEncoding = c.CachedResponse.TransferEncoding
res.Body = &ClosableBuffer{bytes.NewReader(c.CachedBody)}
res.Header.Set(CachedHeader, CachedHeaderVal)
res.Header.Set(CachedMD5Header, c.MD5)
}
示例3: ModifyResponse
// ModifyResponse sets the status code to 400 Bad Request if a loop was
// detected in the request.
func (m *viaModifier) ModifyResponse(res *http.Response) error {
ctx := martian.NewContext(res.Request)
if err, _ := ctx.Get(viaLoopKey); err != nil {
res.StatusCode = 400
res.Status = http.StatusText(400)
return err.(error)
}
return nil
}
示例4: ModifyResponse
// ModifyResponse runs resmod.ModifyResponse.
//
// If an error is returned from resmod.ModifyResponse it is returned.
func (m *Modifier) ModifyResponse(res *http.Response) error {
ctx := martian.NewContext(res.Request)
actx := auth.FromContext(ctx)
err := m.resmod.ModifyResponse(res)
if actx.Error() != nil {
res.StatusCode = 403
res.Status = http.StatusText(403)
}
return err
}
示例5: FilterResponse
func (f *EtagFilter) FilterResponse(request *falcore.Request, res *http.Response) {
request.CurrentStage.Status = 1 // Skipped (default)
if if_none_match := request.HttpRequest.Header.Get("If-None-Match"); if_none_match != "" {
if res.StatusCode == 200 && res.Header.Get("Etag") == if_none_match {
res.StatusCode = 304
res.Status = "304 Not Modified"
res.Body.Close()
res.Body = nil
res.ContentLength = 0
request.CurrentStage.Status = 0 // Success
}
}
}
示例6: ToResponse
func (res *HTTPResponseEvent) ToResponse(body bool) *http.Response {
raw := new(http.Response)
raw.Header = res.Headers
raw.ProtoMajor = 1
raw.ProtoMinor = 1
raw.StatusCode = int(res.StatusCode)
raw.Status = http.StatusText(raw.StatusCode)
raw.TransferEncoding = res.Headers["TransferEncoding"]
if body {
raw.Body = NewHTTPBody(res.GetContentLength(), res.Content)
}
return raw
}
示例7: NewNotification
// NewNotification returns a notification response with a specific body content.
func NewNotification(body *bytes.Buffer) *http.Response {
resp := new(http.Response)
resp.Status = "200 OK"
resp.StatusCode = http.StatusOK
resp.ProtoMajor = 1
resp.ProtoMinor = 0
resp.Body = ioutil.NopCloser(body)
resp.ContentLength = int64(body.Len())
resp.Header = map[string][]string{}
resp.Header.Set("Content-Type", HTTPContentTypeHAPJson)
// Will be ignored unfortunately and won't be fixed https://github.com/golang/go/issues/9304
// Make sure to call FixProtocolSpecifier() instead
resp.Proto = "EVENT/1.0"
return resp
}
示例8: Response
func (r *response) Response() *http.Response {
if r.Data == nil {
r.Data = new(bytes.Buffer)
}
out := new(http.Response)
out.Status = fmt.Sprintf("%d %s", r.StatusCode, http.StatusText(r.StatusCode))
out.StatusCode = r.StatusCode
out.Proto = "HTTP/1.1"
out.ProtoMajor = 1
out.ProtoMinor = 1
out.Header = r.Header
out.Body = &readCloser{r.Data}
out.ContentLength = int64(r.Data.Len())
out.TransferEncoding = nil
out.Close = true
out.Trailer = make(http.Header)
out.Request = r.Request
return out
}
示例9: ServeHTTP
func (p proxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r.Body.Close()
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
log.Println("Failed to hijack connection in ProxyConnections.", err)
return
}
defer conn.Close()
if _, ok := conn.(*tls.Conn); !ok {
log.Println("Recieved a non-TLS connection in ProxyConnections.")
return
}
// Send the connection accepted response.
res := new(http.Response)
res.Status = "200 Connection Established"
res.StatusCode = http.StatusOK
res.Proto = "HTTP/1.1"
res.ProtoMajor = 1
res.ProtoMinor = 1
if err = res.Write(conn); err != nil {
log.Println("Failed to send connection established message in ProxyConnections.", err)
return
}
client, err := NewClientConn(conn, nil, 3, 1)
if err != nil {
log.Println("Error creating SPDY connection in ProxyConnections.", err)
return
}
go client.Run()
// Call user code.
p.ProxyConnHandle(client)
client.Close()
}
示例10: resUnmarshal
func resUnmarshal(p []byte) (string, *http.Response, error) {
var handle string
var res *http.Response
unzipped, err := unzip(p)
if err != nil {
return handle, res, err.(*Error).escalate(errResUnmarshal)
}
in := new(response)
in.Header = http.Header(make(map[string][]string))
if err = json.Unmarshal(unzipped, in); err != nil {
return handle, res, newError(errResUnmarshalJSON, err.Error())
}
handle = in.Handle
res = new(http.Response)
res.Body = &body{bytes.NewBuffer(in.Body)}
res.ContentLength = int64(len(in.Body))
res.Header = in.Header
res.StatusCode = in.Code
res.Status = http.StatusText(in.Code)
return handle, res, nil
}
示例11: Response
func (r *Response) Response() *http.Response {
out := new(http.Response)
r.headerM.Lock()
out.Status = fmt.Sprintf("%d %s", r.StatusCode, http.StatusText(r.StatusCode))
out.StatusCode = r.StatusCode
out.Header = r.Header
r.headerM.Unlock()
out.Proto = "HTTP/1.1"
out.ProtoMajor = 1
out.ProtoMinor = 1
r.dataM.Lock()
if r.data == nil {
out.Body = &ReadCloser{new(bytes.Buffer)}
} else if unrequestedGzip(r) {
// User-agents MUST support gzip compression.
// Regardless of the Accept-Encoding sent by the user-agent, the server may
// always send content encoded with gzip or deflate encoding.
r.data.Prep()
out.Header.Del("Content-Encoding")
out.Header.Del("Content-Length")
out.ContentLength = -1
out.Body = &gzipReader{body: r.data}
} else {
r.data.Prep()
out.Body = r.data
out.ContentLength = r.data.written
}
r.dataM.Unlock()
out.TransferEncoding = nil
out.Close = true
out.Trailer = make(http.Header)
out.Request = r.Request
return out
}
示例12: New
// New returns an event response for a characteristic from an accessory.
func New(a *accessory.Accessory, c *characteristic.Characteristic) (*http.Response, error) {
body, err := Body(a, c)
if err != nil {
return nil, err
}
resp := new(http.Response)
resp.Status = "200 OK"
resp.StatusCode = http.StatusOK
resp.ProtoMajor = 1
resp.ProtoMinor = 0
resp.Body = ioutil.NopCloser(body)
resp.ContentLength = int64(body.Len())
resp.Header = map[string][]string{}
resp.Header.Set("Content-Type", netio.HTTPContentTypeHAPJson)
// (brutella) Not sure if Date header must be set
// resp.Header.Set("Date", netio.CurrentRFC1123Date())
// Will be ignored unfortunately and won't be fixed https://github.com/golang/go/issues/9304
// Make sure to call FixProtocolSpecifier() instead
resp.Proto = "EVENT/1.0"
return resp, nil
}
示例13: RoundTrip
// RoundTrip takes a Request and returns a Response
//
// If there is a fresh Response already in cache, then it will be returned without connecting to
// the server.
//
// If there is a stale Response, then any validators it contains will be set on the new request
// to give the server a chance to respond with NotModified. If this happens, then the cached Response
// will be returned.
func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
cacheKey := cacheKey(req)
cacheableMethod := req.Method == "GET" || req.Method == "HEAD"
var cachedResp *http.Response
if cacheableMethod {
cachedResp, err = CachedResponse(t.Cache, req)
} else {
// Need to invalidate an existing value
t.Cache.Delete(cacheKey)
}
transport := t.Transport
if transport == nil {
transport = http.DefaultTransport
}
if cachedResp != nil && err == nil && cacheableMethod && req.Header.Get("range") == "" {
if t.MarkCachedResponses {
cachedResp.Header.Set(XFromCache, "1")
}
if varyMatches(cachedResp, req) {
// Can only use cached value if the new request doesn't Vary significantly
freshness := getFreshness(cachedResp.Header, req.Header)
if freshness == fresh {
return cachedResp, nil
}
if freshness == stale {
var req2 *http.Request
// Add validators if caller hasn't already done so
etag := cachedResp.Header.Get("etag")
if etag != "" && req.Header.Get("etag") == "" {
req2 = cloneRequest(req)
req2.Header.Set("if-none-match", etag)
}
lastModified := cachedResp.Header.Get("last-modified")
if lastModified != "" && req.Header.Get("last-modified") == "" {
if req2 == nil {
req2 = cloneRequest(req)
}
req2.Header.Set("if-modified-since", lastModified)
}
if req2 != nil {
// Associate original request with cloned request so we can refer to
// it in CancelRequest()
t.setModReq(req, req2)
req = req2
defer func() {
// Release req/clone mapping on error
if err != nil {
t.setModReq(req, nil)
}
if resp != nil {
// Release req/clone mapping on body close/EOF
resp.Body = &onEOFReader{
rc: resp.Body,
fn: func() { t.setModReq(req, nil) },
}
}
}()
}
}
}
resp, err = transport.RoundTrip(req)
if err == nil && req.Method == "GET" && resp.StatusCode == http.StatusNotModified {
// Replace the 304 response with the one from cache, but update with some new headers
endToEndHeaders := getEndToEndHeaders(resp.Header)
for _, header := range endToEndHeaders {
cachedResp.Header[header] = resp.Header[header]
}
cachedResp.Status = fmt.Sprintf("%d %s", http.StatusOK, http.StatusText(http.StatusOK))
cachedResp.StatusCode = http.StatusOK
resp = cachedResp
} else if (err != nil || (cachedResp != nil && resp.StatusCode >= 500)) &&
req.Method == "GET" && canStaleOnError(cachedResp.Header, req.Header) {
// In case of transport failure and stale-if-error activated, returns cached content
// when available
cachedResp.Status = fmt.Sprintf("%d %s", http.StatusOK, http.StatusText(http.StatusOK))
cachedResp.StatusCode = http.StatusOK
return cachedResp, nil
} else {
if err != nil || resp.StatusCode != http.StatusOK {
t.Cache.Delete(cacheKey)
}
if err != nil {
if t.ResponseErrorFunc != nil {
return t.ResponseErrorFunc(resp, err, req)
}
return nil, err
//.........这里部分代码省略.........
示例14: ModifyResponse
// ModifyResponse overwrites the status text and code on an HTTP response and
// returns nil.
func (s *statusModifier) ModifyResponse(res *http.Response) error {
res.StatusCode = s.statusCode
res.Status = http.StatusText(s.statusCode)
return nil
}
示例15: largefetch
func (c *conn) largefetch(w *bufio.Writer, r *http.Request, first *http.Response) error {
pos := 0
length := 0
step := 100000
log.Printf("largefetch begin: %s", r.URL.Path)
var err error
if first == nil {
first, _, pos, length, err = c.rangeRoundTrip(r, 0, 1000000)
if err != nil {
r.Body.Close()
return fmt.Errorf("conn.largefetch(first roundtrip)>%s", err)
}
defer first.Body.Close()
} else {
contentRange := first.Header.Get("Content-Range")
if contentRange == "" {
r.Body.Close()
return errors.New("conn.largefetch: empty content range")
}
m := rangeresp.FindStringSubmatch(contentRange)
if len(m) != 4 {
r.Body.Close()
return errors.New("conn.largefetch: invalid content range")
}
pos, err = strconv.Atoi(m[2])
if err != nil {
r.Body.Close()
return fmt.Errorf("conn.largefetch(convert pos)>%s", err)
}
length, err = strconv.Atoi(m[3])
if err != nil {
r.Body.Close()
return fmt.Errorf("conn.largefetch(convert length)>%s", err)
}
}
first.Header.Del("Content-Range")
//first.ContentLength = int64(end - start + 1)
first.Header.Set("Content-Length", strconv.Itoa(length))
first.StatusCode = 200
first.Status = http.StatusText(200)
err = writeResponse(w, first)
if err != nil {
return fmt.Errorf("conn.largefetch>%s", err)
}
err = w.Flush()
if err != nil {
return fmt.Errorf("conn.largefetch(w.Flush)>%s", err)
}
if length-pos-1 == 0 {
return nil
}
var seq sequencer
task := make(chan int)
errChan := make(chan error)
for i := 0; i < 30; i++ {
go func() {
defer print("end--------")
for n := range task {
start_in := pos + 1 + step*n
end_in := pos + step*(n+1)
if end_in > length-1 {
end_in = length - 1
}
var start_out, end_out int
var resp *http.Response
var err error
for i := 0; i < 3; i++ {
resp, start_out, end_out, _, err = c.rangeRoundTrip(r, start_in, end_in)
if err == nil {
break
}
}
if err != nil {
errChan <- fmt.Errorf("conn.largefetch.routine>%s", err)
seq.Close()
return
}
if start_out != start_in || end_out != end_in {
errChan <- errors.New("conn.largefetch.routine: error range returned")
}
ok := seq.Start(uint(n))
if !ok { // seq closed
return
}
_, err = io.Copy(w, resp.Body)
resp.Body.Close()
if err != nil {
errChan <- fmt.Errorf("conn.largefetch.routine(send conts body)>%s", err)
seq.Close()
return
}
err = w.Flush()
if err != nil {
errChan <- fmt.Errorf("conn.largefetch.routine(conts flush)>%s", err)
seq.Close()
return
}
seq.End(uint(n))
errChan <- nil
}
//.........这里部分代码省略.........