安装 Iris

未匹配的标注

假定你已经安装过Google Go。如若没有请遵从Go安装指引后继续

安装

建议使用go1.13+ 最新版本,理由在于可设置代理地址,不用考虑翻墙的问题,也不需要手动从github下载安装相关包。window环境下ide建议用vscode可安装相关插件,linux下用vim可尝试用vim-go插件。

$ go get github.com/kataras/iris@master

示例

创建example.go 文件,代码如下

package main

import (
    "github.com/kataras/iris"

    "github.com/kataras/iris/middleware/logger"
    "github.com/kataras/iris/middleware/recover"
)

func main() {
    app := iris.New()
    app.Logger().SetLevel("debug")
    // 可选项添加两个内置的句柄(handlers)
    // 捕获相对于http产生的异常行为
    app.Use(recover.New())
    //记录请求日志
    app.Use(logger.New())

    // 谓词:   GET
    // 资源: http://localhost:8080
    app.Handle("GET", "/", func(ctx iris.Context) {
        ctx.HTML("<h1>Welcome</h1>")
    })

    // 等价于 app.Handle("GET", "/ping", [...])
    // 谓词:   GET
    // 资源: http://localhost:8080/ping
    app.Get("/ping", func(ctx iris.Context) {
        ctx.WriteString("pong")
    })

    // 谓词:   GET
    // 资源: http://localhost:8080/hello
    app.Get("/hello", func(ctx iris.Context) {
        ctx.JSON(iris.Map{"message": "Hello Iris!"})
    })

    // http://localhost:8080
    // http://localhost:8080/ping
    // http://localhost:8080/hello
    // Run 方法第二个参数为应用的配置参数
    app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
}

效果

$ go run example.go
Now listening on: http://localhost:8080
Application started. Press CTRL+C to shut down.

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
pardon110
讨论数量: 0
发起讨论 查看所有版本


暂无话题~