V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
fumeboy
V2EX  ›  Go 编程语言

分享一下我根据泛型语法造的 web 轮子

  •  
  •   fumeboy · 2022-06-27 13:39:39 +08:00 · 1115 次点击
    这是一个创建于 641 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码在 https://github.com/fumeboy/nji

    主要是配合泛型和反射,将类型作为元信息自动构造 HTTP handler 的参数注入器 和 URL ,同时支持对参数格式进行校验。

    比如定义如下结构体表明要自动注入 A B 两个参数:

    type get_query_params struct {
    	A plugins.QueryParam[any]
    	B plugins.QueryParam[any]
    }
    func (v *get_query_params) Handle(c *nji.Context) {
    	c.Writer.WriteString(v.A.Value + v.B.Value)
    }
    

    如果要做参数校验:

    type get_query_params struct {
    	A plugins.QueryParam[schema.Must] // 单校验器
    	B plugins.QueryParam[struct { // 多校验器
    		schema.Must // 必须非空
    		schema.IsPhoneNumber
        }]
    }
    

    如果要避免手写 URL:

    type BaseRoute struct {
    	nji.Route[route.ANY, route.ROOT] `a_prefix`
    }
    
    type get_query_params struct {
    	nji.Route[route.GET, BaseRoute] // output URL = `/a_prefix/get_query_params`
    
    	A plugins.QueryParam[schema.Must]
    	B plugins.QueryParam[struct {
    		schema.Must
    		schema.IsPhoneNumber
        }]
    }
    
    1 条回复    2022-08-10 09:04:49 +08:00
    kkeep
        1
    kkeep  
       2022-08-10 09:04:49 +08:00 via Android
    有点意思
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2806 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 15:01 · PVG 23:01 · LAX 08:01 · JFK 11:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.