polycule-connect/polyculeconnect/helpers/helpers.go

32 lines
746 B
Go
Raw Permalink Normal View History

2023-10-14 16:06:02 +00:00
package helpers
import (
"context"
"net/http"
"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
}
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
}