Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

darkweak/souin

Repository files navigation

Souin logo

Souin Table of Contents

  1. Souin reverse-proxy cache description
  2. Configuration
    2.1.Required configuration
    2.1.1.Souin as plugin
    2.1.2.Souin out-of-the-box
    2.2.Optional configuration
  3. Storages
  4. APIs
    4.1.Prometheus API
    4.2.Souin API
    4.3.Security API
  5. Diagrams
    5.1.Sequence diagram
  6. Cache systems
  7. GraphQL
  8. Plugins
    8.1.Beego filter
    8.2.Caddy module
    8.3.Chi middleware
    8.4.Dotweb middleware
    8.5.Echo middleware
    8.6.Fiber middleware
    8.7.Gin middleware
    8.8.Goa middleware
    8.9.Go-zero middleware
    8.10.Goyave middleware
    8.11.Hertz middleware
    8.12.Kratos filter
    8.13.Roadrunner middleware
    8.14.Skipper filter
    8.15.Træfik plugin
    8.16.Tyk plugin
    8.17.Webgo middleware
  9. Credits

Souin HTTP cache

Project description

Souin is a new HTTP cache system suitable for every reverse-proxy. It can be either placed on top of your current reverse-proxy whether it's Apache, Nginx or as plugin in your favorite reverse-proxy like Træfik, Caddy or Tyk.
Since it's written in go, it can be deployed on any server and thanks to the docker integration, it will be easy to install on top of a Swarm, or a kubernetes instance.
It's RFC compatible, supporting Vary, request coalescing, stale cache-control and other specifications related to theRFC-7234.
It supports the newly written RFCs (currently in draft)http-cache-groups andhttp-invalidation.
It also supports theCache-Status HTTP response header, the YKey group such as Varnish, theTargeted HTTP Cache Control RFC, .
It supports the ESI tags, thanks to thego-esi package.

Warning

Sincev1.7.0 Souin implements only one storage. If you need a specific storage you have to take it fromthe storages repository and add it either in your code, during the build otherwise.
(e.g. with otter using caddy) You have to build your caddy module with the desired storagexcaddy build --with github.com/darkweak/souin/plugins/caddy --with github.com/darkweak/storages/otter/caddy and configure otter in your Caddyfile/JSON configuration file.
See thestorages section or thedocumentation website about the storages.

Configuration

The configuration file is store at/anywhere/configuration.yml. You can supply your own as long as you use one of the minimal configurations below.

Required configuration

Souin as plugin

default_cache:# Requiredttl:10s# Default TTL

Souin out-of-the-box

default_cache:# Requiredttl:10s# Default TTLreverse_proxy_url:'http://traefik'# If it's in the same network you can use http://your-service, otherwise just use https://yourdomain.com
KeyDescriptionValue example
default_cache.ttlDuration to cache request (in seconds)10

Besides, it's highly recommended to setdefault_cache.default_cache_control (see it below) to avoid undesired caching for responses withoutCache-Control header.

Optional configuration

# /anywhere/configuration.ymlapi:basepath:/souin-api# Default route basepath for every additional APIs to avoid conflicts with existing routesprometheus:# Prometheus exposed metricsbasepath:/anything-for-prometheus-metrics# Change the prometheus endpoint basepathsouin:# Souin listing keys and cache managementbasepath:/anything-for-souin# Change the souin endpoint basepathcache_keys:'.*\.css':disable_body:true# Prevent the body from being used in the cache keydisable_host:true# Prevent the host from being used in the cache keydisable_method:true# Prevent the method from being used in the cache keydisable_query:true# Prevent the query string from being used in the cache keydisable_scheme:true# request scheme the query string from being used in the cache keydisable_vary:true# Prevent the varied headers string from being used in the cache keyhash:true# Hash the cache key instead of a plaintext onehide:true# Prevent the cache key to be in the response Cache-Status headerheaders:# Add headers to the key      -Authorization# Add the header value in the key      -Content-Type# Add the header value in the keytemplate:"{http.request.method}-{http.request.host}-{http.request.path}"# Use caddy placeholders to create the key (when this option is enabled, disable_* directives are skipped)cdn:# If Souin is set after a CDN fill these informationsapi_key:XXXX# Your provider API key if mandatoryprovider:fastly# The provider placed before Souin (e.g. fastly, cloudflare, akamai, varnish)strategy:soft# The strategy to purge the CDN cache based on tags (e.g. soft, hard)dynamic:true# If true, you'll be able to add custom keys than the ones defined under the surrogate_keys keydefault_cache:allowed_http_verbs:# Allowed HTTP verbs to cache (default GET, HEAD).    -GET    -POST    -HEADallowed_additional_status_codes:# Allowed additional HTTP status code to cache.    -202    -400cache_name:Souin# Override the cache name to use in the Cache-Status headerdistributed:true# Use Olric or Etcd distributed storagekey:disable_body:true# Prevent the body from being used in the cache keydisable_host:true# Prevent the host from being used in the cache keydisable_method:true# Prevent the method from being used in the cache keydisable_query:true# Prevent the query string from being used in the cache keydisable_scheme:true# Prevent the request scheme string from being used in the cache keydisable_vary:true# Prevent the varied headers string from being used in the cache keyhash:true# Hash the cache key instead of a plaintext onehide:true# Prevent the cache key to be in the response Cache-Status headerheaders:# Add headers to the key      -Authorization# Add the header value in the key      -Content-Type# Add the header value in the keytemplate:"{http.request.method}-{http.request.host}-{http.request.path}"# Use caddy placeholders to create the key (when this option is enabled, disable_* directives are skipped)etcd:# If distributed is set to true, you'll have to define either the etcd or olric sectionconfiguration:# Configure directly the Etcd clientendpoints:# Define multiple endpoints        -etcd-1:2379# First node        -etcd-2:2379# Second node        -etcd-3:2379# Third nodemode:bypass# Override the RFC respect.olric:# If distributed is set to true, you'll have to define either the etcd or olric sectionurl:'olric:3320'# Olric serverregex:exclude:'ARegexHere'# Regex to exclude from cachestale:1000s# Stale durationtimeout:# Timeout configurationbackend:10s# Backend timeout before returning an HTTP unavailable responsecache:20ms# Cache provider (badger, etcd, nutsdb, olric, depending the configuration you set) timeout before returning a missttl:1000s# Default TTLdefault_cache_control:no-store# Set default value for Cache-Control response header if not set by upstreamlog_level:INFO# Logs verbosity [ DEBUG, INFO, WARN, ERROR, DPANIC, PANIC, FATAL ], case do not matterssl_providers:# The {providers}.json to use  -traefikurls:'https:\/\/domain.com\/first-.+':# First regex route configurationttl:1000s# Override default TTL'https:\/\/domain.com\/second-route':# Second regex route configurationttl:10s# Override default TTL'https?:\/\/mysubdomain\.domain\.com':# Third regex route configurationttl:50s# Override default TTL'default_cache_control:public, max-age=86400# Override default default Cache-Controlykeys:The_First_Test:headers:Content-Type:'.+'The_Second_Test:url:'the/second/.+'The_Third_Test:The_Fourth_Test:surrogate_keys:The_First_Test:headers:Content-Type:'.+'The_Second_Test:url:'the/second/.+'The_Third_Test:The_Fourth_Test:
KeyDescriptionValue example
apiThe cache-handler API cache management
api.basepathBasePath for all APIs to avoid conflicts/your-non-conflicting-route

(default: /souin-api)
api.{api}.enable(DEPRECATED) Enable the API with related routestrue

(default: true if you define the api name, false then)
api.{api}.security(DEPRECATED) Enable the JWT Authentication token verificationtrue

(default: false)
api.security.secret(DEPRECATED) JWT secret keyAny_charCanW0rk123
api.security.users(DEPRECATED) Array of authorized users with username x password combo- username: admin

password: admin
api.souin.securityEnable JWT validation to access the resourcetrue

(default: false)
cache_keysDefine the key generation rules for each URI matching the key regexp
cache_keys.{your regexp}Regexp that the URI should match to override the key generation.+\.css
cache_keys.{your regexp}.disable_bodyDisable the body part in the key matching the regexp (GraphQL context)true

(default: false)
cache_keys.{your regexp}.disable_hostDisable the host part in the key matching the regexptrue

(default: false)
cache_keys.{your regexp}.disable_methodDisable the method part in the key matching the regexptrue

(default: false)
cache_keys.{your regexp}.disable_queryDisable the query string part in the key matching the regexptrue

(default: false)
cache_keys.{your regexp}.disable_schemeDisable the request scheme string part in the key matching the regexptrue

(default: false)
cache_keys.{your regexp}.disable_varyDisable the vary string part in the key matching the regexptrue

(default: false)
cache_keys.{your regexp}.hashHash the key matching the regexptrue

(default: false)
cache_keys.{your regexp}.headersAdd headers to the key matching the regexp- Authorization

- Content-Type

- X-Additional-Header
cache_keys.{your regexp}.hidePrevent the key from being exposed in theCache-Status HTTP response headertrue

(default: false)
cdnThe CDN management, if you use any cdn to proxy your requests Souin will handle that
cdn.providerThe provider placed before Souinakamai

