大部分主流语言都支持web框架,并且实现起来相对轻便,简捷,比如:
go的gin包
package main
import "github.com/gin-gonic/gin"
func main() {r := gin.Default()r.GET("/ping", func(c *gin.Context) {c.JSON(200, gin.H{"message": "pong",})})r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
python(未运行)
from flask import Flask, url_for
app = Flask(__name__)@app.route('/ping')
def api_ping():return jsonify(message="pong")
if __name__ == '__main__':app.run()
其实.net中也是有的,比如以前的nancy(https://nancyfx.org/)就比较轻量,今天介绍的是更简单的构建mini web host的方法,那就是featherhttp(github:https://github.com/featherhttp/framework),代码如下:也是很简单的实现一个web api服务,三行代码,非常轻量。
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;var app = WebApplication.Create();
app.MapGet("/ping", http=>http.Response.WriteAsJsonAsync(new { message="pong"}));
await app.RunAsync();
项目文件
<Project Sdk="Microsoft.NET.Sdk.Web"><PropertyGroup><TargetFramework>net6.0</TargetFramework></PropertyGroup><ItemGroup><PackageReference Include="FeatherHttp" Version="0.1.83-alpha.g15473de7d1" /></ItemGroup>
</Project>
FeatherHttp现在不在nuget.org上,需要在vs中配置nuget源https://f.feedz.io/featherhttp/framework/nuget/index.json,然后再选择引用。
FeatherHttp,还处在alpha阶段,关于FeatherHttp更多的探索,可参https://github.com/featherhttp/framework。关于FeatherHttp究竟本质是什么,那就在源码中寻找了