golang httpcache 一個方便的http cache 處理包


httpcache 是一個golang http cache 協議的大部分實現,使用簡單,而且支持不同的后端緩存模型(memory,disk,redis....)
以下是一個參考代碼

項目結構

  • go mod
 
module appdemo
go 1.15
require (
    github.com/google/btree v1.0.0 // indirect
    github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirect
    github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
)
  • main.go
package main
import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "time"
    "github.com/gregjones/httpcache"
    "github.com/gregjones/httpcache/diskcache"
)
const (
    // IMAGEURL IMAGEURL
    IMAGEURL = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1604414122241&di=89d0b74128a600ebf054830beabf3535&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fwallpaper%2F1307%2F10%2Fc3%2F23153395_1373426315898.jpg"
)
func main() {
    diskcache := diskcache.New("data")
    client := &http.Client{
        Transport: &httpcache.Transport{
            Cache:               diskcache,
            MarkCachedResponses: true,
        },
        Timeout: time.Second,
    }
    resp, err := client.Get(IMAGEURL)
    if err != nil {
        log.Println("some wrong")
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
    fmt.Println(string(body))
}
  • 效果

 

 

說明

使用httpcache 的好處很明顯,離線網絡以及對於符合http cache 協議規范的可以進行多種cache,減少后端服務的請求以及提供
自身服務的可靠性以及穩定性,對於以上的diskcache使用了diskv,diskv 是一個很不錯的基於磁盤的key,value 存儲包

參考資料

https://github.com/gregjones/httpcache
https://github.com/peterbourgon/diskv


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM