Go實戰--也許最快的Go語言Web框架kataras/iris初識二(TOML、Cache、Cookie)

生命不止,繼續 go go go!!!

昨天介紹了iris框架,介紹瞭如何使用basic認證、Markdown、YAML、Json等:
Go實戰–也許最快的Go語言Web框架kataras/iris初識(basic認證、Markdown、YAML、Json)

繼續跟大家一起學習iris框架.

TOML

什麼是toml?
toml也是一種配置文件,關於golang中配置文件的使用之前也有介紹過:
Go實戰–go語言中使用YAML配置文件(與json、xml、ini對比)

toml是Tom’s Obvious, Minimal Language.的縮寫!

配置文件的使用由來已久,從.ini、XML、JSON、YAML再到TOML,語言的表達能力越來越強,同時書寫便捷性也在不斷提升。 TOML是前GitHub CEO, Tom Preston-Werner,於2013年創建的語言,其目標是成爲一個小規模的易於使用的語義化配置文件格式。TOML被設計爲可以無二義性的轉換爲一個哈希表(Hash table)。

github地址:
https://github.com/toml-lang/toml

Star: 6478

例子

# This is a TOML document.

title = "TOML Example"

[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00 # First class dates

[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
connection_max = 5000
enabled = true

[servers]

  # Indentation (tabs and/or spaces) is allowed but not required
  [servers.alpha]
  ip = "10.0.0.1"
  dc = "eqdc10"

  [servers.beta]
  ip = "10.0.0.2"
  dc = "eqdc10"

[clients]
data = [ ["gamma", "delta"], [1, 2] ]

# Line breaks are OK when inside arrays
hosts = [
  "alpha",
  "omega"
]

看到了吧,不關心空格和縮進。

規範
大小寫敏感
必須是UTF-8編碼
不關心空格、縮進
使用#進行註釋

Go中操作TOML的優秀開源庫
https://github.com/BurntSushi/toml
https://github.com/pelletier/go-toml
具體的之後會專業寫博客介紹

iris讀取toml
新建iris.tml文件:

DisablePathCorrection = false
EnablePathEscape = false
FireMethodNotAllowed = true
DisableBodyConsumptionOnUnmarshal = false
TimeFormat = "Mon, 01 Jan 2006 15:04:05 GMT"
Charset = "UTF-8"

[Other]
    MyServerName = "iris"

main.go:

package main

import (
    "github.com/kataras/iris"
    "github.com/kataras/iris/context"
)

func main() {
    app := iris.New()

    app.Get("/", func(ctx context.Context) {
        ctx.HTML("<b>Hello Iris TOML!</b>")
    })

    app.Run(iris.Addr(":8080"), iris.WithConfiguration(iris.TOML("iris.tml")))
}

Cache

關於緩存,一直沒有跟大家介紹,github上也有很多關於golang的優秀的Cache庫:
patrickmn/go-cache
An in-memory key:value store/cache (similar to Memcached) library for Go, suitable for single-machine applications.

golang/groupcache
groupcache is a caching and cache-filling library, intended as a replacement for memcached in many cases.
同樣,我們以後再進行詳細介紹,這裏我們看看iris中使用Cache:

package main

import (
    "time"

    "github.com/kataras/iris"
    "github.com/kataras/iris/cache"
    "github.com/kataras/iris/context"
)

func main() {
    app := iris.Default()
    cachedHandler := cache.WrapHandler(h, 2*time.Minute)
    app.Get("/hello", cachedHandler)
    app.Run(iris.Addr(":8080"))
}

func h(ctx context.Context) {
    ctx.HTML("<h1> Hello, this should be cached. Every 2 minutes it will be refreshed, check your browser's inspector</h1>")
}

關於cookie,之前也有些文章分享過:
Go實戰–go中使用cookie(The way to go)

iris當然不會缺少cookie的功能了。

package main

import (
    "github.com/kataras/iris"
    "github.com/kataras/iris/context"

    "github.com/kataras/iris/sessions"

    "github.com/gorilla/securecookie"
)

func newApp() *iris.Application {
    app := iris.New()

    cookieName := "mycustomsessionid"
    // AES only supports key sizes of 16, 24 or 32 bytes.
    // You either need to provide exactly that amount or you derive the key from what you type in.
    hashKey := []byte("the-big-and-secret-fash-key-here")
    blockKey := []byte("lot-secret-of-characters-big-too")
    secureCookie := securecookie.New(hashKey, blockKey)

    mySessions := sessions.New(sessions.Config{
        Cookie: cookieName,
        Encode: secureCookie.Encode,
        Decode: secureCookie.Decode,
    })

    app.Get("/", func(ctx context.Context) {
        ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead")
    })
    app.Get("/set", func(ctx context.Context) {

        //set session values
        s := mySessions.Start(ctx)
        s.Set("name", "iris")

        //test if setted here
        ctx.Writef("All ok session setted to: %s", s.GetString("name"))
    })

    app.Get("/get", func(ctx context.Context) {
        // get a specific key, as string, if no found returns just an empty string
        s := mySessions.Start(ctx)
        name := s.GetString("name")

        ctx.Writef("The name on the /set was: %s", name)
    })

    app.Get("/delete", func(ctx context.Context) {
        // delete a specific key
        s := mySessions.Start(ctx)
        s.Delete("name")
    })

    app.Get("/clear", func(ctx context.Context) {
        // removes all entries
        mySessions.Start(ctx).Clear()
    })

    app.Get("/update", func(ctx context.Context) {
        // updates expire date with a new date
        mySessions.ShiftExpiration(ctx)
    })

    app.Get("/destroy", func(ctx context.Context) {
        //destroy, removes the entire session data and cookie
        mySessions.Destroy(ctx)
    })

    return app
}

func main() {
    app := newApp()
    app.Run(iris.Addr(":8080"))
}

瀏覽器訪問:http://localhost:8080/set
http://localhost:8080/get

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章