winkey-ngin
TypeScript icon, indicating that this package has built-in type declarations

2.0.5 • Public • Published

NGin 框架

一款轻量级的node框架,集成各种常用请求方法,让你书写api更加优雅、方便,更注重于业务逻辑的书写

初始化

import ngin, { HttpStatusCode } from "ngin";

const app = ngin();

app.listen();

Method

AsciiJSON

使用 AsciiJSON 生成具有转义的非 ASCII 字符的 ASCII-only JSON。

app.GET("/someJSON", function (context) {
  const data = {
    lang: "GO语言",
    tag: "<br>",
  };
  // 输出 : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}
  context.AsciiJSON(HttpStatusCode.OK, data);
});

HTML 渲染

使用 LoadHTMLGlob(), 加载目标目录

app.LoadHTMLGlob("templates/*")
app.GET("/index", function(context) {
  context.HTML(HttpStatusCode.OK, "index.html", gin.H{
    "title": "Main website",
  })
})

templates/index.tmpl

<html>
  <h1>{{ .title }}</h1>
</html>

JSONP

使用 JSONP 向不同域的服务器请求数据。如果查询参数存在回调,则将回调添加到响应体中。

app.GET("/JSONP", function (context) {
  const data = {
    foo: "bar",
  };

  // /JSONP?callback=x
  // 将输出:x({\"foo\":\"bar\"})
  context.JSONP(HttpStatusCode.OK, data);
});

只绑定 url 查询字符串

app.GET("/query", function(context) {
  // 或者简单地使用 ShouldBindQuery 方法自动绑定:
  const form: {
    user
  } = {
    user: null
    password: null
  }
  // 在这种情况下,将自动选择合适的绑定
  context.ShouldBindQuery(form)
  if (form.user == "user" && form.password == "password") {
    context.JSON(200, {"status": "you are logged in"})
  } else {
    context.JSON(401, {"status": "unauthorized"})
  }
})

Multipart/Urlencoded 绑定

app.POST("/login", function(context) {
  // 简单地使用 ShouldBind 方法自动绑定:
  const form: {
    user
  } = {
    user: null
    password: null
  }
  // 在这种情况下,将自动选择合适的绑定
  context.ShouldBind(form)
  if (form.user == "user" && form.password == "password") {
    context.JSON(200, {"status": "you are logged in"})
  } else {
    context.JSON(401, {"status": "unauthorized"})
  }
})

Multipart/Urlencoded 表单

app.POST("/form_post", function (context) {
  const message = context.PostForm("message");
  const nick = context.DefaultPostForm("nick", "anonymous");

  context.JSON(200, {
    status: "posted",
    message: message,
    nick: nick,
  });
});

Query 和 post form

app.POST("/post", function(context) {
  // 获取query上的id值
  const id = context.Query("id")
  // 获取query上的page值,并且赋予默认值
  const page = context.DefaultQuery("page", "0")
  // 获取body上的name值
  const name = context.PostForm("name")
  // 获取body上的message值,并且赋予默认值
  const message = context.DefaultPostForm("message" "1")

  context.JSON(200)
})

JSON/String 渲染

app.GET("/json", function (context) {
  context.JSON(200, {
    name: "李白",
  });
});

app.GET("/string", function (context) {
  context.String(200, "HelloWorld");
});

Redirect

app.GET("/redirect", function (context) {
  context.Redirect(302, "/new-url");
});

上传文件

app.POST("/upload", function(context) {
  // 单文件
  app.maxFilesSize = 1024 * 1024 2
  // FormFile 只在form-data 下有用
  file, _ := context.FormFile("file")
  console.log(file.Filename)

  const = "./" + file.Filename
  // 上传文件至指定的完整文件路径
  context.SaveUploadedFile(file, dst)

  context.String(HttpStatusCode.OK, `${file.Filename} uploaded!`)
})

使用 HTTP 方法

app.GET("/someGet", getting);
app.POST("/somePost", posting);
app.PUT("/somePut", putting);
app.DELETE("/someDelete", deleting);
app.PATCH("/somePatch", patching);
app.HEAD("/someHead", head);
app.OPTIONS("/someOptions", options);

使用中间件

app.Use(logger())
...
function logger() {
  return function(context) {
    if (true) {
      ...
    } else {
      context.end('block')
      // 返回false或者null均可拦截
      return
    }
  }
}

Cookie 操作

import { CookieOptions } from 'ngin'
app.GET('/cookie', (ctx) => {
  // 获取cookie中的某个key
  const uid = ctx.Cookie('uid')

  // 设置cookie options 可选
  ctx.SetCookie('hi', 'bye', {}: CookieOptions)

  ctx.String(200, "Hello World")
})

Binary 操作

app.POST("/binary", async (ctx) => {
  // 可通过Binary获取二进制数据
  const binary = await ctx.Binary();

  ctx.String(200, "Hello World");
});

Context

导出的全局上下文

参数 说明 类型
request 原生request http.IncomingMessage
response 原生response http.ServerResponse & { req: http.IncomingMessage; }
AsciiJSON AsciiJSON 格式输出 (statusCode: HttpStatusCode, result: JSON) => void
JSON JSON 格式输出 (statusCode: HttpStatusCode, result: JSON) => voi
HTML 文件渲染 (statusCode: HttpStatusCode, target?: string, result?: HttpJSONResult) => void
JSONP JSON 格式输出 (statusCode: HttpStatusCode, result: JSON) => void
ShouldBind 筛选body参数 (obj: JSONParams) => void
ShouldBindQuery 筛选query参数 (obj: JSONParams) => void
PostForm 获取post请求参数 (key: string) => any
DefaultPostForm 获取post请求参数,并且赋予默认值 (key: string, val: string) => any
Query 获取get请求 (key: string) => string
DefaultQuery 获取get请求参数,并且赋予默认值 (key: string, val: any) => any
SaveUploadedFile 保存文件 (file: any, path: string) => void
ClientIP 获取请求ip () => string
ClientIPV6 获取请求ipv6地址 () => string
String 输出String (statusCode: HttpStatusCode, str: string) => void
FormFile 获取form-data中的文件信息 (key: string) => void
Cookie 获取cookie (key: string) => string
SetCookie 设置cookie (key: string, value: any, options?: CookieOptions) => void
Binary 获取二进制数据 () => Promise
url 请求url结构体 http.IncomingMessage['url']
statusCode 状态码 http.IncomingMessage['statusCode']
statusMessage 状态信息 http.IncomingMessage['statusMessage']
method 请求方法 http.IncomingMessage['statusMessage']
headers 请求头 http.IncomingMessage['headers']
end 响应输出 http.ServerResponse['end']
writeHead 书写响应头 http.ServerResponse['writeHead']
body body参数 [key: string]: any
query query参数 [key: string]: any

Readme

Keywords

none

Package Sidebar

Install

npm i winkey-ngin

Weekly Downloads

0

Version

2.0.5

License

MIT

Unpacked Size

233 kB

Total Files

13

Last publish

Collaborators

  • ricardom