koa

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 7, 2021 License: MIT Imports: 14 Imported by: 4

README

koa.go

这是一款Golang版本的koa框架,完整的实现了koa.js的中间件机制,洋葱模型,错误优先机制,并且提供了一个抽象的ctx.SetData及ctx.GetData可以向下传递数据。

如何使用

使用起来极其简单,初始化应用对象,添加中间件,设置路由回调,启动程序

  package main

  import "github.com/ryouaki/koa.go"

  func main() {
    app := koa.New() // 初始化服务对象

    app.Use(plugin.Duration) // 使用中间件,这是一个打印当前请求耗费时长的中间件

    // 自定义中间件,为了验证洋葱模型
    app.Use(func(err error, ctx *koa.Context, next koa.NextCb) {
      fmt.Println("test2")
      next(err) // 中间件必须显式调用next使请求进入下一个处理
      fmt.Println("test2")
    }, func(err error, ctx *koa.Context, next koa.NextCb) {
      fmt.Println("test3")
      // 在数据缓存区设置参数,因为golang无法像js那样动态添加属性,所以需要实现一个map[string]interface{}接口缓存数据
      ctx.SetData("test", ctx.Query["c"][0])
      next(nil) // 中间件必须显式调用next使请求进入下一个处理
      fmt.Println("test3")
    })

    // 设置api路由,其中var为url传参
    app.Get("/test/:var/p", func(err error, ctx *koa.Context, next koa.NextCb) {
      fmt.Println("test", ctx.Params) // 打印url参数
      next(nil) // 执行下一个回调
    }, func(err error, ctx *koa.Context, next koa.NextCb) {
      // 将query内的参数回传给客户端
      ctx.Write([]byte(ctx.GetData("test").(string)))
    })

    err := app.Run(8080) // 启动
    if err != nil { // 是否发生错误
      fmt.Println(err)
    }
  }

计时中间件的实现

  package plugin

  import (
    "fmt"
    "time"

    "github.com/ryouaki/koa.go"
  )

  // 中间件和路由api接口实现都必须是func (err error, ctx *koa.Context, next koa.NextCb)类型
  func Duration(err error, ctx *koa.Context, next koa.NextCb) {
    startTime := time.Now() // 开始计时
    next(nil) // 执行后续操作
    d := time.Now().Sub(startTime) // 计算耗时
    // 打印结果
    fmt.Println(time.Date(startTime.Year(),
      startTime.Month(),
      startTime.Day(),
      startTime.Hour(),
      startTime.Minute(),
      startTime.Second(), 0, time.Local),
      ctx.URL,
      "Request cost: ",
      float64(d)/float64(time.Millisecond), "ms")
  }

其中Context提供了多种接口。

  type Context struct {
    Header   map[string]([]string)
    Res      http.ResponseWriter
    Req      *http.Request
    URL      string
    Path     string
    Method   string
    Status   int
    MatchURL string
    Body     []uint8
    Query    map[string]([]string)
    Params   map[string](string)
    IsFinish bool
    data     map[string]interface{}
  }

  // 获取请求中header内容
  func (ctx *Context) GetHeader(key string) []string 
  // 设置响应的header内容
  func (ctx *Context) SetHeader(key string, value string)
  // 读取请求中的Cookie
  func (ctx *Context) GetCookie(key string) *http.Cookie
  // 设置响应的Cookie
  func (ctx *Context) SetCookie(cookie *http.Cookie)
  // 向请求上下文中设置数据
  func (ctx *Context) SetData(key string, value interface{})
  // 从请求上下文中读取缓存数据
  func (ctx *Context) GetData(key string) interface{}
  // 设置session
  func (ctx *Context) SetSession(key string, value interface{}) 
  // 更新session
  func (ctx *Context) UpdateSession(sess map[string]interface{})
  // 获取session
  func (ctx *Context) GetSession() map[string]interface{}
  // 设置响应返回内容
  func (ctx *Context) Write(data []byte) (int, error)
  // 该请求是否已经结束,这个非常重要。一个请求只能由一个地方进行结束。否则无法保证返回内容的可预测性
  func (ctx *Context) IsFinished() bool

组件

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bytes2String

func Bytes2String(bs []uint8) string

Bytes2String func

func GetGoroutineID added in v1.0.1

func GetGoroutineID() uint64

GetGoroutineID func

func GetIPAddr added in v1.0.1

func GetIPAddr() string

GetIPAddr func

func GetMD5ID added in v1.0.1

func GetMD5ID(b []byte) string

GetMD5ID func

Types

type Application

type Application struct {
	// contains filtered or unexported fields
}

Application Object

func New

func New() *Application

New for a koa instance

func (*Application) Delete

func (app *Application) Delete(path string, cbFunc ...Handler) error

Delete func

func (*Application) Get

func (app *Application) Get(path string, cbFunc ...Handler) error

Get func

func (*Application) Head

func (app *Application) Head(path string, cbFunc ...Handler) error

Head func

func (*Application) Options

func (app *Application) Options(path string, cbFunc ...Handler) error

Options func

func (*Application) Patch

func (app *Application) Patch(path string, cbFunc ...Handler) error

Patch func

func (*Application) Post

func (app *Application) Post(path string, cbFunc ...Handler) error

Post func

func (*Application) Put

func (app *Application) Put(path string, cbFunc ...Handler) error

Put func

func (*Application) Run

func (app *Application) Run(port int) error

Run func

func (*Application) RunTLS

func (app *Application) RunTLS(port int, certFile string, keyFile string) error

RunTLS func

func (*Application) ServeHTTP

func (app *Application) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP interface func

func (*Application) Use

func (app *Application) Use(argus ...interface{})

Use func

type Context

type Context struct {
	Header   map[string]([]string)
	Res      http.ResponseWriter
	Req      *http.Request
	URL      string
	Path     string
	Method   string
	Status   int
	MatchURL string
	Body     []uint8
	Query    map[string]([]string)
	Params   map[string](string)
	IsFinish bool
	// contains filtered or unexported fields
}

Context Request

func (*Context) GetCookie

func (ctx *Context) GetCookie(key string) *http.Cookie

GetCookie func

func (*Context) GetData

func (ctx *Context) GetData(key string) interface{}

GetData func

func (*Context) GetHeader

func (ctx *Context) GetHeader(key string) []string

GetHeader func

func (*Context) GetSession

func (ctx *Context) GetSession() map[string]interface{}

GetSession func

func (*Context) IsFinished

func (ctx *Context) IsFinished() bool

IsFinished func

func (*Context) SetCookie

func (ctx *Context) SetCookie(cookie *http.Cookie)

SetCookie func

func (*Context) SetData

func (ctx *Context) SetData(key string, value interface{})

SetData func

func (*Context) SetHeader

func (ctx *Context) SetHeader(key string, value string)

SetHeader func

func (*Context) SetSession

func (ctx *Context) SetSession(key string, value interface{})

SetSession func

func (*Context) UpdateSession

func (ctx *Context) UpdateSession(sess map[string]interface{})

UpdateSession func

func (*Context) Write

func (ctx *Context) Write(data []byte) (int, error)

type Handler

type Handler func(err error, ctx *Context, next NextCb)

Handler Func

type MiddlewareHandler

type MiddlewareHandler struct {
	// contains filtered or unexported fields
}

MiddlewareHandler struct

type NextCb

type NextCb func(err error)

NextCb Func

type RouterHandler

type RouterHandler struct {
	// contains filtered or unexported fields
}

RouterHandler struct

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL