-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathProgram.fs
More file actions
89 lines (74 loc) · 2.75 KB
/
Program.fs
File metadata and controls
89 lines (74 loc) · 2.75 KB
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
open System
open Microsoft.AspNetCore
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Http
open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Hosting
open Giraffe
open Giraffe.EndpointRouting
type Car =
{
Brand: string
Color: string
ReleaseYear: int
}
let handler1: HttpHandler =
fun (_: HttpFunc) (ctx: HttpContext) -> ctx.WriteTextAsync "Hello World"
let handler2 (firstName: string, age: int) : HttpHandler =
fun (_: HttpFunc) (ctx: HttpContext) ->
sprintf "Hello %s, you are %i years old." firstName age |> ctx.WriteTextAsync
let handler3 (a: string, b: string, c: string, d: int) : HttpHandler =
fun (_: HttpFunc) (ctx: HttpContext) -> sprintf "Hello %s %s %s %i" a b c d |> ctx.WriteTextAsync
let handlerNamed (petId: int) : HttpHandler =
fun (_: HttpFunc) (ctx: HttpContext) -> sprintf "PetId: %i" petId |> ctx.WriteTextAsync
/// Example request:
///
/// ```bash
/// curl -v localhost:5000/json -X Post -d '{"brand":"Ford", "color":"Black", "releaseYear":2015}'
/// ```
let jsonHandler: HttpHandler =
fun (next: HttpFunc) (ctx: HttpContext) ->
task {
match! ctx.BindJsonAsync<Car>() with
| {
Brand = _brand
Color = _color
ReleaseYear = releaseYear
} when releaseYear >= 1990 -> return! json {| Message = "Valid car" |} next ctx
| _ -> return! (setStatusCode 400 >=> json {| Message = "Invalid car year" |}) next ctx
}
let endpoints =
[
subRoute "/foo" [ GET [ route "/bar" (text "Aloha!") ] ]
GET [
route "/" (text "Hello World")
routef "/%s/%i" handler2
routef "/%s/%s/%s/%i" handler3
routef "/pet/%i:petId" handlerNamed
]
GET_HEAD [
route "/foo" (text "Bar")
route "/x" (text "y")
route "/abc" (text "def")
route "/123" (text "456")
]
// Not specifying a http verb means it will listen to all verbs
subRoute "/sub" [ route "/test" handler1 ]
POST [ route "/json" jsonHandler ]
]
let notFoundHandler = "Not Found" |> text |> RequestErrors.notFound
let configureApp (appBuilder: IApplicationBuilder) =
appBuilder.UseRouting().UseGiraffe(endpoints).UseGiraffe(notFoundHandler)
let configureServices (services: IServiceCollection) =
services.AddRouting().AddGiraffe() |> ignore
[<EntryPoint>]
let main args =
let builder = WebApplication.CreateBuilder(args)
configureServices builder.Services
let app = builder.Build()
if app.Environment.IsDevelopment() then
app.UseDeveloperExceptionPage() |> ignore
configureApp app
app.Run()
0