elif-http 0.8.8

HTTP server core for the elif.rs LLM-friendly web framework
Documentation
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
//! # Content Negotiation Middleware
//!
//! Provides HTTP content negotiation based on Accept headers.
//! Automatically handles response format conversion between JSON, XML, and other formats.

use crate::middleware::v2::{Middleware, Next, NextFuture};
use crate::request::ElifRequest;
use crate::response::headers::ElifHeaderValue;
use crate::response::ElifResponse;
use std::collections::HashMap;

/// Supported content types for negotiation
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ContentType {
    Json,
    Xml,
    Html,
    PlainText,
    Csv,
    MessagePack,
    Yaml,
    Custom(String),
}

impl ContentType {
    /// Parse content type from Accept header value
    pub fn from_mime_type(mime_type: &str) -> Option<Self> {
        let mime_lower = mime_type.split(';').next()?.trim().to_lowercase();
        match mime_lower.as_str() {
            "application/json" => Some(Self::Json),
            "application/xml" | "text/xml" => Some(Self::Xml),
            "text/html" => Some(Self::Html),
            "text/plain" => Some(Self::PlainText),
            "text/csv" => Some(Self::Csv),
            "application/msgpack" | "application/x-msgpack" => Some(Self::MessagePack),
            "application/yaml" | "application/x-yaml" | "text/yaml" => Some(Self::Yaml),
            _ => Some(Self::Custom(mime_lower)),
        }
    }

    /// Get MIME type string for response headers
    pub fn to_mime_type(&self) -> &'static str {
        match self {
            Self::Json => "application/json",
            Self::Xml => "application/xml",
            Self::Html => "text/html",
            Self::PlainText => "text/plain",
            Self::Csv => "text/csv",
            Self::MessagePack => "application/msgpack",
            Self::Yaml => "application/yaml",
            Self::Custom(_) => "application/octet-stream", // Fallback for custom types
        }
    }

    /// Get file extension for this content type
    pub fn file_extension(&self) -> &'static str {
        match self {
            Self::Json => "json",
            Self::Xml => "xml",
            Self::Html => "html",
            Self::PlainText => "txt",
            Self::Csv => "csv",
            Self::MessagePack => "msgpack",
            Self::Yaml => "yaml",
            Self::Custom(_) => "bin",
        }
    }
}

/// Accept header value with quality factor
#[derive(Debug, Clone)]
pub struct AcceptValue {
    pub content_type: ContentType,
    pub quality: f32,
    pub params: HashMap<String, String>,
}

impl AcceptValue {
    /// Parse Accept header value (e.g., "application/json;q=0.8")
    pub fn parse(value: &str) -> Option<Self> {
        let parts: Vec<&str> = value.split(';').collect();
        let mime_type = parts.first()?.trim();

        let content_type = ContentType::from_mime_type(mime_type)?;
        let mut quality = 1.0;
        let mut params = HashMap::new();

        // Parse parameters
        for param in parts.iter().skip(1) {
            let param = param.trim();
            if let Some((key, val)) = param.split_once('=') {
                let key = key.trim();
                let val = val.trim();

                if key == "q" {
                    quality = val.parse().unwrap_or(1.0);
                } else {
                    params.insert(key.to_string(), val.to_string());
                }
            }
        }

        Some(Self {
            content_type,
            quality,
            params,
        })
    }
}

/// Content negotiation configuration
pub struct ContentNegotiationConfig {
    /// Default content type when negotiation fails
    pub default_content_type: ContentType,
    /// Supported content types in order of preference
    pub supported_types: Vec<ContentType>,
    /// Whether to add Vary header
    pub add_vary_header: bool,
    /// Custom converters for content types
    pub converters: HashMap<
        ContentType,
        std::sync::Arc<dyn Fn(&serde_json::Value) -> Result<Vec<u8>, String> + Send + Sync>,
    >,
}

