Giter Site home page Giter Site logo

hardenedelements / routable Goto Github PK

View Code? Open in Web Editor NEW
6.0 3.0 0.0 115 KB

Platform agnostic request routing library for .NET

Home Page: https://www.nuget.org/packages/Routable/

License: MIT License

C# 98.99% HTML 1.01%
dotnet routing http kestrel web-service dotnet-core web-application-framework

routable's Introduction

Build Status NuGet

Routable

Routable is a simple, easy to use, request routing library. It is platform agnostic and designed to easily integrate with whatever platform you prefer. Support for Microsoft Kestrel is provided out the gate by Routable.Kestrel, making routable a must-have for multi-platform web services and applications.

Routable is brand new; as such, it is missing a lot of must-have functionality. We hope to add this functionality as time permits, and if you see something you think we missed we would love it if you would file an issue (be detailed please; pull requests are welcome, but they may be modified significantly).

Three simple rules

Routable is governed by three simple rules. First, the base library is simple and needs to stay that way. It doesn't bother with things like views, complex content type negotiation or canned authentication schemes. Nope, routable is here to route your requests and give you the glorious opportunity to handle those requests. Second, the base library is platform agnostic and it doesn't quibble over the gory details of delivering complete and total commonality to everyone - no, instead, we route your requests and return you to your regularly scheduled platform. And finally, routable is extensible. We admit it, we use a lot of generics - but only because we love to see the way people work when tools get out of the way and let developers get in touch with their platform.

Libraries

Routable is a collection of libraries. First, you got your platform agnostic base library - that's Routable. Then you have your simple view support - that's Routable.Views.Simple. JSON support? Yeah, we integrate JSON.NET in Routable.Json. And finally, you're going to need at least one platform integration to get started - we chose Kestrel because it's what we use the most; you can find that under Routable.Kestrel. There are other platforms in the wind, but we haven't published those quite yet, they need some polishing up.

Library NuGet Download
Routable NuGet
Routable.Kestrel NuGet
Routable.Json NuGet
Routable.Views.Simple NuGet

Examples (targeting Kestrel)

Using a bit of creative license, we'll be using Routable.Kestrel as a companion to these examples, very little changes with other platforms (eg. change kestrel to my favorite platform).

Registration

public sealed class Startup
{
	static void Main(string[] args) => new WebHostBuilder()
		.UseKestrel(options => options.Listen(IPAddress.Any, 8080))
		.Configure(builder => builder.UseRoutable(options => options
			.WithJsonSupport()
			.UseFileSystemViews(_ => _.AddSearchPath("views").OnUnresolvedModelValue((expr, paths, model) => $"[ERR! ({expr})]"))
			.AddRouting(new MyRouting(options))
			.AddRouting(new KestrelRouting(options) {
				_ => _.Get("/meeseeks").Do((ctx, req, resp) => resp.Write("Hi, I'm Mr. Meeseeks!")),
				_ => _.Path("/grimey").Do((ctx, req, resp) => resp.Write("I don't check methods, because I'm Homer Simpson!"))
			})
			.OnError(new KestrelRouting(options) {
				_ => _.Do((context, request, response) => {
					response.Status = 500;
					response.Write($"{context.Error?.GetType()?.FullName} ({context.Error?.Message}):\n\t{context.Error.StackTrace.Replace("\n", "\n\t")}\n");
				})
			})
		))
		.Build()
		.Run();
}

Routing in a Class

public sealed class MyRouting : KestrelRouting
{
	public MyRouting(RoutableOptions<KestrelRoutableContext, KestrelRoutableRequest, KestrelRoutableResponse> options) : base(options)
	{
		// write a view using Routable.Views.Simple.
		Add(_ => _.Get("/").DoAsync(async (ctx, req, resp) => await resp.WriteViewAsync("index", new {
			SomeModelField = "Widget widget"
		})));

		Add(_ => _.Get("/test").Do((ctx, req, resp) => resp.Write("Hello World!")));
		Add(_ => _.Post("/test").Try(OnTestPost));

		Add(_ => _.Get("/json").Do((ctx, req, resp) => resp.Write(JObject.FromObject(new {
			Field1 = 1,
			Field2 = "string?"
		}))));
	}

	private bool OnTestPost(KestrelRoutableContext ctx, KestrelRoutableRequest req, KestrelRoutableResponse resp) {
		if(req.Form.TryGetValue("my-parameter", out var value) == true) {
			resp.Write($"Value: {value.FirstOrDefault() ?? "<null>"}");
			return true;
		} else {
			return false;
		}
	}
}

routable's People

Contributors

mmaguigan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

routable's Issues

Ability to access model root

User should be able to obtain the root model regardless of nesting level (eg. within a @ForEach) using the @Root expression.

Line endings are not consistent

It seems the line endings throughout the project have become inconsistent. Use dos2unix and clean up the entire repository while it's young. This will dirty up git-blame.

Add unit tests

This project could definitely use some serious love in the unit test department.

Custom view resolution

Currently the Routable.Views.Simple library resolves views using the file system. This should use a view resolution delegate with handy shortcuts for file system loading; and perhaps embedded resource streams.

Add pattern factory method

Feature Request

Add support for pattern matching to determine if a value has a certain shape.

Proposed solution

Add an extension method with concise syntax like Add(route => route.Post().Pattern("/test/{id:guid}")

Additional context

Should support or handle uri with omitted forward slash

View configuration should be enumerable

If view configuration were enumerable, a library author could offer a routing collection, extension method for adding the functionality of said library and leverage embedded views from the library assembly. All without interfering with the calling web application.

Added simple parsing engine for views

Using regular expressions for model value replacement is a quick and dirty method of providing a template engine. However, using Sprache we can have more advanced view template operations and we can add more easily.

Acceptance criteria

  1. Use Sprache to parse view templates to a tree of operations.
  2. Cache operation tree as in-memory representation of views.
  3. Render operation trees against a model on demand.
  4. Bonus, detect template updates and re-parse the view template.

Stacked routing

If multiple routes match a given request, they should be enumerated individually and each one should be processed sequentially until one of the routes successfully processes the request in full. For example, if we have four routes, and the first two are bypassable routes that return false, the third will be processed - and if that route is successfully processed the fourth will not be.

Use case

  • Authentication patterns
  • Session management
  • Authorization patterns
  • Auditing
  • Analytics

Write documentation

This project is in desperate need of good documentation. Start by documenting this issue ๐Ÿ˜„

Allow view inclusion

Allow views to incorporate the content of other views. This may be accomplished by nesting the AST of the included view within the AST of the caller. Protip: the nested content will not expire properly when changes are detected unless written properly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.