0 | ||| Define response types and functions
 1 | module Pact.WAI.Response
 2 |
 3 | import Pact.WAI.Core
 4 | import Pact.WAI.Header
 5 | import Pact.WAI.StatusCode
 6 | import Data.String
 7 | import Data.SortedMap as Map
 8 |
 9 | import Derive.Prelude
10 |
11 | %language ElabReflection
12 |
13 | public export
14 | record Response where
15 |   constructor MkResponse
16 |   status : StatusCode
17 |   headers : Headers
18 |   body : Maybe String
19 |
20 | %runElab derive "Response" [Show]
21 |
22 | ||| 404 Not Found response
23 | ||| Returned when the requested path cannot be matched to any route
24 | public export
25 | notFoundResponse : Response
26 | notFoundResponse = MkResponse notFound emptyHeaders Nothing
27 |
28 | ||| 400 Bad Request response
29 | ||| Returned when the request is invalid
30 | public export
31 | badRequestResponse : String -> Response
32 | badRequestResponse body = MkResponse badRequest emptyHeaders (Just body)
33 |
34 | ||| Render headers to a string
35 | ||| @ headers The headers to render
36 | public export
37 | renderHeaders : Headers -> String
38 | renderHeaders headers = 
39 |   let headersList = Map.toList headers
40 |   in Data.String.joinBy "\r\n" . map (\(k, v) => "\{k}: \{v}" ) $ headersList
41 |
42 | ||| Response rendering function
43 | ||| Converts a Response to a string for HTTP response
44 | ||| @ resp The response object to render
45 | public export
46 | renderResponse : Response -> String
47 | renderResponse (MkResponse status headers body) = 
48 |   let statusLine = "HTTP/1.1 \{status} \{statusMessage status}\r\n"
49 |       bodyStr = maybe "" id body
50 |   in statusLine ++ renderHeaders headers ++ "\r\n\r\n" ++ bodyStr
51 |   
52 |
53 | testResponse : Response
54 | testResponse = MkResponse ok (fromList [("Content-Type", "text/plain"), ("Content-Length", "12")]) (Just "Hello, World!")
55 |
56 | test = renderResponse testResponse