github.com/blend/go-sdk@v1.20220411.3/examples/cache/main.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package main 9 10 import ( 11 "os" 12 "time" 13 14 "github.com/blend/go-sdk/cache" 15 "github.com/blend/go-sdk/ex" 16 "github.com/blend/go-sdk/graceful" 17 "github.com/blend/go-sdk/logger" 18 "github.com/blend/go-sdk/uuid" 19 "github.com/blend/go-sdk/web" 20 "github.com/blend/go-sdk/webutil" 21 ) 22 23 func getData() (interface{}, error) { 24 time.Sleep(500 * time.Millisecond) 25 var output []string 26 for x := 0; x < 1024; x++ { 27 output = append(output, uuid.V4().String()) 28 } 29 return output, nil 30 } 31 32 func main() { 33 log := logger.Prod() 34 log.Disable(webutil.FlagHTTPRequest) // disable noisey events. 35 app, err := web.New( 36 web.OptConfigFromEnv(), 37 web.OptLog(log), 38 web.OptUse(web.GZip), // NOTE: as of v3.0.0 gzip response compression middleware is not enabled by default, you _must_ enable it explicitly. 39 web.OptShutdownGracePeriod(time.Second), 40 ) 41 if err != nil { 42 log.Fatal(err) 43 os.Exit(1) 44 } 45 app.PanicAction = func(_ *web.Ctx, r interface{}) web.Result { 46 return web.Text.InternalError(ex.New(r)) 47 } 48 49 lc := cache.New(cache.OptSweepInterval(500 * time.Millisecond)) 50 go lc.Start() 51 52 app.GET("/stats", func(r *web.Ctx) web.Result { 53 return web.JSON.Result(lc.Stats()) 54 }) 55 56 app.GET("/item/:id", func(r *web.Ctx) web.Result { 57 data, _, _ := lc.GetOrSet( 58 web.StringValue(r.RouteParam("id")), 59 getData, 60 cache.OptValueTTL(30*time.Second), 61 cache.OptValueOnRemove(func(key interface{}, reason cache.RemovalReason) { 62 log.Infof("cache item removed: %s %v", key, reason) 63 }), 64 ) 65 return web.JSON.Result(data) 66 }) 67 68 if err := graceful.Shutdown(app); err != nil { 69 log.Fatal(err) 70 os.Exit(1) 71 } 72 }