beetlex-io / FastHttpApi

a lightweight and high-performance http/websocket service component in the dotnet core platform that supports TLS.
Apache License 2.0
650 stars 175 forks source link
dotnet dotnetcore fasthttp fasthttpapi http https-server rpc-api rpc-service ssl webapi websocket websockets-server

BeetleX.FastHttpApi is a lightweight and high-performance HTTP service component in the dotnet core platform that supports WebSocket and SSL.

                          <img src="https://img.shields.io/nuget/dt/BeetleX.FastHttpApi">
                          </a>

samples

[https://github.com/beetlex-io/BeetleX-Samples]

Web Framework Benchmarks

Round 20 benchmarks-round20

Using

Install BeetleX.FastHttpApi

Install-Package BeetleX.FastHttpApi

Base sample code

    [Controller]
    class Program
    {
        private static BeetleX.FastHttpApi.HttpApiServer mApiServer;
        static void Main(string[] args)
        {
            mApiServer = new BeetleX.FastHttpApi.HttpApiServer();
            mApiServer.Options.LogLevel = BeetleX.EventArgs.LogType.Trace;
            mApiServer.Options.LogToConsole = true;
            mApiServer.Debug();//set view path with vs project folder
            mApiServer.Register(typeof(Program).Assembly);
            //mApiServer.Options.Port=80; set listen port to 80
            mApiServer.Open();//default listen port 9090  
            Console.Write(mApiServer.BaseServer);
            Console.Read();
        }
        // Get /hello?name=henry 
        // or
        // Get /hello/henry
        [Get(Route="{name}")]
        public object Hello(string name)
        {
            return $"hello {name} {DateTime.Now}";
        }
        // Get /GetTime  
        public object GetTime()
        {
            return DateTime.Now;
        }
    }

Url Map

mApiServer.Map("/", (ctx) =>
{
    ctx.Result(new TextResult("map /"));
});

mApiServer.Map("/user/{id}", async (ctx) =>
{
    ctx.Result(new TextResult((string)ctx.Data["id"]));
});

Url rewrite

mApiServer.UrlRewrite.Add("/api/PostStream/{code}/{datacode}", "/api/PostStream");
mApiServer.UrlRewrite.Add("/api/PostStream/{code}", "/api/PostStream");
mApiServer.UrlRewrite.Add(null, "/gettime", "/time", null);

Action route

[RouteMap("/map/{code}")]
[RouteMap("/map/{code}/{customer}")]
public object Map(string code, string customer)
{
    return new { code, customer };
}

Hosting and DI services

Install-Package BeetleX.FastHttpApi.Hosting

    public class Program
    {
        static void Main(string[] args)
        {
            HttpServer host = new HttpServer(80);
            host.UseTLS("test.pfx", "123456");
            host.Setting((service, option) =>
            {
                service.AddTransient<UserInfo>();
                option.LogToConsole = true;
                option.LogLevel = BeetleX.EventArgs.LogType.Info;
            });
            host.Completed(server =>
            {

            });
            host.RegisterComponent<Program>();
            host.Run();
        }
    }

    [Controller]
    public class Home
    {
        public Home(UserInfo user)
        {
            mUser = user;
        }

        public object Hello()
        {
            return mUser.Name;
        }

        private UserInfo mUser;
    }

    public class UserInfo
    {
        public string Name { get; set; } = "admin";
    }

Windows service

class Program
{
    private static HttpServer mServer;

    static void Main(string[] args)
    {
        mServer = new HttpServer(80);
        mServer.IsWindowsServices = true;
        mServer.Setting((service, option) =>
        {
            option.LogToConsole = true;
            option.WriteLog = true;
            option.LogLevel = BeetleX.EventArgs.LogType.Info;
        });
        mServer.RegisterComponent<Home>();
        mServer.Run();
    }
}
[Controller]
public class Home
{
    public object Hello(string name)
    {
        return $"hello {name}";
    }
}

EntityFrameworkCore extensions

BeetleX.FastHttpApi.EFCore.Extension

class Program
{
    static void Main(string[] args)
    {
        HttpApiServer server = new HttpApiServer();
        server.AddEFCoreDB<NorthwindEFCoreSqlite.NorthwindContext>();
        server.Options.Port = 80;
        server.Options.LogToConsole = true;
        server.Options.LogLevel = EventArgs.LogType.Info;
        server.Options.SetDebug();
        server.Register(typeof(Program).Assembly);
        server.AddExts("woff");
        server.Open();
        Console.Read();
    }
}
[Controller]
public class Webapi
{
    public DBObjectList<Customer> Customers(string name, string country, EFCoreDB<NorthwindContext> db)
    {
        Select<Customer> select = new Select<Customer>();
        if (!string.IsNullOrEmpty(name))
            select &= c => c.CompanyName.StartsWith(name);
        if (!string.IsNullOrEmpty(country))
            select &= c => c.Country == country;
        select.OrderBy(c => c.CompanyName.ASC());
        return (db.DBContext, select);
    }

    [Transaction]
    public void DeleteCustomer(string customer, EFCoreDB<NorthwindContext> db)
    {
        db.DBContext.Orders.Where(o => o.CustomerID == customer).Delete();
        db.DBContext.Customers.Where(c => c.CustomerID == customer).Delete();
    }

    public DBValueList<string> CustomerCountry(EFCoreDB<NorthwindContext> db)
    {
        SQL sql = "select distinct country from customers";
        return (db.DBContext, sql);
    }
}

Setting https

/hello?name=xxxor/hello/henry

        [Get(Route = "{name}")]
        public object Hello(string name, IHttpContext context)
        {
            return $"hello {name} {DateTime.Now}";
        }

/SetValue?id=xxx&value=xxxxor/SetValue/xxx-xxx

        [Get(Route = "{id}-{value}")]
        public object SetValue(string id, string value, IHttpContext context)
        {
            return $"{id}={value} {DateTime.Now}";
        }

{"name":"xxxx","value":"xxx"}

        [Post]
        [JsonDataConvert]
        public object Post(string name, string value, IHttpContext context)
        {
            Console.WriteLine(context.Data);
            return $"{name}={value}";
        }

or

        [Post]
        [JsonDataConvert]
        public object Post(Property body, IHttpContext context)
        {
            Console.WriteLine(context.Data);
            return $"{body.name}={body.value}";
        }

name=aaa&value=aaa

        [Post]
        [FormUrlDataConvert]
        public object PostForm(string name, string value, IHttpContext context)
        {
            Console.WriteLine(context.Data);
            return $"{name}={value}";
        }

Websocket

Request json

{
      url: '/Hello', 
      params: { name: 'test' }
}

Request json

{
      url: '/GetTime', 
      params: { }
}