首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >来自处理程序net/http的Golang缓存结果

来自处理程序net/http的Golang缓存结果
EN

Stack Overflow用户
提问于 2022-01-17 17:51:31
回答 1查看 403关注 0票数 0

无法从缓存中获得结果。只工作请求基地。我需要优化应用程序的许多请求。这是我第一个用歌朗的应用,请原谅我。如何获得缓存结果?

代码语言:javascript
复制
import (
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/ip2location/ip2proxy-go"
    "github.com/patrickmn/go-cache"
)

func main() {
    http.HandleFunc("/", HelloHandler)
    http.ListenAndServe(":8080", nil)
    log.Fatal(http.ListenAndServe(":8080", nil))
}
func HelloHandler(w http.ResponseWriter, r *http.Request) {
    c := cache.New(5*time.Minute, 10*time.Minute)
    ip := r.URL.Query().Get("ip")
    x, found := c.Get(ip)
    if found {
        if x != "0" {
            w.WriteHeader(http.StatusOK)
            fmt.Fprintf(w, "isProxy Cache")
        } else {
            w.WriteHeader(http.StatusNoContent)
            fmt.Fprintf(w, "notProxy Cache")
        }

    } else {
        db, err := ip2proxy.OpenDB("./IP2PROXY-IP-PROXYTYPE-COUNTRY.BIN")
        if err != nil {
            return
        }
        all, err := db.GetAll(ip)
        if err != nil {
            fmt.Print(err)
            return
        }
        isProxy := all["isProxy"]
        c.Set(ip, isProxy, cache.DefaultExpiration)
        if isProxy != "0" {
            w.WriteHeader(http.StatusOK)
            fmt.Fprintf(w, "isProxy ")
        } else {
            w.WriteHeader(http.StatusNoContent)
            fmt.Fprintf(w, "notProxy ")
        }
        db.Close()
    }
}

这:所有“isProxy”返回0,1,-1值。

EN

回答 1

Stack Overflow用户

发布于 2022-01-17 20:45:07

创建一个全局变量并将缓存存储在那里。示例:

代码语言:javascript
复制
var globalCache *cache.Cache

func main() {
    globalCache = cache.New(5*time.Minute, 10*time.Minute)

    http.HandleFunc("/", HelloHandler)
    http.ListenAndServe(":8080", nil)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func HelloHandler(w http.ResponseWriter, r *http.Request) {
    // use globalCache
}

更新:不需要原子,因为cache.Cache在内部创建锁。谢谢你纠正我。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70745556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档