烂翻译系列之Iris——新手入门——快速开始

Quick start  快速开始


Create an empty file, let's assume its name is example.go, then open it and copy-paste the below code.

创建一个空文件,假设它的名字为example.go,然后打开它并复制粘贴以下代码。

package main

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

func main() {
    app := iris.Default()
    app.Use(myMiddleware)

    app.Handle("GET", "/ping", func(ctx iris.Context) {
        ctx.JSON(iris.Map{"message": "pong"})
    })

    // Listens and serves incoming http requests on http://localhost:8080.
    // 监听访问http://localhost:8080的请求并为其提供服务
    app.Listen(":8080") 
}

func myMiddleware(ctx iris.Context) {
ctx.Application().Logger().Infof(
"Runs before %s", ctx.Path())
ctx.Next()
}

Start a terminal session and execute the following.

打开一个终端并执行以下命令。

# run example.go and visit http://localhost:8080/ping on browser
$ go run example.go

Show me more!  更多

Let's take a small overview of how easy is to get up and running.

让我们领略一下起动并运行是多么的容易呀。

package main

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

func main() {
    app := iris.New()
    // Load all templates from the "./views" folder where extension is ".html" and parse them using the standard `html/template` package.
//加载“./views”文件夹下所有扩展名为“.html”的模板文件并使用标准的‘html/template’包解析它们
app.RegisterView(iris.HTML("./views", ".html")) // Method(函数): GET // Resource(资源): http://localhost:8080 app.Get("/", func(ctx iris.Context) { // Bind: {{.message}} with "Hello world!" 将表达式{{.message}}和数据“Hello world!”绑定 ctx.ViewData("message", "Hello world!") // Render template file: ./views/hello.html 呈现模板文件:./views/hello.html ctx.View("hello.html") }) // Method(函数): GET // Resource(资源): http://localhost:8080/user/42 // // Need to use a custom regexp instead? // Easy; // Just mark the parameter's type to 'string' // which accepts anything and make use of // its `regexp` macro function, i.e: // app.Get("/user/{id:string regexp(^[0-9]+$)}")
//想要使用自定义正则表达式代替?容易;只需标记参数为字符串型(可以接收任何内容)并使用‘regexp’宏函数
app.Get("/user/{id:uint64}", func(ctx iris.Context) { userID, _ := ctx.Params().GetUint64("id") ctx.Writef("User ID: %d", userID) }) // Start the server using a network address. 启动服务 app.Listen(":8080") }
<!-- file: ./views/hello.html 文件:./views/hello.html-->
<html>
<head>
    <title>Hello Page</title>
</head>
<body>
    <h1>{{.message}}</h1>
</body>
</html>

Wanna re-start your app automatically when source code changes happens? Install the iris-cli tool and execute iris-cli run instead of go run main.go.

当修改了源码后,想要自动重启你的应用?安装iris-cli工具并以执行iris-cli run命令来代替执行go run 命令。

At the next section we will learn more about Routing.

下一节我们将学习更多路由相关内容。

posted @ 2021-12-13 10:10  菜鸟吊思  阅读(330)  评论(0)    收藏  举报