随记:iris/hero的依赖注入

本文详细介绍使用Iris框架进行依赖注入的三种方法:路径参数注入、结构体注入及Per-Request动态依赖注入,通过具体代码示例展示了如何在实际项目中应用这些技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  package main

    import "github.com/kataras/iris"

    import "github.com/kataras/iris/hero"

    func main() {

        app := iris.Default()

       //1. 根据路径参数进行注入,{to:string},与 func hello(to string),进行注入

        helloHandler := hero.Handler(hello)

        app.Get("/builtin/{to:string}", helloHandler)

        //2. 结构体注入 - 

        hero.Register(&myTestService{

            prefix: "Service: Hello",

        })

        helloServiceHandler := hero.Handler(helloService)

        app.Get("/service/{to:string}", helloServiceHandler)

        //3. Per-Request - Dynamic Dependencies

        hero.Register(func(ctx iris.Context) (form LoginForm) {

            ctx.ReadForm(&form)

            return

        })

        loginHandle := hero.Handler(login)

        app.Post("/dynamic/login", loginHandle)

 

        // listen and serve on http://0.0.0.0:8080.

        app.Run(iris.Addr(":8080"))

    }

    //1. 路径参数注入方式

    func hello(to string) string {

        return "Hello " + to

    }

    //2. 接口注入 

    type Service interface {

        SayHello(to string) string

    }

    type myTestService struct {

        prefix string

    }

    func (s *myTestService) SayHello(to string) string {

        return s.prefix + " " + to

    }

    func helloService(to string, service Service) string {

        return service.SayHello(to)

    }

    //3. 请求注入 - Dynamic Dependencies

    type LoginForm struct {

        Username string

        Password string

    }

    func login(form LoginForm) string {

        return "Hello " + form.Username

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值