fastly

souin
cdn.api_keyThe api key used to access to the providerXXXX
cdn.dynamicEnable the dynamic keys returned by your backend applicationfalse

(default: true)
cdn.emailThe api key used to access to the provider if required, depending the providerXXXX
cdn.hostnameThe hostname if required, depending the providerdomain.com
cdn.networkThe network if required, depending the provideryour_network
cdn.strategyThe strategy to use to purge the cdn cache, soft will keep the content as a stale resourcehard

(default: soft)
cdn.service_idThe service id if required, depending the provider123456_id
cdn.zone_idThe zone id if required, depending the provideranywhere_zone
default_cache.allowed_http_verbsThe HTTP verbs to support cache- GET

- POST

(default: GET, HEAD)
default_cache.allowed_additional_status_codesThe additional HTTP status code to support cache- 200

- 404
default_cache.badgerConfigure the Badger cache storage
default_cache.badger.pathConfigure Badger with a file/anywhere/badger_configuration.json
default_cache.badger.configurationConfigure Badger directly in the Caddyfile or your JSON caddy configurationSee the Badger configuration for the options
default_cache.default_cache_controlSet the default value ofCache-Control response header if not set by upstream (Souin treats emptyCache-Control aspublic if omitted)no-store
default_cache.etcdConfigure the Etcd cache storage
default_cache.etcd.configurationConfigure Etcd directly in the Caddyfile or your JSON caddy configurationSee the Etcd configuration for the options
default_cache.etcd.urlSet the Etcd cluster endpointhttp://etcd1:2379,http://etcd2:2379
default_cache.keyOverride the key generation with the ability to disable unecessary parts
default_cache.key.disable_bodyDisable the body part in the key (GraphQL context)true

(default: false)
default_cache.key.disable_hostDisable the host part in the keytrue

(default: false)
default_cache.key.disable_methodDisable the method part in the keytrue

(default: false)
default_cache.key.disable_queryDisable the query string part in the keytrue

(default: false)
default_cache.key.disable_schemeDisable the request scheme string part in the keytrue

(default: false)
default_cache.key.disable_varyDisable the request vary string part in the keytrue

(default: false)
default_cache.key.hashHash the key name in the storagetrue

(default: false)
default_cache.key.headersAdd headers to the key matching the regexp- Authorization

- Content-Type

- X-Additional-Header
default_cache.key.hidePrevent the key from being exposed in theCache-Status HTTP response headertrue

(default: false)
default_cache.key.templateUse caddy placeholders to create the key (when this option is enabled, disable_* directives are skipped)Placeholders documentation
default_cache.max_cacheable_body_bytesSet the maximum size (in bytes) for a response body to be cached (unlimited if omited)1048576 (1MB)
default_cache.modeRFC respect tweakingOne ofbypassbypass_requestbypass_responsestrict (defaultstrict)
default_cache.natsConfigure the Nats cache storage
default_cache.nats.urlSet the Nats cluster endpointnats://127.0.0.1:4222,nats://127.0.0.1:4223
default_cache.nats.configurationConfigure Nats directly in the Caddyfile or your JSON caddy configurationSee the Nats configuration for the options
default_cache.nutsConfigure the Nuts cache storage
default_cache.nuts.pathSet the Nuts file path storage/anywhere/nuts/storage
default_cache.nuts.configurationConfigure Nuts directly in the Caddyfile or your JSON caddy configurationSee the Nuts configuration for the options
default_cache.olricConfigure the Olric cache storage
default_cache.olric.pathConfigure Olric with a file/anywhere/olric_configuration.json
default_cache.olric.configurationConfigure Olric directly in the Caddyfile or your JSON caddy configurationSee the Olric configuration for the options
default_cache.otterConfigure the Otter cache storage
default_cache.otter.configurationConfigure Otter directly in the Caddyfile or your JSON caddy configuration
default_cache.otter.configuration.sizeSet the size of the pool in Otter999999 (default10000)
default_cache.port.{web,tls}The device's local HTTP/TLS port that Souin should be listening onRespectively80 and443
default_cache.redisConfigure the Redis cache storage
default_cache.redis.urlSet the Redis cluster endpointnats://127.0.0.1:4222,nats://127.0.0.1:4223
default_cache.redis.configurationConfigure Redis directly in the Caddyfile or your JSON caddy configurationSee the Go-redis configuration for the options orSee the Rueidis configuration for the options
default_cache.regex.excludeThe regex used to prevent paths being cached^[A-z]+.*$
default_cache.staleThe stale duration25m
default_cache.timeoutThe timeout configuration
default_cache.timeout.backendThe timeout duration to consider the backend as unreachable10s
default_cache.timeout.cacheThe timeout duration to consider the cache provider as unreachable10ms
default_cache.ttlThe TTL duration120s
log_levelThe log levelOne of DEBUG, INFO, WARN, ERROR, DPANIC, PANIC, FATAL it's case insensitive
reverse_proxy_urlThe reverse-proxy's instance URL (Apache, Nginx, Træfik...)-http://yourservice (Container way)
http://localhost:81 (Local way)
http://yourdomain.com:81 (Network way)
ssl_providersList of your providers handling certificates- traefik