impl Default for ContentNegotiationConfig {
    fn default() -> Self {
        let mut converters = HashMap::new();
        converters.insert(
            ContentType::Json,
            std::sync::Arc::new(Self::convert_to_json)
                as std::sync::Arc<
                    dyn Fn(&serde_json::Value) -> Result<Vec<u8>, String> + Send + Sync,
                >,
        );
        converters.insert(
            ContentType::PlainText,
            std::sync::Arc::new(Self::convert_to_text)
                as std::sync::Arc<
                    dyn Fn(&serde_json::Value) -> Result<Vec<u8>, String> + Send + Sync,
                >,
        );
        converters.insert(
            ContentType::Html,
            std::sync::Arc::new(Self::convert_to_html)
                as std::sync::Arc<
                    dyn Fn(&serde_json::Value) -> Result<Vec<u8>, String> + Send + Sync,
                >,
        );

        Self {
            default_content_type: ContentType::Json,
            supported_types: vec![
                ContentType::Json,
                ContentType::PlainText,
                ContentType::Html,
                ContentType::Xml,
            ],
            add_vary_header: true,
            converters,
        }
    }
}

impl ContentNegotiationConfig {
    /// Default JSON converter
    fn convert_to_json(value: &serde_json::Value) -> Result<Vec<u8>, String> {
        serde_json::to_vec_pretty(value).map_err(|e| e.to_string())
    }

    /// Default plain text converter
    fn convert_to_text(value: &serde_json::Value) -> Result<Vec<u8>, String> {
        let text = match value {
            serde_json::Value::String(s) => s.clone(),
            serde_json::Value::Number(n) => n.to_string(),
            serde_json::Value::Bool(b) => b.to_string(),
            serde_json::Value::Null => "null".to_string(),
            other => serde_json::to_string(other).map_err(|e| e.to_string())?,
        };
        Ok(text.into_bytes())
    }

    /// Default HTML converter
    fn convert_to_html(value: &serde_json::Value) -> Result<Vec<u8>, String> {
        let json_str = serde_json::to_string_pretty(value).map_err(|e| e.to_string())?;
        let html = format!(
            r#"<!DOCTYPE html>
<html>
<head>
    <title>API Response</title>
    <style>
        body {{ font-family: monospace; padding: 20px; }}
        pre {{ background: #f5f5f5; padding: 15px; border-radius: 5px; }}
    </style>
</head>
<body>
    <h1>API Response</h1>
    <pre>{}</pre>
</body>
</html>"#,
            html_escape::encode_text(&json_str)
        );
        Ok(html.into_bytes())
    }
}

/// Middleware for HTTP content negotiation
#[derive(Debug)]
pub struct ContentNegotiationMiddleware {
    config: ContentNegotiationConfig,
}

impl std::fmt::Debug for ContentNegotiationConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ContentNegotiationConfig")
            .field("default_content_type", &self.default_content_type)
            .field("supported_types", &self.supported_types)
            .field("add_vary_header", &self.add_vary_header)
            .field(
                "converters",
                &format!("<{} converters>", self.converters.len()),
            )
            .finish()
    }
}

impl Clone for ContentNegotiationConfig {
    fn clone(&self) -> Self {
        Self {
            default_content_type: self.default_content_type.clone(),
            supported_types: self.supported_types.clone(),
            add_vary_header: self.add_vary_header,
            converters: self.converters.clone(), // Arc is Clone, so this works correctly
        }
    }
}

impl ContentNegotiationMiddleware {
    /// Create new content negotiation middleware
    pub fn new() -> Self {
        Self {
            config: ContentNegotiationConfig::default(),
        }
    }

    /// Create with custom configuration
    pub fn with_config(config: ContentNegotiationConfig) -> Self {
        Self { config }
    }

    /// Set default content type
    pub fn default_type(mut self, content_type: ContentType) -> Self {
        self.config.default_content_type = content_type;
        self
    }

    /// Add supported content type
    pub fn support(mut self, content_type: ContentType) -> Self {
        if !self.config.supported_types.contains(&content_type) {
            self.config.supported_types.push(content_type);
        }
        self
    }

