Slim

Static Files

Images, JavaScript, CSS, PDF, fonts, etc…

Using Static Middleware

s := slim.New()s.Use(slim.Static("./static"))
Tip

If we use the function slim.Classic() to initialize, we need to be aware that this method already has built-in static middleware, which uses the ./public folder as the root directory for static service.

For more information about Slim instances, please refer to the Instance section.

Using Slim#Static()

The instance method Slim#Static(prefix, root string) is used to register routes that provide static services based on path prefixes.

Register folder-based static service route
s := slim.Classic()s.Static("/static", "assets")

The example above uses the string “/static” as a prefix for routes, responding to requests with any file from the assets directory. For example, when a client requests the file /static/js/main.js, the program will respond with assets/js/main.js.

Tip

Additionally, we provide similar methods for both router and route collector to respond to static services.

Using Slim#File()

The instance method Slim#File is used to register file routes, which can correctly respond with file content.

Example
s := slim.Classic()// File method defined on Slim instances.File("/path", "<PATH/TO/FILE>")r := s.Router()// File method defined on routerr.File("/path", "<PATH/TO/FILE>")r.Group(func(g slim.RouteCollector) {    // File method defined on route collector    g.File("/path", "<PATH/TO/FILE>")})
Homepage route
s.File("/", "public/index.html")

Respond to the homepage using the file we provide “public/index.html”.

Favicon
s.File("/favicon.ico", "images/favicon.ico")

Respond to favicon requests using the icon file we provide “images/favicon.ico”.

Tip

Here, we utilize the context method Context#File(file string) mentioned in the previous Response chapter to correctly respond with files. Additionally, we also provide similar methods for both router and route collector to register file routes.

Navigate Select esc Close search