80 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using MontoyaTech.Rest.Net;
namespace MontoyaTech.Rest.Net.Example
{
public class Program
{
public class User
{
public string Name = null;
public User(string name)
{
this.Name = name;
}
public static explicit operator User(string input)
{
return new User(input.ToString());
}
}
public static void Main(string[] args)
{
var listener = new RouteListener(8080,
new Route(HttpRequestMethod.Get, "/status", Status),
new Route<double, double>(HttpRequestMethod.Post, "/add/{a}/{b}", Add),
new Route<User>(HttpRequestMethod.Post, "/signup/{username}", Signup),
new Route(HttpRequestMethod.Get, "/json", Json)
);
listener.RequestPreProcessEvent += (HttpListenerContext context) => {
Console.WriteLine("Request start: " + context.Request.RawUrl);
return true;
};
listener.RequestPostProcessEvent += (HttpListenerContext context) =>
{
Console.WriteLine("Request end: " + context.Request.RawUrl);
};
listener.Start();
Console.WriteLine("Available routes:");
foreach (var route in listener.Routes)
Console.WriteLine($"- [{route.Method}] {route.Syntax}");
Console.WriteLine($"Rest api server running at http://localhost:{listener.Port}");
listener.Block();
}
public static HttpListenerResponse Status(HttpListenerContext context)
{
return context.Response.WithStatus(HttpStatusCode.OK).WithText("Everything is operational. 👍");
}
public static HttpListenerResponse Add(HttpListenerContext context, double a, double b)
{
return context.Response.WithStatus(HttpStatusCode.OK).WithText((a + b).ToString());
}
public static HttpListenerResponse Signup(HttpListenerContext context, User user)
{
return context.Response.WithStatus(HttpStatusCode.OK).WithText("User:" + user.Name);
}
public static HttpListenerResponse Json(HttpListenerContext context)
{
return context.Response.WithStatus(HttpStatusCode.OK).WithJson(new User("Rest.Net"));
}
}
}