Comments (4)
Hello!
I don't use Opium these days so I have fallen behind on updating examples related to it after making some breaking changes within this library.
That said, here's an example that should help you get started! This takes a couple of different handlers from the example shown in Opium's readme, but with routes
doing the heavy lifting when it comes to routing. Opium
itself doesn't allow customizing which router gets used so one can piggy-back on top of a App.all "**"
route which will forward everything to the custom routes based routing layer. Hope this helps!
open Opium
module Person = struct
type t = { name : string; age : int }
let yojson_of_t t = `Assoc [ ("name", `String t.name); ("age", `Int t.age) ]
let t_of_yojson yojson =
match yojson with
| `Assoc [ ("name", `String name); ("age", `Int age) ] -> { name; age }
| _ -> failwith "invalid person json"
end
let print_param_handler name _req =
Response.of_plain_text (Printf.sprintf "Hello, %s" name) |> Lwt.return
let print_person_handler name age _req =
{ Person.name; age } |> Person.yojson_of_t |> Response.of_json |> Lwt.return
let not_found _req = Response.of_plain_text ~status:`Not_found "" |> Lwt.return
let routed_handler routes =
let router = Routes.one_of routes in
fun req ->
match Routes.match' router ~target:req.Request.target with
| Routes.NoMatch -> not_found req
| FullMatch r -> r req
| MatchWithTrailingSlash r ->
(* This branch indicates that incoming request's path finishes with a
trailing slash. If you app needs to distinguish trailing slashes
(/a/b vs /a/b/), this is where you'd write something to handle the
use-case *)
r req
let () =
App.empty
|> App.all "**" (fun req ->
routed_handler
Routes.
[
route (s "hello" / str /? nil) print_param_handler;
route (s "person" / str / int /? nil) print_person_handler;
]
req)
|> App.run_command
from routes.
Thanks a lot, your example really helped!
What library do you use to build your HTTP layer? I really like your library so I'd be interested to hear your opinion :)
Usually, my routes define acting on "resources", receiving one or many verbs. Since routes
isn't concerned with the HTTP verb, I organized my code this way for now:
type 'a resource = { get : 'a Routes.route; post : 'a Routes.route }
let hello_resource =
{ get = Routes.(route (s "hello" / str /? nil) print_param_handler)
; post = Routes.(route (s "hello" / str /? nil) post_stuff)
}
;;
let () =
App.empty
|> App.get "**" (fun req ->
routed_handler
Routes.
[ hello_resource.get
; route (s "person" / str / int /? nil) print_person_handler
]
req)
|> App.post "**" (fun req -> routed_handler [ hello_resource.post ] req)
|> App.run_command
;;
Please let me know if you can think of a better way :)
Have a great day!
from routes.
What library do you use to build your HTTP layer? I really like your library so I'd be interested to hear your opinion :)
My preference is to use async when writing concurrent applications. I've been working on https://github.com/anuragsoni/shuttle/tree/main/http which provides a http codec implementation (only HTTP/1.1 for now) and my current preference is to use this when I need to write http services/clients. There are some docs hosted online (https://anuragsoni.github.io/shuttle/shuttle_http/index.html for an intro to writing servers) and https://anuragsoni.github.io/shuttle/shuttle_http/Shuttle_http/Client/index.html has some docs for using clients.
Usually, my routes define acting on "resources", receiving one or many verbs.
This is my preferred approach as well. I handle this slightly different from your example though, and implement the method handling within a handler like so:
let validate_methods methods handler request =
match methods with
| [] -> handler request
| xs ->
if List.mem request.Request.meth xs then handler request
else Lwt.return (Response.make ~status:`Method_not_allowed ())
let print_param_handler name =
validate_methods [ `GET ] (fun _req ->
(* Dispatch different actions for HTTP verbs if needed *)
Response.of_plain_text (Printf.sprintf "Hello, %s" name) |> Lwt.return)
I like this as it makes it very clear to me that a handler was invoked because a route "matched", but if it has a http verb that shouldn't be used we exit early and return a HTTP 405. Another potential option to organize this logic could be to create one router per http verb, and dispatch requests like so:
module MethodMap = Map.Make (struct
type t = Method.t
let compare a b = compare a b
end)
let routed_handler' routes req =
match MethodMap.find_opt req.Request.meth routes with
| None -> Lwt.return (Response.make ~status:`Method_not_allowed ())
| Some router -> (
match Routes.match' router ~target:req.Request.target with
| Routes.NoMatch -> not_found req
| FullMatch r -> r req
| MatchWithTrailingSlash r ->
(* This branch indicates that incoming request's path finishes with a
trailing slash. If you app needs to distinguish trailing slashes
(/a/b vs /a/b/), this is where you'd write something to handle the
use-case *)
r req)
I tend to not prefer this as it leads to some duplication of route definitions if the same path sequence needs to work with multiple http verbs.
from routes.
I'm going to migrate this issue to a discussion as I don't think I'll add any opium related samples directly within this repo.
from routes.
Related Issues (20)
- API for catch all route HOT 8
- Support additonal methods `Other(string) HOT 3
- Forward additional custom data to handlers HOT 9
- fix travis build with 4.08 HOT 2
- Ability to get human readable name for route HOT 2
- Expose an add method which allows a user to add a new route to the router trie HOT 2
- Add human readable route patterns
- Use a less restrictive ocaml/dune constraint
- Keep the old readme example in examples/ HOT 2
- Optional patterns at the end of path HOT 3
- Pattern with 2+ options where path is discarded HOT 5
- Group targets with different signature under same type HOT 8
- Fix mdx tests on windows HOT 1
- Update or remove the bucklescript packaging setup
- Versions 0.9.0 and 0.9.1 don't appear in opam packages HOT 3
- Compiler error when combining custom pattern with "variable pattern" (e.g. str) HOT 2
- Route.match' edge case question HOT 5
- Trailing slashes example in the README HOT 1
- Good way to match on methods and paths?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from routes.