jk

package module
v0.0.0-...-a41ec9f Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2023 License: MIT Imports: 13 Imported by: 0

README

jk

介绍

go版本 >= 1.18.0

处理官方net/http的中间件,绑定解析表单,绑定解下请求头,中间件,等等。

安装教程
go get gitee.com/ruige_fun/jk
go get github.com/go-playground/validator/v10
一般用法
package main

import (
	"gitee.com/ruige_fun/jk"
	"github.com/go-playground/validator/v10"
	"log"
	"net/http"
)

func main() {
	jk.SetValidator(validator.New()) //设置表单验证方法

	mdd := jk.NewMiddleware() //创建一个中间件管理
	mdd.Append(printLog) //追加一个中间件处理方法

	http.HandleFunc("/ping", mdd.Get(ping)) //只处理GET请求
	_ = http.ListenAndServe(":8000", nil)
}

type pPing struct {
	ID   uint   `json:"id" url:"id" validate:"required,min=2"`
	Name string `json:"name" url:"name" validate:"required,min=6"`
}

func ping(c jk.Context) {
	var p pPing
	err := c.Req().ReadQuery(&p) //将url查询参数,绑定到 &p
	if err != nil {
		_, _ = c.CWriteJSON(jk.NewRespErr(http.StatusBadRequest, "参数错误").CodeValue())
		return
	}
	err = c.Req().Validator(p) //进行表单校验
	if err != nil {
		_, _ = c.CWriteJSON(jk.NewRespErr(http.StatusBadRequest, "参数错误").CodeValue())
		return
	}
	_, _ = c.CWriteJSON(jk.NewRespOK(p, p.ID).CodeValue())
}

func printLog(c jk.Context) {
	log.Println(c.Req().GetIP(), c.Req().Method(), c.Req().GetUrlPath())
}


请求结果1

http://127.0.0.1:8000/ping?id=1&name=abc2

{"code":400,"msg":"参数错误","data":{"data":null,"other":null}}
请求结果2

http://127.0.0.1:8000/ping?id=2&name=abcdefg

{"code":200,"msg":"","data":{"data":{"id":2,"name":"abcdefg"},"other":2}}

Documentation

Index

Constants

View Source
const (
	ContentTypeDownload = `application/force-download` //文件下载

	ContentTypeDefault = `text/plain; charset=utf-8`              //文本
	ContentTypeJSON    = `application/json; charset=utf-8`        //json
	ContentTypeHTML    = `text/html; charset=utf-8`               //HTML
	ContentTypeXJS     = `application/x-javascript;charset=utf-8` //JavaScript
	ContentTypeJS      = `text/javascript; charset=utf-8`         //JavaScript
	ContentTypeCSS     = `text/css; charset=utf-8`                //CSS

	ContentTypeImageJPEG = `image/jpeg`   //jpeg图片
	ContentTypeImageJPG  = `image/jpeg`   //jpg图片
	ContentTypeImagePNG  = `image/png`    //png图片
	ContentTypeImageWEBP = `image/webp`   //webp图片
	ContentTypeImageGIF  = `image/gif`    //gif图片
	ContentTypeImageICON = `image/x-icon` //icon图标

	ContentTypeImageOctetStream = `application/octet-stream` //八位字节流
)
View Source
const (
	TagQuery   = `url`
	TagForm    = `form`
	TagHeaders = `header`
	TagParams  = `param`
)

Variables

This section is empty.

Functions

func CORS

func CORS(c Context)

CORS 允许跨域请求中间件

func SetValidator

func SetValidator(v Validator)

SetValidator 设置表单验证的方法,如果没有进行设置,则不会进行表单验证。

Types

type Context

type Context interface {
	// Writer 原生http.ResponseWriter
	Writer() http.ResponseWriter

	// Request 原生*http.Request
	Request() *http.Request

	// SetStatusCode 设置响应状态码
	SetStatusCode(code int)

	// Values 上下文的key-value
	Values() Values

	// Req 与请求有关信息解析与绑定
	Req() Request

	// Stop 中间件里面使用,停止后续步骤的执行。
	Stop()

	// HeaderClean 清空已设置的响应头
	HeaderClean()
	// HeaderSet 设置响应头
	HeaderSet(key, value string)
	// HeaderDel 删除已设置的响应头
	HeaderDel(key string)
	// HeaderGet 获取已设置的响应头
	HeaderGet(key string) string

	// WriteClean 清空已写入的响应体
	WriteClean()
	// Write 写入响应体
	Write(body []byte)
	// WriteString 写入响应体
	WriteString(body string)
	// WriteJSON 写入响应体,将obj进行json编码后写入响应体
	WriteJSON(obj any) (int, error)
	// CWrite 写入响应体并且设置响应状态码
	CWrite(code int, body []byte)
	// CWriteString 写入响应体并且设置响应状态码
	CWriteString(code int, body string)
	// CWriteJSON 写入响应体并且设置响应状态码,将obj进行json编码后写入响应体
	CWriteJSON(code int, obj any) (int, error)

	// ResponseBody 返回当前已写入的响应体所有内容
	ResponseBody() string
	// contains filtered or unexported methods
}

