Iris 框架安裝步驟

declandragon發表於2019-10-28

前言

今天準備開始使用 Go 開發,用 iris 框架,記錄安裝過程。

環境

win10 專業版 1903

Go 1.13.3

準備工作

  • 配置host
# 感覺有點玄學,不知道有沒有起到實際作用
192.30.253.113 github.com
151.101.185.194 github.global.ssl.fastly.net

安裝步驟

  • $GOPATH 目錄下執行 go get -v github.com/kataras/iris 下載時間可能有點久
  • 建立目錄 $GOPATH\src\golang.org\x ,在該目錄下執行
git clone git@github.com:golang/net.git
git clone git@github.com:golang/crypto.git
git clone git@github.com:golang/text.git

我安裝完成之後是這樣的,有幾個是之前安裝

Iris 框架安裝步驟

測試

$GOPATH 目錄下新建 iris資料夾 ,新建 server.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.Use(recover.New())
    app.Use(logger.New())
    //輸出html
    // 請求方式: GET
    // 訪問地址: http://localhost:8080/welcome
    app.Handle("GET", "/welcome", 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")
    })
    //輸出json
    // 請求方式: GET
    // 請求地址: http://localhost:8080/hello
    app.Get("/hello", func(ctx iris.Context) {
        ctx.JSON(iris.Map{"message": "Hello Iris!"})
    })
    app.Run(iris.Addr(":8080")) //8080 監聽埠
}

執行 go run server.go

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

在瀏覽器中訪問

http://localhost:8080/welcome
http://localhost:8080/hello
http://localhost:8080/ping

如下圖

Iris 框架安裝步驟

Iris 框架安裝步驟

Iris 框架安裝步驟

終端輸出

[INFO] 2019/10/28 19:17 200   0s ::1 GET /welcome
[INFO] 2019/10/28 19:17 200   0s ::1 GET /hello
[INFO] 2019/10/28 19:17 200   0s ::1 GET /ping

如果有什麼錯誤的地方,希望大家能指出,一起學習進步。

相關文章