-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHelloWorld.elm
93 lines (77 loc) · 2.34 KB
/
HelloWorld.elm
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
module HelloWorld exposing (main)
import Error
import Html.String as Html
import Html.String.Attributes as Attr
import Logger as Log
import Response
import Server exposing (Config, Flags, Request, Response)
main : Server.Program
main =
Server.program
{ init = init
, handler = handler
}
init : Flags -> Config
init _ =
Server.baseConfig
handler : Request -> Response
handler request =
case Server.getPath request of
[] ->
Response.ok
|> Response.setBody indexPage
|> Server.respond request
|> Server.andThen (\_ -> Log.toConsole "index page requested")
[ "hello" ] ->
let
maybeName =
Server.getQueryParams request
|> listFind (\( key, _ ) -> key == "name")
in
case maybeName of
Just ( _, Just name ) ->
Log.toConsole ("Saying hello to " ++ name)
|> Server.andThen
(\_ ->
Response.ok
|> Response.setBody ("Hello, " ++ name ++ "!")
|> Server.respond request
)
_ ->
Response.ok
|> Response.setBody "What is your name?"
|> Server.respond request
_ ->
Response.notFound
|> Server.respond request
listFind : (a -> Bool) -> List a -> Maybe a
listFind predicate list =
case list of
[] ->
Nothing
next :: rest ->
if predicate next then
Just next
else
listFind predicate rest
indexPage : String
indexPage =
Html.div
[]
[ Html.h1 [] [ Html.text "Howdy, Partner" ]
, Html.nav
[]
[ Html.a
[ Attr.href "" ]
[ Html.text "Home" ]
, Html.a
[ Attr.href "hello?name=carl" ]
[ Html.text "Say Hello" ]
]
]
|> Html.toString 2
|> (++) "<!DOCTYPE html><html><head><title>Fun With Elm</title></head><body>"
|> (\html ->
html
++ "</body></html>"
)