- nginx

- apache
urls.{your url or regex}List of your custom configuration depending each URL or regex'https://yourdomain.com'
urls.{your url or regex}.ttlOverride the default TTL if defined90s

10m
urls.{your url or regex}.default_cache_controlOverride the default defaultCache-Control if definedpublic, max-age=86400
surrogate_keys.{key name}.headersHeaders that should match to be part of the surrogate key groupAuthorization: ey.+

Content-Type: json
surrogate_keys.{key name}.headers.{header name}Header name that should be present a match the regex to be part of the surrogate key groupContent-Type: json
surrogate_keys.{key name}.urlUrl that should match to be part of the surrogate key group.+
ykeys.{key name}.headers(DEPRECATED) Headers that should match to be part of the ykey groupAuthorization: ey.+

Content-Type: json
ykeys.{key name}.headers.{header name}(DEPRECATED) Header name that should be present a match the regex to be part of the ykey groupContent-Type: json
ykeys.{key name}.url(DEPRECATED) Url that should match to be part of the ykey group.+

APIs

All endpoints are accessible through theapi.basepath configuration line or by default through/souin-api to avoid named route conflicts. Be sure to define an unused route to not break your existing application.

Prometheus API

Prometheus API expose some metrics about the cache.
The base path for the prometheus API is/metrics.Not supported inside Træfik because the deny the unsafe library usage inside plugins

MethodEndpointDescription
GET/Expose the different keys listed below.
KeyDefinition
souin_request_upstream_counterCount the incoming requests that go to the upstream
souin_no_cached_response_counterCount the uncacheable responses
souin_cached_response_counterCount the cacheable responses
souin_avg_response_timeAverage response time

Souin API

Souin API allow users to manage the cache.
The base path for the souin API is/souin.
The Souin API supports the invalidation by surrogate keys such as Fastly which will replace the Varnish system. You can read the docabout this system.This system is able to invalidate by tags your cloud provider cache. Actually it supports Akamai and Fastly but in a near future some other providers would be implemented like Cloudflare or Varnish.

MethodEndpointHeadersDescription
GET/-List stored keys cache
GET/surrogate_keys-List stored keys cache
PURGE/{id or regexp}-Purge selected item(s) depending. The parameter can be either a specific key or a regexp; use$ to end a specific key; without$,id is considered a regex
PURGE/?ykey={key}-Purge selected item(s) corresponding to the target ykey such as Varnish (deprecated)
PURGE/Surrogate-Key: Surrogate-Key-First, Surrogate-Key-SecondPurge selected item(s) belong to the target key in the headerSurrogate-Key (seeSurrogate-Key system)
PURGE/flush-Purge all providers and surrogate storages

Security API

DEPRECATED
Security API allows users to protect other APIs with JWT authentication.
The base path for the security API is/authentication.

MethodEndpointBodyHeadersDescription
POST/login{"username":"admin", "password":"admin"}['Content-Type' => 'json']Try to login, it returns a response which contains the cookie namesouin-authorization-token with the JWT if succeed
POST/refresh-['Content-Type' => 'json', 'Cookie' => 'souin-authorization-token=the-token']Refreshes the token, replaces the old with a new one

Diagrams

Sequence diagram

See the sequence diagram for the minimal version belowSequence diagram

Cache systems

Supported providers

The cache system sits on top of three providers at the moment. It provides two in-memory storage solutions (badger and nuts), and two distributed storages Olric and Etcd because setting, getting, updating and deleting keys in these providers is as easy as it gets.
The Badger provider (default one): you can tune its configuration using the badger configuration inside your Souin configuration. In order to do that, you have to declare thebadger block. See the following json example.

"badger": {"configuration": {"ValueDir":"default","ValueLogFileSize":16777216,"MemTableSize":4194304,"ValueThreshold":524288,"BypassLockGuard":true  }}

The Nuts provider: you can tune its configuration using the nuts configuration inside your Souin configuration. In order to do that, you have to declare thenuts block. See the following json example.