type HandlerFunc

type HandlerFunc func(Context)

type Middleware

type Middleware interface {
	Clone() Middleware

	Append(HandlerFunc)
	Use(HandlerFunc)

	HandlerFunc(HandlerFunc) http.HandlerFunc

	Any(HandlerFunc) http.HandlerFunc
	Get(HandlerFunc) http.HandlerFunc
	Post(HandlerFunc) http.HandlerFunc
	Delete(HandlerFunc) http.HandlerFunc
	Put(HandlerFunc) http.HandlerFunc
	Head(HandlerFunc) http.HandlerFunc
	Patch(HandlerFunc) http.HandlerFunc
	Connect(HandlerFunc) http.HandlerFunc
	Options(HandlerFunc) http.HandlerFunc
	Trace(HandlerFunc) http.HandlerFunc

	MethodList() HandlerFuncList
	// contains filtered or unexported methods
}

func NewMiddleware

func NewMiddleware() Middleware

type Request

type Request interface {
	// Method 请求方法
	Method() string
	// GetIP 获取相对真实的IP
	GetIP() string
	// GetUrlPath 获取请求路径
	GetUrlPath() string

	// GetBody 获取请求体
	GetBody() ([]byte, error)

	// ReadQuery 读取url的查询参数,并且绑定到obj
	ReadQuery(obj any) error
	// ReadAllForm 读取url的查询参数和pos表单,并且绑定到obj
	ReadAllForm(obj any) error
	// ReadPostForm 读取post表单的查询参数,并且绑定到obj
	ReadPostForm(obj any) error
	// ReadHeaders 读取请求头,并且绑定到obj
	ReadHeaders(obj any) error
	// ReadBody 读取请求体,并且绑定到obj;支持post表单、json。
	ReadBody(obj any) error
	// ReadJSON 读取请求头,并且json解码到obj;
	ReadJSON(obj any) error

	// ReadQueryV 读取url的查询参数,并且绑定到obj;最后进行表单校验。
	ReadQueryV(obj any) error
	// ReadAllFormV 读取url的查询参数和pos表单,并且绑定到obj;最后进行表单校验。
	ReadAllFormV(obj any) error
	// ReadPostFormV 读取post表单的查询参数,并且绑定到obj;最后进行表单校验。
	ReadPostFormV(obj any) error
	// ReadHeadersV 读取请求头,并且绑定到obj;最后进行表单校验。
	ReadHeadersV(obj any) error
	// ReadBodyV 读取请求体,并且绑定到obj;支持post表单、json;最后进行表单校验。
	ReadBodyV(obj any) error
	// ReadJSONV 读取请求头,并且json解码到obj;最后进行表单校验。
	ReadJSONV(obj any) error

	// Validator 表单校验
	Validator(obj any) error
	// contains filtered or unexported methods
}

type Resp

type Resp interface {
	SetCode(code int)
	SetMsg(msg string)
	SetData(data any)
	SetOther(other any)

	ToJson() []byte
	Value() any              //返回可以JSON编码的对象
	CodeValue() (int, any)   //返回http状态码code和可以JSON编码的对象
	CodeValueOK() (int, any) //返回http状态码200和可以JSON编码的对象
}

func NewResp

func NewResp(code int, msg string, data any, other any) Resp

NewResp 创建一个标准的响应体结构

func NewRespErr

func NewRespErr(code int, msg string) Resp

NewRespErr 创建一个标准的响应体结构,默认无Data

func NewRespOK

func NewRespOK(dataOther ...any) Resp

NewRespOK 创建一个标准的响应体结构,默认code = 200

type Validator

type Validator interface {
	Struct(interface{}) error
}

type Values

type Values interface {
	Set(string, any)
	Get(string, ...any) (any, bool)

	GetString(string, ...string) (string, bool)

	GetInt(string, ...int) (int, bool)
	GetInt8(string, ...int8) (int8, bool)
	GetInt16(string, ...int16) (int16, bool)
	GetInt32(string, ...int32) (int32, bool)
	GetInt64(string, ...int64) (int64, bool)
	GetUint(string, ...uint) (uint, bool)
	GetUint8(string, ...uint8) (uint8, bool)
	GetUint16(string, ...uint16) (uint16, bool)
	GetUint32(string, ...uint32) (uint32, bool)
	GetUint64(string, ...uint64) (uint64, bool)

	GetFloat32(string, ...float32) (float32, bool)
	GetFloat64(string, ...float64) (float64, bool)

	GetBool(string, ...bool) (bool, bool)

	GetTime(string, ...time.Time) (time.Time, bool)
}

Values 上下文存储信息 此接口的设计,参考 github.com/kataras/iris/v12/core/memstore 。

Jump to

Keyboard shortcuts

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