Standard library · Network

net/http/middleware

The usual security, cache and CORS headers, and request logging, in one call.

import net.http.middleware
On this page
  1. Functions

Call these at the top of a handler to add the usual headers to the response. Each one takes the context id, just as the handler itself does.

Functions

Log

func Log(ctx: i64)
Writes the method and path of the request to the output.
net-http-middleware-Headers.salam
import net.http
import net.http.middleware
import net.router

func home(ctx: i64):
    middleware.Log(ctx)
    middleware.AllowAll(ctx)
    middleware.Secure(ctx)
    middleware.NoCache(ctx)
    http.Ctx_text(ctx, "hello")
end

func logo(ctx: i64):
    middleware.Cache(ctx, 3600)
    http.Ctx_text(ctx, "png")
end

func main:
    mut r := router.NewRouter()
    router.Get(r, "/", home)
    router.Get(r, "/logo.png", logo)
    mut s := http.NewServer(19624)
    http.Use(s, r)
    _ := http.RunBackground(s)
    a := http.Get("http://127.0.0.1:19624/")
    each name in ["access-control-allow-origin", "x-content-type-options", "x-frame-options", "cache-control"]:
        println name + ": " + http.GetHeader(a, name)
    end
    println http.GetHeader(http.Get("http://127.0.0.1:19624/logo.png"), "cache-control")
end
Output[HTTP] GET / access-control-allow-origin: * x-content-type-options: nosniff x-frame-options: DENY cache-control: no-store, no-cache, must-revalidate max-age=3600

AllowAll

func AllowAll(ctx: i64)
Opens CORS to every domain: Access-Control-Allow-Origin: * and the usual methods and headers.

The example for this item is shown with the ones above: net-http-middleware-Headers.salam

Secure

func Secure(ctx: i64)
The basic security headers: no content type sniffing, no framing and no XSS.

The example for this item is shown with the ones above: net-http-middleware-Headers.salam

NoCache

func NoCache(ctx: i64)
Tells the browser and any proxies not to keep the response.

The example for this item is shown with the ones above: net-http-middleware-Headers.salam

Cache

func Cache(ctx: i64, seconds: int)
Tells the browser to keep the response for this many seconds.

The example for this item is shown with the ones above: net-http-middleware-Headers.salam