header_regression_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package fasthttp
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "strings"
  7. "testing"
  8. )
  9. func TestIssue28ResponseWithoutBodyNoContentType(t *testing.T) {
  10. t.Parallel()
  11. var r Response
  12. // Empty response without content-type
  13. s := r.String()
  14. if strings.Contains(s, "Content-Type") {
  15. t.Fatalf("unexpected Content-Type found in response header with empty body: %q", s)
  16. }
  17. // Explicitly set content-type
  18. r.Header.SetContentType("foo/bar")
  19. s = r.String()
  20. if !strings.Contains(s, "Content-Type: foo/bar\r\n") {
  21. t.Fatalf("missing explicitly set content-type for empty response: %q", s)
  22. }
  23. // Non-empty response.
  24. r.Reset()
  25. r.SetBodyString("foobar")
  26. s = r.String()
  27. if !strings.Contains(s, fmt.Sprintf("Content-Type: %s\r\n", defaultContentType)) {
  28. t.Fatalf("missing default content-type for non-empty response: %q", s)
  29. }
  30. // Non-empty response with custom content-type.
  31. r.Header.SetContentType("aaa/bbb")
  32. s = r.String()
  33. if !strings.Contains(s, "Content-Type: aaa/bbb\r\n") {
  34. t.Fatalf("missing custom content-type: %q", s)
  35. }
  36. }
  37. func TestIssue6RequestHeaderSetContentType(t *testing.T) {
  38. t.Parallel()
  39. testIssue6RequestHeaderSetContentType(t, MethodGet)
  40. testIssue6RequestHeaderSetContentType(t, MethodPost)
  41. testIssue6RequestHeaderSetContentType(t, MethodPut)
  42. testIssue6RequestHeaderSetContentType(t, MethodPatch)
  43. }
  44. func testIssue6RequestHeaderSetContentType(t *testing.T, method string) {
  45. contentType := "application/json"
  46. contentLength := 123
  47. var h RequestHeader
  48. h.SetMethod(method)
  49. h.SetRequestURI("http://localhost/test")
  50. h.SetContentType(contentType)
  51. h.SetContentLength(contentLength)
  52. issue6VerifyRequestHeader(t, &h, contentType, contentLength, method)
  53. s := h.String()
  54. var h1 RequestHeader
  55. br := bufio.NewReader(bytes.NewBufferString(s))
  56. if err := h1.Read(br); err != nil {
  57. t.Fatalf("unexpected error: %s", err)
  58. }
  59. issue6VerifyRequestHeader(t, &h1, contentType, contentLength, method)
  60. }
  61. func issue6VerifyRequestHeader(t *testing.T, h *RequestHeader, contentType string, contentLength int, method string) {
  62. if string(h.ContentType()) != contentType {
  63. t.Fatalf("unexpected content-type: %q. Expecting %q. method=%q", h.ContentType(), contentType, method)
  64. }
  65. if string(h.Method()) != method {
  66. t.Fatalf("unexpected method: %q. Expecting %q", h.Method(), method)
  67. }
  68. if h.ContentLength() != contentLength {
  69. t.Fatalf("unexpected content-length: %d. Expecting %d. method=%q", h.ContentLength(), contentLength, method)
  70. }
  71. }