008--Go框架Macaron使用


1、为了使用Macaron,我只是用了一个网站的东西:https://github.com/Unknwon/macaron

go get github.com/Unknwon/macaron

2、Demo启动案例:

    import "github.com/Unknwon/macaron"
    func main() {
        m := macaron.Classic()
        m.Get("/", func() string {
            return "Hello world!"
        })
        m.Get("/hello", func()(int, string) {
            return 400, "Hello world!"
        })
        m.Run()
    }
  • 访问路径:http://localhost:4000/
    3、Macaron可以使用多个处理器(下面就是处理器,允许有多个)
    func() string {
        return "Hello world!"
    }

4、扩展示例

    func main() {
        m := macaron.Classic()
        m.Get("/",myHandler)//这个地方不是函数调用,是将这个地址传递给m.get方法
        m.Get("/hello/*",myHandler)//这个地方不是函数调用,是将这个地址传递给m.get方法
        log.Print("Server is Running.....")
        // 通过标准接口库启实例
        log.Print(http.ListenAndServe("localhost:4000", m))
    }
    // 依赖注入获取服务
    func myHandler(context *macaron.Context) string  {
        return  "this request path is: " + context.Req.RequestURI;
    }

5、(请求上下文)同一个请求,多个处理器之间传递数据

    func main() {
        m := macaron.Classic()
        m.Get("/",handler1 , handler2, handler3)
        log.Print("Server is Running.....")
        log.Print(http.ListenAndServe("localhost:4000", m))
    }
    // 依赖注入获取服务
    func handler1(ctx *macaron.Context) {
        ctx.Data["Num"] = 1
    }
    func handler2(ctx *macaron.Context) {
        ctx.Data["Num"] =  ctx.Data["Num"].(int) + 2
    }
    func handler3(ctx *macaron.Context) string{
        return fmt.Sprintf("Num: %d", ctx.Data["Num"])
    }

6、(请求上下文)获取参数

    func main() {
        m := macaron.Classic()
        m.Get("/", func(ctx *macaron.Context) string{
            return ctx.Query("uid")
        })
        log.Print("Server is Running.....")
        log.Print(http.ListenAndServe("localhost:4000", m))
    }
    func main() {
        m := macaron.Classic()
        m.Get("/", func(ctx *macaron.Context) string{
            return ctx.RemoteAddr()
        })
        log.Print("Server is Running.....")
        log.Print(http.ListenAndServe("localhost:4000", m))
    }

8、处理器让出处理权限,让之后的处理器先处理

    func main() {
        m := macaron.Classic()
        m.Get("/",next1,next2,next3 )
        log.Print("Server is Running.....")
        log.Print(http.ListenAndServe("localhost:4000", m))
    }
    func next1(ctx *macaron.Context){
        fmt.Print("next1-start   ")
        ctx.Next();
        fmt.Print("next1-exit   ")
    }
    func next2(ctx *macaron.Context){
        fmt.Print("next2-start   ")
        ctx.Next();
        fmt.Print("next2-exit   ")
    }
    func next3(ctx *macaron.Context) string{
        fmt.Print("next3-start   ")
        ctx.Next();
        fmt.Print("next3-exit   ")
        return  "hello world"
    }

9、设置cookie

    func main() {
        m := macaron.Classic()
        m.Get("/cookie/set", setCookie)
        m.Get("/cookie/get", getCookie)
        log.Print("Server is Running.....")
        log.Print(http.ListenAndServe("localhost:4000", m))
    }
    func setCookie(ctx *macaron.Context) {
        ctx.SetCookie("user", "enzoism")
        ctx.SetSecureCookie("user2", "enzoism",1000)
        ctx.SetSuperSecureCookie("salt","user3", "enzoism")
    }
    func getCookie(ctx *macaron.Context) string {
        fmt.Println("-----cookie:"+ctx.GetCookie("user"))
        value2,_:=ctx.GetSecureCookie("user2")
        fmt.Println("-----cookie2:"+value2)
        value3,_:=ctx.GetSuperSecureCookie("salt","user3")
        fmt.Println("-----cookie3:"+value3)
        return "Hello World!"
    }

10、响应流(一旦有任何一个处理器响应了,后面的处理器都不在执行了)

    ctx.Resp.Write([]byte("你好,世界!"))
    或者返回 return "Hello World!"

