aboutsummaryrefslogtreecommitdiffstats
path: root/modules/context/response.go
blob: 549bd30ee020d702370450fde2fc77a973ba8d9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright 2021 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package context

import "net/http"

// ResponseWriter represents a response writer for HTTP
type ResponseWriter interface {
	http.ResponseWriter
	Flush()
	Status() int
}

var (
	_ ResponseWriter = &Response{}
)

// Response represents a response
type Response struct {
	http.ResponseWriter
	status int
}

// Write writes bytes to HTTP endpoint
func (r *Response) Write(bs []byte) (int, error) {
	size, err := r.ResponseWriter.Write(bs)
	if err != nil {
		return 0, err
	}
	if r.status == 0 {
		r.WriteHeader(200)
	}
	return size, nil
}

// WriteHeader write status code
func (r *Response) WriteHeader(statusCode int) {
	r.status = statusCode
	r.ResponseWriter.WriteHeader(statusCode)
}

// Flush flush cached data
func (r *Response) Flush() {
	if f, ok := r.ResponseWriter.(http.Flusher); ok {
		f.Flush()
	}
}

// Status returned status code written
func (r *Response) Status() int {
	return r.status
}

// NewResponse creates a response
func NewResponse(resp http.ResponseWriter) *Response {
	if v, ok := resp.(*Response); ok {
		return v
	}
	return &Response{resp, 0}
}