V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
fumeboy

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

  •  
  •   fumeboy · Jun 27, 2022 · 1530 views
    This topic created in 1401 days ago, the information mentioned may be changed or developed.

    代码在 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 replies    2022-08-10 09:04:49 +08:00
    kkeep
        1
    kkeep  
       Aug 10, 2022 via Android
    有点意思
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1428 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 16:57 · PVG 00:57 · LAX 09:57 · JFK 12:57
    ♥ Do have faith in what you're doing.