    /// Add custom converter for content type
    pub fn converter<F>(mut self, content_type: ContentType, converter: F) -> Self
    where
        F: Fn(&serde_json::Value) -> Result<Vec<u8>, String> + Send + Sync + 'static,
    {
        self.config
            .converters
            .insert(content_type.clone(), std::sync::Arc::new(converter));
        // Automatically add the content type to supported types if not already present
        if !self.config.supported_types.contains(&content_type) {
            self.config.supported_types.push(content_type);
        }
        self
    }

    /// Disable Vary header
    pub fn no_vary_header(mut self) -> Self {
        self.config.add_vary_header = false;
        self
    }

    /// Parse Accept header and return preferred content types in order
    fn parse_accept_header(&self, accept_header: &str) -> Vec<AcceptValue> {
        let mut accept_values = Vec::new();

        for value in accept_header.split(',') {
            if let Some(accept_value) = AcceptValue::parse(value.trim()) {
                accept_values.push(accept_value);
            }
        }

        // Sort by quality factor (descending)
        accept_values.sort_by(|a, b| {
            b.quality
                .partial_cmp(&a.quality)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        accept_values
    }

    /// Choose best content type based on Accept header and supported types
    fn negotiate_content_type(&self, accept_header: Option<&ElifHeaderValue>) -> ContentType {
        let accept_str = match accept_header.and_then(|h| h.to_str().ok()) {
            Some(s) => s,
            None => return self.config.default_content_type.clone(),
        };

        let accept_values = self.parse_accept_header(accept_str);

        // Find the first acceptable type that we support
        for accept_value in &accept_values {
            if self
                .config
                .supported_types
                .contains(&accept_value.content_type)
            {
                return accept_value.content_type.clone();
            }

            // Handle wildcard types
            if let ContentType::Custom(mime) = &accept_value.content_type {
                if mime == "*/*" {
                    return self.config.default_content_type.clone();
                } else if mime.ends_with("/*") {
                    let category = &mime[..mime.len() - 2];
                    // Find first supported type in the same category
                    for supported in &self.config.supported_types {
                        if supported.to_mime_type().starts_with(category) {
                            return supported.clone();
                        }
                    }
                }
            }
        }

        self.config.default_content_type.clone()
    }

    /// Check if response contains JSON data that can be converted
    fn extract_json_value(&self, response_body: &[u8]) -> Option<serde_json::Value> {
        // Try to parse as JSON
        serde_json::from_slice(response_body).ok()
    }

    /// Convert response to requested format
    async fn convert_response(
        &self,
        response: ElifResponse,
        target_type: ContentType,
    ) -> ElifResponse {
        let axum_response = response.into_axum_response();
        let (parts, body) = axum_response.into_parts();

        // Get current content type
        let current_content_type = parts
            .headers
            .get("content-type")
            .and_then(|h| h.to_str().ok())
            .and_then(ContentType::from_mime_type)
            .unwrap_or(ContentType::Json);

        // If already in target format, return as-is
        if current_content_type == target_type {
            let response = axum::response::Response::from_parts(parts, body);
            return ElifResponse::from_axum_response(response).await;
        }

        // Read response body
        let body_bytes = match axum::body::to_bytes(body, usize::MAX).await {
            Ok(bytes) => bytes,
            Err(_) => {
                // Can't read body, return as-is
                let response =
                    axum::response::Response::from_parts(parts, axum::body::Body::empty());
                return ElifResponse::from_axum_response(response).await;
            }
        };

        // Extract JSON value for conversion
        let json_value = match self.extract_json_value(&body_bytes) {
            Some(value) => value,
            None => {
                // Can't parse as JSON, return as-is
                let response =
                    axum::response::Response::from_parts(parts, axum::body::Body::from(body_bytes));
                return ElifResponse::from_axum_response(response).await;
            }
        };

        // Convert to target format
        let converted_body =
            match self.config.converters.get(&target_type) {
                Some(converter) => match converter(&json_value) {
                    Ok(body) => body,
                    Err(_) => {
                        // Conversion failed, return 406 Not Acceptable
                        return ElifResponse::from_axum_response(
                        axum::response::Response::builder()
                            .status(axum::http::StatusCode::NOT_ACCEPTABLE)
                            .header("content-type", "application/json")
                            .body(axum::body::Body::from(
                                serde_json::to_vec(&serde_json::json!({
                                    "error": {
                                        "code": "not_acceptable",
                                        "message": "Cannot convert response to requested format",
                                        "hint": "Supported formats: JSON, Plain Text, HTML"
                                    }
                                })).unwrap_or_default()
                            ))
                            .unwrap()
                    ).await;
                    }
                },
                None => {
                    // No converter available
                    return ElifResponse::from_axum_response(
                        axum::response::Response::builder()
                            .status(axum::http::StatusCode::NOT_ACCEPTABLE)
                            .header("content-type", "application/json")
                            .body(axum::body::Body::from(
                                serde_json::to_vec(&serde_json::json!({
                                    "error": {
                                        "code": "not_acceptable",
                                        "message": "Requested format is not supported",
                                        "hint": "Supported formats: JSON, Plain Text, HTML"
                                    }
                                }))
                                .unwrap_or_default(),
                            ))
                            .unwrap(),
                    )
                    .await;
                }
            };

        // Build response with new content type
        let mut new_parts = parts;
        new_parts.headers.insert(
            axum::http::HeaderName::from_static("content-type"),
            axum::http::HeaderValue::from_static(target_type.to_mime_type()),
        );

        new_parts.headers.insert(
            axum::http::HeaderName::from_static("content-length"),
            axum::http::HeaderValue::try_from(converted_body.len().to_string()).unwrap(),
        );

        if self.config.add_vary_header {
            new_parts.headers.insert(
                axum::http::HeaderName::from_static("vary"),
                axum::http::HeaderValue::from_static("Accept"),
            );
        }

        let response =
            axum::response::Response::from_parts(new_parts, axum::body::Body::from(converted_body));

        ElifResponse::from_axum_response(response).await
    }
}

impl Default for ContentNegotiationMiddleware {
    fn default() -> Self {
        Self::new()
    }
}

impl Middleware for ContentNegotiationMiddleware {
    fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static> {
        let accept_header = request.header("accept").cloned();
        let target_type = self.negotiate_content_type(accept_header.as_ref());
        let config = self.config.clone();

        Box::pin(async move {
            let response = next.run(request).await;

            let middleware = ContentNegotiationMiddleware { config };
            middleware.convert_response(response, target_type).await
        })
    }

    fn name(&self) -> &'static str {
        "ContentNegotiationMiddleware"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::request::ElifRequest;
    use crate::response::headers::ElifHeaderMap;
    use crate::response::headers::ElifHeaderName;
    use crate::response::ElifResponse;

    #[test]
    fn test_content_type_parsing() {
        assert_eq!(
            ContentType::from_mime_type("application/json"),
            Some(ContentType::Json)
        );
        assert_eq!(
            ContentType::from_mime_type("application/xml"),
            Some(ContentType::Xml)
        );
        assert_eq!(
            ContentType::from_mime_type("text/html"),
            Some(ContentType::Html)
        );
        assert_eq!(
            ContentType::from_mime_type("text/plain"),
            Some(ContentType::PlainText)
        );
    }

    #[test]
    fn test_accept_value_parsing() {
        let accept = AcceptValue::parse("application/json;q=0.8").unwrap();
        assert_eq!(accept.content_type, ContentType::Json);
        assert_eq!(accept.quality, 0.8);

        let accept = AcceptValue::parse("text/html").unwrap();
        assert_eq!(accept.content_type, ContentType::Html);
        assert_eq!(accept.quality, 1.0);

        let accept = AcceptValue::parse("text/plain;q=0.5;charset=utf-8").unwrap();
        assert_eq!(accept.content_type, ContentType::PlainText);
        assert_eq!(accept.quality, 0.5);
        assert_eq!(accept.params.get("charset"), Some(&"utf-8".to_string()));
    }

    #[test]
    fn test_accept_header_parsing() {
        let middleware = ContentNegotiationMiddleware::new();
        let values =
            middleware.parse_accept_header("text/html,application/json;q=0.9,text/plain;q=0.8");

        assert_eq!(values.len(), 3);
        // Should be sorted by quality (HTML=1.0, JSON=0.9, Plain=0.8)
        assert_eq!(values[0].content_type, ContentType::Html);
        assert_eq!(values[1].content_type, ContentType::Json);
        assert_eq!(values[2].content_type, ContentType::PlainText);
    }

    #[test]
    fn test_content_negotiation() {
        let middleware = ContentNegotiationMiddleware::new();

        // Test JSON preference
        let header = ElifHeaderValue::from_static("application/json");
        assert_eq!(
            middleware.negotiate_content_type(Some(&header)),
            ContentType::Json
        );

        // Test HTML preference with quality
        let header = ElifHeaderValue::from_static("text/html,application/json;q=0.9");
        assert_eq!(
            middleware.negotiate_content_type(Some(&header)),
            ContentType::Html
        );

        // Test unsupported type fallback
        let header = ElifHeaderValue::from_static("application/pdf");
        assert_eq!(
            middleware.negotiate_content_type(Some(&header)),
            ContentType::Json // default
        );

        // Test wildcard
        let header = ElifHeaderValue::from_static("*/*");
        assert_eq!(
            middleware.negotiate_content_type(Some(&header)),
            ContentType::Json // default
        );
    }

    #[tokio::test]
    async fn test_json_to_text_conversion() {
        let middleware = ContentNegotiationMiddleware::new();

        let mut headers = ElifHeaderMap::new();
        let accept_header = ElifHeaderName::from_str("accept").unwrap();
        let plain_value = ElifHeaderValue::from_str("text/plain").unwrap();
        headers.insert(accept_header, plain_value);
        let request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/api/data".parse().unwrap(),
            headers,
        );

        let next = Next::new(|_req| {
            Box::pin(async move {
                ElifResponse::ok().json_value(serde_json::json!({
                    "message": "Hello, World!",
                    "count": 42
                }))
            })
        });

        let response = middleware.handle(request, next).await;
        assert_eq!(
            response.status_code(),
            crate::response::status::ElifStatusCode::OK
        );

        // Check content type was converted
        let axum_response = response.into_axum_response();
        let (parts, _) = axum_response.into_parts();
        assert_eq!(parts.headers.get("content-type").unwrap(), "text/plain");
    }

    #[tokio::test]
    async fn test_json_to_html_conversion() {
        let middleware = ContentNegotiationMiddleware::new();

        let mut headers = ElifHeaderMap::new();
        let accept_header = ElifHeaderName::from_str("accept").unwrap();
        let html_value = ElifHeaderValue::from_str("text/html").unwrap();
        headers.insert(accept_header, html_value);
        let request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/api/data".parse().unwrap(),
            headers,
        );

        let next = Next::new(|_req| {
            Box::pin(async move {
                ElifResponse::ok().json_value(serde_json::json!({
                    "message": "Hello, World!"
                }))
            })
        });

        let response = middleware.handle(request, next).await;
        assert_eq!(
            response.status_code(),
            crate::response::status::ElifStatusCode::OK
        );

        let axum_response = response.into_axum_response();
        let (parts, body) = axum_response.into_parts();
        assert_eq!(parts.headers.get("content-type").unwrap(), "text/html");

        // Check that HTML was generated
        let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
        let html_content = String::from_utf8(body_bytes.to_vec()).unwrap();
        assert!(html_content.contains("<!DOCTYPE html>"));
        assert!(html_content.contains("Hello, World!"));
    }

