github.com/haalcala/mattermost-server-change-repo@v0.0.0-20210713015153-16753fbeee5f/app/response_transfer.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package app
     5  
     6  import (
     7  	"bytes"
     8  	"fmt"
     9  	"io/ioutil"
    10  	"net/http"
    11  	"strconv"
    12  	"strings"
    13  )
    14  
    15  type PluginResponseWriter struct {
    16  	bytes.Buffer
    17  	headers    http.Header
    18  	statusCode int
    19  }
    20  
    21  func (rt *PluginResponseWriter) Header() http.Header {
    22  	if rt.headers == nil {
    23  		rt.headers = make(http.Header)
    24  	}
    25  	return rt.headers
    26  }
    27  
    28  func (rt *PluginResponseWriter) WriteHeader(statusCode int) {
    29  	rt.statusCode = statusCode
    30  }
    31  
    32  // From net/http/httptest/recorder.go
    33  func parseContentLength(cl string) int64 {
    34  	cl = strings.TrimSpace(cl)
    35  	if cl == "" {
    36  		return -1
    37  	}
    38  	n, err := strconv.ParseInt(cl, 10, 64)
    39  	if err != nil {
    40  		return -1
    41  	}
    42  	return n
    43  
    44  }
    45  
    46  func (rt *PluginResponseWriter) GenerateResponse() *http.Response {
    47  	res := &http.Response{
    48  		Proto:      "HTTP/1.1",
    49  		ProtoMajor: 1,
    50  		ProtoMinor: 1,
    51  		StatusCode: rt.statusCode,
    52  		Header:     rt.headers.Clone(),
    53  	}
    54  
    55  	if res.StatusCode == 0 {
    56  		res.StatusCode = http.StatusOK
    57  	}
    58  
    59  	res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode))
    60  
    61  	if rt.Len() > 0 {
    62  		res.Body = ioutil.NopCloser(rt)
    63  	} else {
    64  		res.Body = http.NoBody
    65  	}
    66  
    67  	res.ContentLength = parseContentLength(rt.headers.Get("Content-Length"))
    68  
    69  	return res
    70  }