2023-07-24 20:56:10 +00:00
|
|
|
package helpers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ContextKey string
|
|
|
|
|
|
|
|
const ResponseInfoKey ContextKey = "response_info"
|
|
|
|
|
|
|
|
type ResponseInfo struct {
|
|
|
|
ReturnCode int
|
|
|
|
ContentLength int
|
|
|
|
}
|
|
|
|
|
|
|
|
func HandleResponse(w http.ResponseWriter, r *http.Request, returncode int, content []byte, l *logrus.Logger) {
|
|
|
|
w.WriteHeader(returncode)
|
|
|
|
n, err := w.Write(content)
|
|
|
|
if err != nil {
|
|
|
|
l.Errorf("Failed to write content to response: %q", err.Error())
|
|
|
|
}
|
|
|
|
if n != len(content) {
|
|
|
|
l.Errorf("Failed to write the entire response (%d/%d)", n, len(content))
|
|
|
|
}
|
|
|
|
|
|
|
|
contextedReq := r.WithContext(context.WithValue(r.Context(), ResponseInfoKey, ResponseInfo{ReturnCode: returncode, ContentLength: len(content)}))
|
|
|
|
*r = *contextedReq
|
|
|
|
}
|
2023-08-16 21:33:26 +00:00
|
|
|
|
|
|
|
func AddToContext(r *http.Request, returncode, contentLength int) {
|
|
|
|
contextedReq := r.WithContext(context.WithValue(r.Context(), ResponseInfoKey, ResponseInfo{ReturnCode: returncode, ContentLength: contentLength}))
|
|
|
|
*r = *contextedReq
|
|
|
|
}
|