"nuts": {"configuration": {"Dir":"default","EntryIdxMode":1,"RWMode":0,"SegmentSize":1024,"NodeNum":42,"SyncEnable":true,"StartFileLoadingMode":1  }}

The Otter provider: you can tune its configuration using the otter configuration inside your Souin configuration. In order to do that, you have to declare theotter block. See the following json example.

"otter": {"configuration": {"size":9999999  }}

The Olric provider: you can tune its configuration using the olric configuration inside your Souin configuration and declare Souin has to use the distributed provider. In order to do that, you have to declare theolric block and thedistributed directive. See the following json example.

"distributed":true,"olric": {"configuration": {# Olric configuration here...  }}

In order to do that, the Olric provider need to be either on the same network as the Souin instance when using docker-compose or over the internet, then it will use by default in-memory to avoid network latency as much as possible.

The Etcd provider: you can tune its configuration using the etcd configuration inside your Souin configuration and declare Souin has to use the distributed provider. In order to do that, you have to declare theetcd block and thedistributed directive. See the following json example.

"distributed":true,"etcd": {"configuration": {# Etcd configuration here...  }}

In order to do that, the Etcd provider need to be either on the same network as the Souin instance when using docker-compose or over the internet, then it will use by default in-memory to avoid network latency as much as possible.Souin will return at first the response from the choosen provider when it gives a non-empty response, or fallback to the reverse proxy otherwise.Since v1.4.2, Souin supportsOlric and since v1.6.10 it supportsEtcd to handle distributed cache.

GraphQL

This feature is currently in beta.
Souin can partially cache your GraphQL requests. It automatically handles the data retrieval and omit the caching for the mutations.
However, it will invalidate whole cache keys with a body when you send a mutation request due to the inability to read and understand automatically which cached endpoint should be deleted.
You can enable the GraphQL support with thedefault_cache.allowed_http_verbs key to define the list of supported HTTP verbs likeGET,POST,DELETE.

default_cache:allowed_http_verbs:    -GET    -POST    -HEAD

Cache invalidation

The cache invalidation is built for CRUD requests, if you're doing a GET HTTP request, it will serve the cached response when it exists, otherwise the reverse-proxy response will be served.
If you're doing a POST, PUT, PATCH or DELETE HTTP request, the related cache GET request, and the list endpoint will be dropped.
It also supports invalidation viaSouin API to invalidate the cache programmatically.

Plugins

Beego filter

To use Souin as beego filter, you can refer to theBeego filter integration folder to discover how to configure it.
You just have to define a new beego router and tell to the instance to use theHandle method like below:

import ("net/http"httpcache"github.com/darkweak/souin/plugins/beego")funcmain(){// ...web.InsertFilterChain("/*",httpcache.NewHTTPCacheFilter())// ...}

Caddy module

To use Souin as caddy module, you can refer to theCaddy module integration folder to discover how to configure it.
The related Caddyfile can be foundhere.
Then you just have to run the following command:

xcaddy build --with github.com/darkweak/souin/plugins/caddy

There is the fully configuration below

{    log {        level debug    }    cache {        allowed_http_verbs GET POST PATCH        allowed_additional_status_codes 202        api {            basepath /some-basepath            prometheus {                security            }            souin {                security            }        }        badger {            path the_path_to_a_file.json        }        cache_name Souin        cache_keys {            .*\.something {                disable_body                disable_host                disable_method                disable_query                disable_scheme                disable_vary                headers X-Token Authorization                hide                hash            }        }        cdn {            api_key XXXX            dynamic            email darkweak@protonmail.com            hostname domain.com            network your_network            provider fastly            strategy soft            service_id 123456_id            zone_id anywhere_zone        }        key {            disable_body            disable_host            disable_method            disable_query            disable_scheme            disable_vary            hash            hide            headers Content-Type Authorization        }        log_level debug        etcd {            configuration { # Your Etcd configuration here            }        }        olric {            url url_to_your_cluster:3320            path the_path_to_a_file.yaml            configuration { # Your Olric configuration here            }        }        regex {            exclude /test2.*        }        stale 200s        timeout {          backend 20s          cache 5ms        }        ttl 1000s        default_cache_control no-store    }}:4443respond"Hello World!"@match path/test1*@match2 path/test2*@matchdefault path/default@souin-api path/souin-api*cache@match {    ttl 5s    badger {        path/tmp/badger/first-match        configuration { # Required value            ValueDir <string> # Optional            SyncWrites <bool>            NumVersionsToKeep <int>            ReadOnly <bool>            Compression <int>            InMemory <bool>            MetricsEnabled <bool>            MemTableSize <int>            BaseTableSize <int>            BaseLevelSize <int>            LevelSizeMultiplier <int>            TableSizeMultiplier <int>            MaxLevels <int>            VLogPercentile <float>            ValueThreshold <int>            NumMemtables <int>            BlockSize <int>            BloomFalsePositive <float>            BlockCacheSize <int>            IndexCacheSize <int>            NumLevelZeroTables <int>            NumLevelZeroTablesStall <int>            ValueLogFileSize <int>            ValueLogMaxEntries <int>            NumCompactors <int>            CompactL0OnClose <bool>            LmaxCompaction <bool>            ZSTDCompressionLevel <int>            VerifyValueChecksum <bool>            EncryptionKey <string>            EncryptionKey <Duration>            BypassLockGuard <bool>            ChecksumVerificationMode <int>            DetectConflicts <bool>            NamespaceOffset <int>        }    }}cache@match2 {    ttl 50s    badger {        path/tmp/badger/second-match        configuration {            ValueDir match2            ValueLogFileSize 16777216            MemTableSize 4194304            ValueThreshold 524288            BypassLockGuard true        }    }    default_cache_control"public, max-age=86400"}cache@matchdefault {    ttl 5s    badger {        path/tmp/badger/default-match        configuration {            ValueDir default            ValueLogFileSize 16777216            MemTableSize 4194304            ValueThreshold 524288            BypassLockGuard true        }    }}route/no-method-and-domain.css {    cache {        cache_keys {            .*\.css {                disable_host                disable_method            }        }    }    respond"Hello without storing method and domain cache key"}cache@souin-api {}

Chi middleware

To use Souin as chi middleware, you can refer to theChi middleware integration folder to discover how to configure it.
You just have to define a new chi router and tell to the instance to use theHandle method like below:

import ("net/http"cache"github.com/darkweak/souin/plugins/chi""github.com/go-chi/chi/v5")funcmain(){// ...router:=chi.NewRouter()httpcache:=cache.NewHTTPCache(cache.DevDefaultConfiguration)router.Use(httpcache.Handle)router.Get("/*",defaultHandler)// ...}

Dotweb middleware

To use Souin as dotweb middleware, you can refer to theDotweb plugin integration folder to discover how to configure it.
You just have to define a new dotweb router and tell to the instance to use the process method like below:

import (cache"github.com/darkweak/souin/plugins/dotweb""github.com/go-dotweb/dotweb/v5")funcmain(){// ...httpcache:=cache.NewHTTPCache(cache.DevDefaultConfiguration)app.HttpServer.GET("/:p",func(ctx dotweb.Context)error {returnctx.WriteString("Hello, World 👋!")}).Use(httpcache)// ...}

Echo middleware

To use Souin as echo middleware, you can refer to theEcho plugin integration folder to discover how to configure it.
You just have to define a new echo router and tell to the instance to use the process method like below:

import ("net/http"souin_echo"github.com/darkweak/souin/plugins/echo""github.com/labstack/echo/v4")funcmain(){// ...e:=echo.New()s:=souin_echo.New(souin_echo.DefaultConfiguration)e.Use(s.Process)// ...}

Fiber middleware

To use Souin as fiber middleware, you can refer to theFiber plugin integration folder to discover how to configure it.
You just have to define a new fiber router and tell to the instance to use the process method like below:

import (cache"github.com/darkweak/souin/plugins/fiber""github.com/gofiber/fiber/v2")funcmain(){// ...httpcache:=cache.NewHTTPCache(cache.DevDefaultConfiguration)app.Use(httpcache.Handle)// ...}

Gin middleware

To use Souin as gin middleware, you can refer to theGin plugin integration folder to discover how to configure it.
You just have to define a new gin router and tell to the instance to use the process method like below:

import ("net/http"souin_gin"github.com/darkweak/souin/plugins/gin""github.com/gin-gonic/gin")funcmain(){// ...r:=gin.New()s:=souin_gin.New(souin_gin.DefaultConfiguration)r.Use(s.Process())// ...}

Go-zero middleware

To use Souin as go-zero middleware, you can refer to theGo-zero plugin integration folder to discover how to configure it.
You just have to give a Condfiguration object to theNewHTTPCache method to get a new HTTP cache instance and use the Handle method as a GlobalMiddleware:

import ("net/http"cache"github.com/darkweak/souin/plugins/go-zero")funcmain(){// ...httpcache:=cache.NewHTTPCache(cache.DevDefaultConfiguration)server.Use(httpcache.Handle)// ...}

Goa middleware

To use Souin as goa middleware, you can refer to theGoa plugin integration folder to discover how to configure it.
You just have to start Goa, define a new goa router and tell to the router instance to use the Handle method as GlobalMiddleware like below:

import ("net/http"httpcache"github.com/darkweak/souin/plugins/goa"goahttp"goa.design/goa/v3/http")funcmain(){// ...g:=goahttp.NewMuxer()g.Use(httpcache.NewHTTPCache(httpcache.DevDefaultConfiguration))// ...}

Goyave middleware

To use Souin as goyave middleware, you can refer to theGoyave plugin integration folder to discover how to configure it.
You just have to start Goyave, define a new goyave router and tell to the router instance to use the Handle method as GlobalMiddleware like below:

import ("net/http"cache"github.com/darkweak/souin/plugins/goyave""goyave.dev/goyave/v4")funcmain() {// ...goyave.Start(func(r*goyave.Router) {r.GlobalMiddleware(cache.NewHTTPCache(cache.DevDefaultConfiguration).Handle)// ...})}

Hertz middleware

To use Souin as hertz middleware, you can refer to theHertz middleware integration folder to discover how to configure it.
You just have to use theNewHTTPCache method like below:

import ("context""net/http"// ...httpcache"github.com/darkweak/souin/plugins/hertz")funcmain() {// ...h.Use(httpcache.NewHTTPCache(httpcache.DevDefaultConfiguration))// ...}

Kratos filter

To use Souin as Kratos filter, you can refer to theKratos plugin integration folder to discover how to configure it.
You just have to start the Kratos HTTP server with the Souin filter like below:

import (httpcache"github.com/darkweak/souin/plugins/kratos"kratos_http"github.com/go-kratos/kratos/v2/transport/http")funcmain() {kratos_http.NewServer(kratos_http.Filter(httpcache.NewHTTPCacheFilter(httpcache.DevDefaultConfiguration),),)}

You can also use the configuration file to configuration the HTTP cache. Refer to the code block below:

server: #...data: #...# HTTP cache parthttpcache:  api:    souin: {}  default_cache:    regex:      exclude: /excluded    ttl: 5s  log_level: debug

After that you have to edit your server instanciation to use the HTTP cache configuration parser

import (httpcache"github.com/darkweak/souin/plugins/kratos"kratos_http"github.com/go-kratos/kratos/v2/transport/http")funcmain() {c:=config.New(config.WithSource(file.NewSource("examples/configuration.yml")),config.WithDecoder(func(kv*config.KeyValue,vmap[string]interface{})error {returnyaml.Unmarshal(kv.Value,v)}),)iferr:=c.Load();err!=nil {panic(err)}server:=kratos_http.NewServer(kratos_http.Filter(httpcache.NewHTTPCacheFilter(httpcache.ParseConfiguration(c)),),)// ...}

Roadrunner middleware

To use Souin as Roadrunner middleware, you can refer to theRoadrunner plugin integration folder to discover how to configure it.
Ysou have to build yourrr binary with the souin dependency.

[velox]build_args = ['-trimpath','-ldflags','-s -X github.com/roadrunner-server/roadrunner/v2/internal/meta.version=${VERSION} -X github.com/roadrunner-server/roadrunner/v2/internal/meta.buildTime=${TIME}'][roadrunner]ref ="master"[github]    [github.token]token ="GH_TOKEN"    [github.plugins]logger = {ref ="master",owner ="roadrunner-server",repository ="logger" }cache = {ref ="master",owner ="darkweak",repository ="souin",folder ="/plugins/roadrunner" }# others ...[log]level ="debug"mode ="development"

After that, you'll be able to set each Souin configuration key under thehttp.cache key.

# .rr.yamlhttp:# Other http sub keyscache:api:basepath:/httpcache_apiprometheus:basepath:/anything-for-prometheus-metricssouin:{}default_cache:allowed_http_verbs:        -GET        -POST        -HEADallowed_additional_status_codes:        -202        -400cdn:api_key:XXXXdynamic:truehostname:XXXXnetwork:XXXXprovider:fastlystrategy:softregex:exclude:'/excluded'timeout:backend:5scache:1msttl:5sstale:10slog_level:debugykeys:The_First_Test:headers:Content-Type:'.+'The_Second_Test:url:'the/second/.+'surrogate_keys:The_First_Test:headers:Content-Type:'.+'The_Second_Test:url:'the/second/.+'middleware:    -cache# Other middlewares

Skipper filter

To use Souin as skipper filter, you can refer to theSkipper plugin integration folder to discover how to configure it.
You just have to add to your Skipper instance the Souin filter like below:

package mainimport (souin_skipper"github.com/darkweak/souin/plugins/skipper""github.com/zalando/skipper""github.com/zalando/skipper/filters")funcmain() {skipper.Run(skipper.Options{Address:":9090",RoutesFile:"example.yaml",CustomFilters: []filters.Spec{souin_skipper.NewSouinFilter()}},)}

After that you will be able to declare the httpcache filter in your eskip file.

hello: Path("/hello")   -> httpcache(`{"api":{"basepath":"/souin-api","security":{"secret":"your_secret_key","enable":true,"users":[{"username":"user1","password":"test"}]},"souin":{"security":true,"enable":true}},"default_cache":{"regex":{"exclude":"ARegexHere"},"ttl":"10s","stale":"10s"},"log_level":"INFO"}`)  -> "https://www.example.org"

Træfik plugin

To use Souin as Træfik plugin, you can refer to thepilot documentation and theTræfik plugin integration folder to discover how to configure it.
You have to declare theexperimental block in your traefik static configuration file. Keep in mind Træfik run their own interpreter and they often break any dependances (such as the yaml.v3 support).

# anywhere/traefik.ymlexperimental:plugins:souin:moduleName:github.com/darkweak/souinversion:v1.7.6

After that you can declare either the whole configuration at once in the middleware block or by service. See the examples below.

# anywhere/dynamic-configurationhttp:routers:whoami:middlewares:        -http-cacheservice:whoamirule:Host(`domain.com`)middlewares:http-cache:plugin:souin:api:prometheus:{}souin:{}default_cache:regex:exclude:'/test_exclude.*'ttl:5sallowed_http_verbs:              -GET              -HEAD              -POSTallowed_additional_status_codes:              -202              -400default_cache_control:no-storelog_level:debugurls:'domain.com/testing':ttl:5s'mysubdomain.domain.com':ttl:50sdefault_cache_control:public, max-age=86400ykeys:The_First_Test:headers:Content-Type:'.+'The_Second_Test:url:'the/second/.+'The_Third_Test:The_Fourth_Test:surrogate_keys:The_First_Test:headers:Content-Type:'.+'The_Second_Test:url:'the/second/.+'The_Third_Test:The_Fourth_Test:
# anywhere/docker-compose.ymlservices:#...whoami:image:traefik/whoamilabels:# other labels...      -traefik.http.routers.whoami.middlewares=http-cache      -traefik.http.middlewares.http-cache.plugin.souin.api.souin      -traefik.http.middlewares.http-cache.plugin.souin.default_cache.ttl=10s      -traefik.http.middlewares.http-cache.plugin.souin.default_cache.allowed_http_verbs=GET,HEAD,POST      -traefik.http.middlewares.http-cache.plugin.souin.log_level=debug

Tyk plugin

To use Souin as a Tyk plugin, you can refer to theTyk plugin integration folder to discover how to configure it.
You have to define the use of Souin aspost andresponse custom middleware. You can compile your own Souin integration using theMakefile and thedocker-compose inside thetyk integration directory and place your generatedsouin-plugin.so file inside yourmiddleware directory.

{"name":"httpbin.org","api_id":"3","org_id":"3","use_keyless":true,"version_data": {"not_versioned":true,"versions": {"Default": {"name":"Default","use_extended_paths":true      }    }  },"custom_middleware": {"pre": [],"post": [      {"name":"SouinRequestHandler","path":"/opt/tyk-gateway/middleware/souin-plugin.so"      }    ],"post_key_auth": [],"auth_check": {"name":"","path":"","require_session":false    },"response": [      {"name":"SouinResponseHandler","path":"/opt/tyk-gateway/middleware/souin-plugin.so"      }    ],"driver":"goplugin","id_extractor": {"extract_from":"","extract_with":"","extractor_config": {}    }  },"proxy":{"listen_path":"/httpbin/","target_url":"http://httpbin.org/","strip_listen_path":true  },"active":true,"config_data": {"httpcache": {"api": {"souin": {"enable":true        }      },"cdn": {"api_key":"XXXX","provider":"fastly","strategy":"soft"      },"default_cache": {"ttl":"5s"      }    }  }}

Webgo middleware

To use Souin as webgo middleware, you can refer to theWebgo middleware integration folder to discover how to configure it.
You just have to define a new webgo router and tell to the instance to use the process method like below:

import ("net/http""github.com/bnkamalesh/webgo/v6"cache"github.com/darkweak/souin/plugins/webgo")funcmain(){// ...httpcache:=cache.NewHTTPCache(cache.DevDefaultConfiguration)router.Use(httpcache.Middleware)// ...}

Credits

Thanks to these users for contributing or helping this project in any way


[8]ページ先頭

©2009-2025 Movatter.jp