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

原文地址:https://www.cnblogs.com/rongfengliang/p/13934444.html