// TODO: Check the pattern here. I suspect that cloudEvent.CopyToAsync(response) would be more natural. /// <summary> /// Copies the CloudEvent into this HttpListenerResponse instance /// </summary> /// <param name="httpListenerResponse">this</param> /// <param name="cloudEvent">CloudEvent to copy</param> /// <param name="contentMode">Content mode (structured or binary)</param> /// <param name="formatter">Formatter</param> /// <returns>Task</returns> public static Task CopyFromAsync(this HttpListenerResponse httpListenerResponse, CloudEvent cloudEvent, ContentMode contentMode, ICloudEventFormatter formatter) { if (contentMode == ContentMode.Structured) { var buffer = formatter.EncodeStructuredEvent(cloudEvent, out var contentType); httpListenerResponse.ContentType = contentType.ToString(); MapAttributesToListenerResponse(cloudEvent, httpListenerResponse); return(httpListenerResponse.OutputStream.WriteAsync(buffer, 0, buffer.Length)); } Stream stream = HttpUtilities.MapDataAttributeToStream(cloudEvent, formatter); // TODO: Check the defaulting to JSON here... httpListenerResponse.ContentType = cloudEvent.DataContentType?.ToString() ?? "application/json"; MapAttributesToListenerResponse(cloudEvent, httpListenerResponse); return(stream.CopyToAsync(httpListenerResponse.OutputStream)); }
// TODO: HttpWebResponse as well? // TODO: Change to a CopyTo extension method on CloudEvent? /// <summary> /// Copies a CloudEvent into the specified HttpWebRequest instance. /// </summary> /// <param name="httpWebRequest">The request to populate.</param> /// <param name="cloudEvent">CloudEvent to copy</param> /// <param name="contentMode">Content mode (structured or binary)</param> /// <param name="formatter">Formatter</param> /// <returns>Task</returns> public static async Task CopyFromAsync(this HttpWebRequest httpWebRequest, CloudEvent cloudEvent, ContentMode contentMode, ICloudEventFormatter formatter) { if (contentMode == ContentMode.Structured) { var buffer = formatter.EncodeStructuredEvent(cloudEvent, out var contentType); httpWebRequest.ContentType = contentType.ToString(); await httpWebRequest.GetRequestStream().WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false); return; } Stream stream = HttpUtilities.MapDataAttributeToStream(cloudEvent, formatter); httpWebRequest.ContentType = cloudEvent.DataContentType?.ToString() ?? "application/json"; MapAttributesToWebRequest(cloudEvent, httpWebRequest); await stream.CopyToAsync(httpWebRequest.GetRequestStream()); }