1 Star 0 Fork 0

瑞哥 / jk

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

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}}
MIT License Copyright (c) 2023 瑞哥 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

处理官方net/http的中间件,绑定解析表单,绑定解下请求头,中间件,等等。 展开 收起
Go
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/ruige_fun/jk.git
git@gitee.com:ruige_fun/jk.git
ruige_fun
jk
jk
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891