    #[tokio::test]
    async fn test_unsupported_format_406() {
        let middleware = ContentNegotiationMiddleware::new();

        let mut headers = ElifHeaderMap::new();
        let accept_header = ElifHeaderName::from_str("accept").unwrap();
        let pdf_value = ElifHeaderValue::from_str("application/pdf").unwrap();
        headers.insert(accept_header, pdf_value);
        let request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/api/data".parse().unwrap(),
            headers,
        );

        let next = Next::new(|_req| {
            Box::pin(async move {
                ElifResponse::ok().json_value(serde_json::json!({
                    "message": "Hello, World!"
                }))
            })
        });

        let response = middleware.handle(request, next).await;
        // Should still return JSON as default since PDF is not supported but has a converter
        assert_eq!(
            response.status_code(),
            crate::response::status::ElifStatusCode::OK
        );
    }

    #[tokio::test]
    async fn test_builder_pattern() {
        let middleware = ContentNegotiationMiddleware::new()
            .default_type(ContentType::Html)
            .support(ContentType::Csv)
            .no_vary_header();

        assert_eq!(middleware.config.default_content_type, ContentType::Html);
        assert!(middleware
            .config
            .supported_types
            .contains(&ContentType::Csv));
        assert!(!middleware.config.add_vary_header);
    }

    #[test]
    fn test_content_type_mime_types() {
        assert_eq!(ContentType::Json.to_mime_type(), "application/json");
        assert_eq!(ContentType::Xml.to_mime_type(), "application/xml");
        assert_eq!(ContentType::Html.to_mime_type(), "text/html");
        assert_eq!(ContentType::PlainText.to_mime_type(), "text/plain");
        assert_eq!(ContentType::Csv.to_mime_type(), "text/csv");
    }

    #[test]
    fn test_json_conversion_functions() {
        let json_val = serde_json::json!({
            "name": "test",
            "value": 42
        });

        // Test JSON conversion
        let json_result = ContentNegotiationConfig::convert_to_json(&json_val).unwrap();
        assert!(String::from_utf8(json_result).unwrap().contains("test"));

        // Test text conversion with string value
        let text_val = serde_json::json!("Hello World");
        let text_result = ContentNegotiationConfig::convert_to_text(&text_val).unwrap();
        assert_eq!(String::from_utf8(text_result).unwrap(), "Hello World");

        // Test HTML conversion
        let html_result = ContentNegotiationConfig::convert_to_html(&json_val).unwrap();
        let html_content = String::from_utf8(html_result).unwrap();
        assert!(html_content.contains("<!DOCTYPE html>"));
        assert!(html_content.contains("test"));
    }

    #[tokio::test]
    async fn test_custom_converter_preservation_after_clone() {
        // Test that custom converters are preserved after config clone
        let middleware =
            ContentNegotiationMiddleware::new().converter(ContentType::Csv, |_json_value| {
                // Custom CSV converter
                Ok(b"custom,csv,data".to_vec())
            });

        let mut headers = ElifHeaderMap::new();
        let accept_header = ElifHeaderName::from_str("accept").unwrap();
        let csv_value = ElifHeaderValue::from_str("text/csv").unwrap();
        headers.insert(accept_header, csv_value);
        let request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/api/data".parse().unwrap(),
            headers,
        );

        let next = Next::new(|_req| {
            Box::pin(async move {
                ElifResponse::ok().json_value(serde_json::json!({
                    "test": "data"
                }))
            })
        });

        // This should work because the custom converter is preserved through clone
        let response = middleware.handle(request, next).await;
        assert_eq!(
            response.status_code(),
            crate::response::status::ElifStatusCode::OK
        );

        // Check that it was converted to CSV format
        let axum_response = response.into_axum_response();
        let (parts, _) = axum_response.into_parts();
        assert_eq!(parts.headers.get("content-type").unwrap(), "text/csv");
    }
}