2023-10-14 16:06:02 +00:00
|
|
|
package helpers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
|
|
|
|
2024-08-15 16:25:15 +00:00
|
|
|
"go.uber.org/zap"
|
2023-10-14 16:06:02 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type ContextKey string
|
|
|
|
|
|
|
|
const ResponseInfoKey ContextKey = "response_info"
|
|
|
|
|
|
|
|
type ResponseInfo struct {
|
|
|
|
ReturnCode int
|
|
|
|
ContentLength int
|
|
|
|
}
|
|
|
|
|
2024-08-15 16:25:15 +00:00
|
|
|
func HandleResponse(w http.ResponseWriter, r *http.Request, returncode int, content []byte, l *zap.SugaredLogger) {
|
2023-10-14 16:06:02 +00:00
|
|
|
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
|
|
|
|
}
|