118 lines
3.7 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;
using System.Net.Mime;
namespace MontoyaTech.Rest.Net.Example
{
public class Program
{
public class User
{
public string Name = null;
public List<string> List = null;
public ulong Property { get; set; }
public User() { }
public User(string name)
{
this.Name = name;
}
}
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<string>(HttpRequestMethod.Get, "/auth/{username}", Exists),
new Route(HttpRequestMethod.Post, "/auth/signup", Signup),
new Route(HttpRequestMethod.Get, "/auth/", Json)
);
string code = ClientCodeGenerator.GenerateCSharpClient(listener.Routes);
Console.WriteLine(code);
listener.RequestPreProcessEvent += (HttpListenerContext context) => {
Console.WriteLine($"[{context.Request.HttpMethod}] Request start: " + context.Request.RawUrl);
return true;
};
listener.RequestPostProcessEvent += (HttpListenerContext context) =>
{
Console.WriteLine($"[{context.Request.HttpMethod}] 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 {listener.BaseUrl}");
var client = new Client(listener.BaseUrl);
var result = client.Auth.Get();
listener.Block();
}
[RouteGroup("Test")]
[RouteResponse(typeof(string))]
public static HttpListenerResponse Status(HttpListenerContext context)
{
return context.Response.WithStatus(HttpStatusCode.OK).WithText("Everything is operational. 👍");
}
[RouteGroup("Test")]
[RouteResponse(typeof(string))]
public static HttpListenerResponse Add(HttpListenerContext context, double a, double b)
{
return context.Response.WithStatus(HttpStatusCode.OK).WithText((a + b).ToString());
}
[RouteGroup("Test")]
[RouteRequest(typeof(User))]
public static HttpListenerResponse SignupRequest(HttpListenerContext context)
{
return context.Response.WithStatus(HttpStatusCode.OK);
}
[RouteGroup("Auth")]
[RouteName("UserExists")]
[RouteResponse(typeof(bool))]
public static HttpListenerResponse Exists(HttpListenerContext context, string name)
{
Console.WriteLine("Auth.Exists called, name:" + name);
return context.Response.WithStatus(HttpStatusCode.OK).WithJson(true);
}
[RouteGroup("Auth")]
[RouteRequest(typeof(User))]
public static HttpListenerResponse Signup(HttpListenerContext context)
{
return context.Response.WithStatus(HttpStatusCode.OK);
}
[RouteGroup("Auth")]
[RouteName("Get")]
[RouteResponse(typeof(User))]
public static HttpListenerResponse Json(HttpListenerContext context)
{
return context.Response.WithStatus(HttpStatusCode.OK).WithJson(new User("Rest.Net"));
}
}
}