11、请求对象(查看任何请求对象信息)

    return ctx.Req.Method

12、服务静态资源(默认是public,在创建的时候不需要public路径)

    func main() {
        m := macaron.Classic()
        m.Use(macaron.Static("public"))
        log.Print("Server is Running.....")
        log.Print(http.ListenAndServe("localhost:4000", m))
    }

13、容错恢复(可以理解成一种调试手段)

    func main() {
        m := macaron.Classic()
        //macaron.Env =macaron.PROD//生产环境
        // 服务静态文件
        m.Use(macaron.Static("public"))
        m.Get("/panic", panicHandler)
        log.Print("Server is Running.....")
        log.Print(http.ListenAndServe("localhost:4000", m))
    }
    func panicHandler() {
        panic("有钱,任性!")
    }

14、全局日志

    func main() {
        m := macaron.Classic()
        m.Get("/log", logger)
        log.Print("Server is Running.....")
        log.Print(http.ListenAndServe("localhost:4000", m))
    }
    func logger(l *log.Logger) {
        l.Println("打印一行日志")
    }

简化代码

package main

import (
    "github.com/Unknwon/macaron"
    "log"
    "fmt"
)
// 同一个请求,多个处理器之间传递数据
func main() {
    m := macaron.Classic()
    // 服务静态文件
    m.Use(macaron.Static("public"))
    // 在同一个请求中,多个处理器之间可相互传递数据
    m.Get("/", handler1, handler2, handler3)

    // 获取请求参数
    m.Get("/q", queryHandler)

    // 获取远程 IP 地址
    m.Get("/ip", ipHandler)

    // 处理器可以让出处理权限,让之后的处理器先执行
    m.Get("/next", next1, next2, next3)

    // 设置和获取 Cookie
    m.Get("/cookie/set", setCookie)
    m.Get("/cookie/get", getCookie)

    // 响应流
    m.Get("/resp", respHandler)

    // 请求对象
    m.Get("/req", reqHandler)

    // 请求级别容错恢复
    m.Get("/panic", panicHandler)

    // 全局日志器
    m.Get("/log", logger)

    m.Run()
}
// 依赖注入获取服务
func handler1(ctx *macaron.Context) {
    ctx.Data["Num"] = 1
}
func handler2(ctx *macaron.Context) {
    ctx.Data["Num"] =  ctx.Data["Num"].(int) + 2
}
func handler3(ctx *macaron.Context) string{
    return fmt.Sprintf("Num: %d", ctx.Data["Num"])
}
func queryHandler(ctx *macaron.Context) {
    fmt.Println(ctx.Query("uid"))
    fmt.Println(ctx.QueryInt("uid"))
    fmt.Println(ctx.QueryInt64("uid"))
}

func ipHandler(ctx *macaron.Context) string {
    return ctx.RemoteAddr()
}

func next1(ctx *macaron.Context) {
    fmt.Println("位于处理器 1 中")

    ctx.Next()

    fmt.Println("退出处理器 1")
}

func next2(ctx *macaron.Context) {
    fmt.Println("位于处理器 2 中")

    ctx.Next()

    fmt.Println("退出处理器 2")
}

func next3(ctx *macaron.Context) {
    fmt.Println("位于处理器 3 中")

    ctx.Next()

    fmt.Println("退出处理器 3")
}

func setCookie(ctx *macaron.Context) {
    ctx.SetCookie("user", "wuwen")
}

func getCookie(ctx *macaron.Context) string {
    return ctx.GetCookie("user")
}

func respHandler(ctx *macaron.Context) {
    ctx.Resp.Write([]byte("你好,世界!"))
}

func reqHandler(ctx *macaron.Context) string {
    return ctx.Req.Method
}

func panicHandler() {
    panic("有钱,任性!")
}

func logger(l *log.Logger) {
    l.Println("打印一行日志")
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,288评论 19 139
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,838评论 1 92
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 177,295评论 25 709
  • 也不知是多久前的随笔了,应该是忙得焦头烂额的某段时间吧。一起记在这里如果六十年后,有人让我回顾我的人生,我会说什么...
    _人间客阅读 3,315评论 0 0
  • 法安天下德润人心。 ——排列整齐的我 一 年度目标 1.长期 (1)20年: 成为大所律师(例如大成) (2)10...
    勇敢做一个笨笨的自己阅读 1,234评论 0 0

友情链接更多精彩内容