HTTP servers and clients: handlers, text and JSON responses, cookies and sending requests.
import net.http
This package has both halves of HTTP/1.1: a server for web pages and JSON APIs, and a client for calling other services. The server hands each request to a net.router router, which picks the handler by method and path. Every handler takes one i64, the context id of the request; you read the request and write the response with the context functions below, or turn the id into a Context struct with Ctx and call the same names on it.
Register every route before Use. The server keeps a copy of the router.
•
Post, Put and Patch label a body as a form (application/x-www-form-urlencoded) unless you pass a Content-Type; send JSON with PostWith and that header.
•
The client does not follow redirects unless you ask. A 302 comes back as a 302 with its Location header; set max_redirects in RequestOptions (or call SetMaxRedirects on a client) to follow them. It never hangs or reads without limit: a read or write that is idle for 30 seconds fails, a response over 256 MB fails, and timeout_ms caps the whole request.
•
Ok means a 2xx status. When the server could not be reached at all, Status is 0 and Error says why.
•
A value read from a request is freed when the handler returns; see the end of the page.
The examples run the server with RunBackground on 127.0.0.1 and send requests to it from the same program.
A JSON API in one file
The most common job is a small JSON API: list some records, show one by its id, and create new ones. Register each route on the router with its handler, hand the router to the server with Use, and start it. Here the records are Salam structs: json.Marshal turns them into the response body, and json.UnmarshalLenient reads the posted body back into a struct, ignoring fields it does not know and leaving the missing ones at their defaults.
net-http-guide-api.salam
import net.http
import net.router
import encoding.json
import conv
mut books := Vector {} asVector<Book>
structBook:
@json "id"pub id: int = 0
@json "title"pub title: str = ""endfunclist(ctx: i64):
http.Json(ctx, json.Marshal(books))
endfuncshow(ctx: i64):
id := conv.AtoiOr(http.Param(ctx, "id"), -1)
each b in books:
if b.id == id:
http.Json(ctx, json.Marshal(b))
retendend
http.SetStatus(ctx, 404)
http.Json(ctx, `{"error":"no such book"}`)
endfunccreate(ctx: i64):
mut b := Book {}
try:
json.UnmarshalLenient(http.Body(ctx), b)
catch e:
http.SetStatus(ctx, 400)
http.Json(ctx, "{" + json.Member("error", e.ToStr()) + "}")
retend
b.id = books.Len() + 1
books.Push(b)
http.SetStatus(ctx, 201)
http.SetHeader(ctx, "Location", "/books/" + b.id)
http.Json(ctx, json.Marshal(b))
endfuncmain:
mut r := router.NewRouter()
router.Get(r, "/books", list)
router.Get(r, "/books/:id", show)
router.Post(r, "/books", create)
mut s := http.NewServer(19761)
http.Use(s, r)
_ := http.RunBackground(s)
base := "http://127.0.0.1:19761"
a := http.Post(base + "/books", `{"title": "The Little Prince"}`)
println http.Status(a), http.GetHeader(a, "location"), http.Body(a)
_ := http.Post(base + "/books", `{"title": "Rumi"}`)
println http.Body(http.Get(base + "/books"))
println http.Body(http.Get(base + "/books/2"))
c := http.Get(base + "/books/9")
println http.Status(c), http.Body(c)
d := http.Post(base + "/books", `{"title": 7}`)
println http.Status(d), http.Body(d)
end
Output
201 /books/1 {"id":1,"title":"The Little Prince"}
[{"id":1,"title":"The Little Prince"},{"id":2,"title":"Rumi"}]
{"id":2,"title":"Rumi"}
404 {"error":"no such book"}
400 {"error": "json: value does not match the expected type (line 1, column 11)"}
Nothing is sent until the handler returns: the status, the headers and the body are collected and go out together, and a second body call replaces the first. That is why a handler returns right after it writes an error. A 201 with a Location header is the usual answer to a create, and a 404 with a short JSON error is easier for a client to handle than an empty page. Path parameters such as :id always arrive as text, so convert them with conv.Atoi (or conv.AtoiOr, which gives a fallback for text that is not a number) before comparing.
HTML forms, query strings and redirects
A browser form arrives as application/x-www-form-urlencoded. Form reads one field and decodes it, so %40 becomes @ and + becomes a space. Query does the same for the query string. After a successful POST, answer with Redirect so that pressing reload in the browser does not send the form again.
net-http-guide-forms.salam
import net.http
import net.router
import template
mut messages := Vector {} asVector<str>
funcboard(ctx: i64):
mut html := "<ul>"each m in messages:
html = html + "<li>" + template.EscapeHTML(m) + "</li>"end
http.Html(ctx, html + "</ul>")
endfuncpost(ctx: i64):
name := http.Form(ctx, "name")
text := http.Form(ctx, "text")
if name == ""or text == "":
http.SetStatus(ctx, 400)
http.Text(ctx, "name and text are required")
retend
messages.Push(name + ": " + text)
http.Redirect(ctx, "/board")
endfuncsearch(ctx: i64):
word := http.Query(ctx, "q")
mut found := 0each m in messages:
if m.Find(word) >= 0:
found++
endend
http.Text(ctx, "'" + word + "' found in " + found + " message(s)")
endfuncmain:
mut r := router.NewRouter()
router.Get(r, "/board", board)
router.Post(r, "/board", post)
router.Get(r, "/search", search)
mut s := http.NewServer(19762)
http.Use(s, r)
_ := http.RunBackground(s)
base := "http://127.0.0.1:19762"mut form := http.NewHeaders()
form.Insert("name", "Sara")
form.Insert("text", "see you at 5 & bring tea")
mut headers := http.NewHeaders()
headers.Insert("Content-Type", "application/x-www-form-urlencoded")
a := http.PostWith(base + "/board", http.EncodeForm(form), headers)
println http.Status(a), http.GetHeader(a, "location")
b := http.PostWith(base + "/board", "name=Reza", headers)
println http.Status(b), http.Body(b)
println http.Body(http.Get(base + "/board"))
mut q := http.NewHeaders()
q.Insert("q", "bring tea")
println http.Body(http.Get(http.WithQuery(base + "/search", q)))
end
Output
302 /board
400 name and text are required
<ul><li>Sara: see you at 5 & bring tea</li></ul>
'bring tea' found in 1 message(s)
Anything a user typed must be escaped before it goes into HTML; otherwise a message containing <script> runs in every visitor's browser. template.EscapeHTML does that, as the & in the output shows. On the client side, EncodeForm builds a form body from a map and WithQuery adds a query string to a URL, both with correct escaping.
Route groups and a login check
router.Group puts a route under a common prefix, which is how an API is versioned under /api/v1. There is no separate middleware chain: a check that several handlers share is a plain function that returns true when the request may go on, or writes the error response itself and returns false. Each handler calls it on its first line and returns when it fails.
ok
401 Bearer {"error":"sign in first"}
{"user":"maryam"}
204
404
A route that is not registered answers 404 on its own, so /profile without the prefix is not found. For a cookie based login instead of a token, see net.http.session.
Static files and server settings
router.Static serves a whole directory under a prefix, with the content type taken from the file extension. A path that tries to climb out of the directory with .. is refused, and a missing file is a 404. HideTokens drops the version number from the Server header, so the answer says only Salam.
The examples above use RunBackground so that one program can be both the server and its own client. A real service calls Run, which never returns. Read the port from the environment, listen on 0.0.0.0 when the server sits in a container or behind a proxy, and turn on the access log while you are getting it running.
net-http-guide-server.salam
import net.http
import net.router
import os
import conv
funchome(ctx: i64):
http.Html(ctx, "<h1>Salam</h1>")
endfunchealth(ctx: i64):
http.Json(ctx, `{"status":"ok"}`)
endfuncmain:
port := conv.AtoiOr(os.Env("PORT"), 8080)
http.SetMaxBodyBytes(1048576)
http.SetKeepAliveIdle(5000)
mut r := router.NewRouter()
router.Get(r, "/", home)
router.Get(r, "/health", health)
router.Static(r, "/assets", "public")
mut s := http.NewServer(port)
http.SetHost(s, "0.0.0.0")
http.HideTokens(s)
http.EnableAccessLog(s)
http.Use(s, r)
println"listening on port " + port
http.Run(s)
end
Run it and try it from a second terminal:
PORT=8080 salam run server.salam
curl http://127.0.0.1:8080/health
The limits are for the whole process: SetMaxBodyBytes and SetMaxHeaderBytes reject requests that are too large, SetKeepAliveIdle closes idle connections, and SetKeepAliveMaxRequests caps how many requests one connection may send. For HTTPS, call RunTLS with a certificate and key file instead of Run, or put the server behind a proxy that handles TLS.
Calling an API as a client
Get, Post and the other one-line calls send a request and return a Response; the ...With forms take a map of extra headers. The program below shows the four answers a client has to handle. A Post without a content type reaches the server as a form, so a JSON API refuses it with 415; the same body through PostWith with Content-Type: application/json creates the ticket. A redirect is not followed, so Get returns the 302 and you read Location yourself. A server that is not running gives status 0 and the reason in Error.
net-http-guide-client.salam
import net.http
import net.router
import encoding.json
funccreate_ticket(ctx: i64):
kind := http.Header(ctx, "Content-Type")
if kind != "application/json":
http.SetStatus(ctx, 415)
http.Json(ctx, "{\"error\":\"expected JSON, got " + kind + "\"}")
retend
title := json.Get(http.Body(ctx), "title")
http.SetStatus(ctx, 201)
http.Json(ctx, "{\"id\":31,\"title\":" + json.Str(title) + "}")
endfuncold_tickets(ctx: i64): http.Redirect(ctx, "/v2/tickets") endfuncmain:
mut r := router.NewRouter()
router.Post(r, "/tickets", create_ticket)
router.Get(r, "/tickets", old_tickets)
mut s := http.NewServer(18631)
http.SetHost(s, "127.0.0.1")
http.Use(s, r)
ifnot http.RunBackground(s):
println"port 18631 is busy"ret1end
base := "http://127.0.0.1:18631"
body := `{"title": "Printer is out of paper"}`
plain := http.Post(base + "/tickets", body)
println"Post:", http.Status(plain), http.Body(plain)
mut headers := http.NewHeaders()
headers.Insert("Content-Type", "application/json")
made := http.PostWith(base + "/tickets", body, headers)
println"PostWith:", http.Status(made), http.Ok(made), "id", json.GetInt(http.Body(made), "id")
moved := http.Get(base + "/tickets")
println"Get:", http.Status(moved), "Location:", http.GetHeader(moved, "location")
down := http.Get("http://127.0.0.1:1/tickets")
println"dead server:", http.Status(down), http.Ok(down), http.Error(down)
ret0end
Output
Post: 415 {"error":"expected JSON, got application/x-www-form-urlencoded"}
PostWith: 201 true id 31
Get: 302 Location: /v2/tickets
dead server: 0 false could not connect to 127.0.0.1:1
Gzip and chunked answers are decoded for you, and every request is sent with Connection: close. For a series of calls that share a login, NewClient keeps the cookies from each answer and sends them with the next request, plus any headers set with SetHeader. A cookie is sent back only to the host that set it; a cookie you add with SetCookie goes to the host of the first request, never to a host a redirect leads to.
Any number of threads can use the one-line calls at once, because a call keeps no state outside itself. A Client from NewClient can be shared by threads too: it carries its own lock, so SetHeader, the cookie jar and the settings stay consistent. Call Free when you are done with a shared client. A Client {} written as a literal has no lock and belongs to one thread.
Raw requests: your own headers, bytes and time limits
The one-line calls above build the request for you. When you need full control of the request line and headers, for example to sign a request, to send a binary body or to talk to an API with unusual headers, write the request head yourself and send it with SendRaw. The aws, webpush, db.meilisearch, db.elasticsearch and db.typesense packages are built on these calls. The examples run against a small server in a thread of the same program, so they need no network.
Every raw call takes an Endpoint from ParseEndpoint (host, port and TLS on or off; any path in the URL is dropped, because the path goes in your request line) and a request head: the request line, the headers and an empty line, each line ending in \r\n. The body is a pointer and a length, so it can hold any bytes. The answer is a RawResponse with the body as bytes, chunked bodies already decoded, freed with FreeRaw. SendRaw waits as long as the server does; SendRawTimeout adds a time limit in milliseconds; SendRawTLS adds your own tls.Config. A response larger than RawLimit (256 MB by default) is reported as an error.
Things that catch people out:
•
Send Connection: close unless the answer is framed. The raw calls stop as soon as an answer with a Content-Length or a chunked body is complete. An answer with neither is read until the server closes the connection, so on a kept-alive connection the call waits until then (or until the time limit).
•
ok means a 2xx status, not "an answer arrived". Check status to tell a 404 from a dead server.
•
A str stops at the first zero byte, so binary bodies stay in data; RawText cuts at the first zero.
POST JSON with your own headers
ParseEndpoint turns a URL into the host, port and whether to use TLS. The request head is plain text that you write: the request line, a Host header, and here an Authorization token, the content type and the body length, closed by an empty line. SendRawTimeout sends the head and the body and returns the answer; RawText turns the reply body into a str. HeaderValue finds a header in the response head, ignoring case.
net-http-raw-post-json.salam
import net.http
import net.tcp
import encoding.json
mut server := tcp.Server {}
funcread_request(conn: tcp.Conn): str:
mut got := tcp.Read(conn, 4096)
until got.Find("\r\n\r\n") < 0:
got += tcp.Read(conn, 4096)
end
head_end := got.Find("\r\n\r\n") + 4
want := http.HeaderValue(got, "content-length").ToInt()
until got.Len() < head_end + want:
got += tcp.Read(conn, 4096)
endret got
endfuncapi():
conn := tcp.Accept(server)
request := read_request(conn)
at := request.Find("\r\n\r\n") + 4
body := request.Substr(at, request.Len() - at)
name := json.Get(body, "name")
auth := http.HeaderValue(request, "authorization")
reply := "{\"id\": 7, \"name\": \"" + name + "\", \"auth\": \"" + auth + "\"}"
head := "HTTP/1.1 201 Created\r\nContent-Type: application/json\r\nLocation: /users/7\r\nContent-Length: " +
reply.Len() + "\r\nConnection: close\r\n\r\n"
_ := tcp.Write(conn, head + reply)
tcp.Close(conn)
endfuncmain:
server = tcp.Bind(0)
t := spawn(api)
ep := http.ParseEndpoint("http://127.0.0.1:" + tcp.Port(server))
body := `{"name": "Sara", "role": "editor"}`mut head := "POST /users HTTP/1.1\r\n"
head += "Host: 127.0.0.1\r\n"
head += "Authorization: Bearer abc123\r\n"
head += "Content-Type: application/json\r\n"
head += "Content-Length: " + body.Len() + "\r\n"
head += "Connection: close\r\n\r\n"mut r := http.SendRawTimeout(ep, head, body asvoid*, body.Len(), 5000)
reply := http.RawText(r)
http.FreeRaw(r)
join(t)
tcp.CloseServer(server)
println"status:", r.status, r.ok
println"location:", http.HeaderValue(r.head, "Location")
println"id:", json.GetInt(reply, "id")
println"body:", reply
end
Content-Length must be the length in bytes, which is what str.len() returns, so it stays right for text in any language. A wrong length makes servers wait for more data or cut the body.
Status codes and failures
A RawResponse tells three cases apart. ok is true only for a 2xx status. A 4xx or 5xx answer still has its status and a body, which usually explain the problem. When no answer came at all, because the connection was refused, the host was unknown or the URL could not be parsed, status is 0 and error says why.
net-http-raw-status-errors.salam
import net.http
import net.tcp
mut server := tcp.Server {}
funcapi():
repeat2:
conn := tcp.Accept(server)
request := tcp.Read(conn, 4096)
if request.Find("GET /missing ") == 0:
tcp.WriteHTTP(conn, "404 Not Found", "application/json", `{"error": "no such page"}`)
else:
tcp.WriteHTTP(conn, "503 Service Unavailable", "text/plain", "try again later")
end
tcp.Close(conn)
endendfuncget(ep: http.Endpoint, path: str):
head := "GET " + path + " HTTP/1.1\r\nHost: " + ep.host + "\r\nConnection: close\r\n\r\n"mut r := http.SendRawTimeout(ep, head, null, 0, 5000)
body := http.RawText(r)
if r.ok:
println path, "worked:", body
else r.status > 0:
println path, "answered", r.status, "with", body
else:
println path, "failed:", r.error
end
http.FreeRaw(r)
endfuncmain:
server = tcp.Bind(0)
t := spawn(api)
ep := http.ParseEndpoint("http://127.0.0.1:" + tcp.Port(server))
get(ep, "/missing")
get(ep, "/busy")
join(t)
tcp.CloseServer(server)
get(http.ParseEndpoint("http://127.0.0.1:1"), "/nobody-listens")
bad := http.ParseEndpoint("ftp://files.example.com")
println"ftp endpoint ok:", bad.ok
get(bad, "/")
end
Output
/missing answered 404 with {"error": "no such page"}
/busy answered 503 with try again later
/nobody-listens failed: could not connect to 127.0.0.1:1
ftp endpoint ok: false
/ failed: the endpoint could not be parsed
A 503 or 429 often means "try again later"; read Retry-After with HeaderValue before you retry, and do not retry a 4xx such as 404, which will not change.
A small API client
A struct that holds the endpoint and the token, with one method per kind of request, keeps the header writing in one place. The JSON in the replies is read with encoding.json: json.Get for a field and json.Items to walk an array.
net-http-raw-api-client.salam
import net.http
import net.tcp
import encoding.json
mut server := tcp.Server {}
structApi:
pub ep: http.Endpoint = http.Endpoint {}
pub token: str = ""pubfuncget(path: str): str:
mut head := "GET " + path + " HTTP/1.1\r\n"
head += "Host: " + this.ep.host + "\r\n"
head += "Authorization: Bearer " + this.token + "\r\n"
head += "Accept: application/json\r\n"
head += "Connection: close\r\n\r\n"mut r := http.SendRawTimeout(this.ep, head, null, 0, 5000)
defer http.FreeRaw(r)
ret http.RawText(r)
endendfuncbackend():
repeat2:
conn := tcp.Accept(server)
request := tcp.Read(conn, 4096)
if request.Find("GET /users/7 ") == 0:
tcp.WriteHTTP(
conn, "200 OK", "application/json", `{"id": 7, "name": "Sara", "city": "Shiraz"}`
)
else:
tcp.WriteHTTP(
conn,
"200 OK",
"application/json",
`[{"item": "pen", "qty": 3}, {"item": "notebook", "qty": 1}]`
)
end
tcp.Close(conn)
endendfuncmain:
server = tcp.Bind(0)
t := spawn(backend)
api := Api { ep = http.ParseEndpoint("http://127.0.0.1:" + tcp.Port(server)), token = "abc123" }
user := api.Get("/users/7")
println json.Get(user, "name"), "from", json.Get(user, "city")
orders := api.Get("/users/7/orders")
each order in json.Items(orders):
println" ", json.GetInt(order, "qty"), "x", json.Get(order, "item")
endjoin(t)
tcp.CloseServer(server)
end
Output
Sara from Shiraz
3 x pen
1 x notebook
Chunked answers and time limits
A server that does not know the length of its answer in advance sends it in chunks, each one prefixed by its size in hex. SendRawTimeout removes that framing for you. The last parameter of SendRawTimeout is a time limit in milliseconds for each read and write, and on Linux also for the connect, so a server that accepts the connection and then says nothing cannot hang the program. The second request below hits such a server with a 300 ms limit.
net-http-raw-chunked.salam
import net.http
import net.tcp
mut server := tcp.Server {}
funcfeed():
repeat2in i:
conn := tcp.Accept(server)
_ := tcp.Read(conn, 4096)
if i < 1:
_ := tcp.Write(
conn,
"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\n\r\n6\r\nnews: \r\n9\r\nall quiet\r\n0\r\n\r\n"
)
else:
_ := tcp.Read(conn, 4096)
end
tcp.Close(conn)
endendfuncmain:
server = tcp.Bind(0)
t := spawn(feed)
ep := http.ParseEndpoint("http://127.0.0.1:" + tcp.Port(server))
head := "GET /feed HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n"mut raw := http.SendRawTimeout(ep, head, null, 0, 2000)
println"body:", http.RawText(raw)
http.FreeRaw(raw)
mut slow := http.SendRawTimeout(ep, head, null, 0, 300)
println"silent server:", slow.ok, slow.status, slow.error
http.FreeRaw(slow)
join(t)
tcp.CloseServer(server)
end
Output
body: news: all quiet
silent server: false 0 the request timed out
A timeout is reported as the request timed out and an answer cut short by a closing connection as the response body was cut short; both are worth a retry later. SendRaw has no time limit at all; give SendRawTimeout a limit for any server you do not control. SendRawTLS takes the same limit plus a tls.Config for a private CA.
Binary downloads
A str ends at the first zero byte, so an image or a zip file turned into one is cut short. Read it from the RawResponse instead: data points at the body bytes and len is their count. The program downloads twelve bytes of a PNG header and shows that RawText, which turns the body into a str, keeps only the eight bytes before the first zero.
true 200 image/png
bytes received: 12
89 50 4e 47 0d 0a 1a 0a 00 00 00 0d
is a PNG: true
RawText keeps 8 bytes
A RawResponse body is limited to RawLimit bytes, 256 MB unless you change it with SetRawLimit; a larger answer is reported as an error instead of filling memory. The data buffer belongs to you until FreeRaw.
HTTPS
An https:// URL gives an endpoint with secure set, and the same calls then speak TLS through tls, checking the server certificate. Nothing else changes. This example asks the GitHub API about the Salam repository, so it needs the internet; GitHub requires a User-Agent header.
net-http-raw-https.salam
import net.http
import encoding.json
funcmain:
ep := http.ParseEndpoint("https://api.github.com")
println ep.host, ep.port, ep.secure
mut head := "GET /repos/SalamLang/Salam HTTP/1.1\r\n"
head += "Host: api.github.com\r\n"
head += "User-Agent: salam-example\r\n"
head += "Accept: application/vnd.github+json\r\n"
head += "Connection: close\r\n\r\n"mut r := http.SendRawTimeout(ep, head, null, 0, 10000)
defer http.FreeRaw(r)
body := http.RawText(r)
if r.status == 0:
println"request failed:", r.error
ret1endprintln"status:", r.status
println"rate limit left:", http.HeaderValue(r.head, "x-ratelimit-remaining")
if r.ok:
println json.Get(body, "full_name"), "is written in", json.Get(body, "language")
endret0end
When this page was written it printed:
api.github.com 443 true
status: 200
rate limit left: 58
SalamLang/Salam is written in TeX
The rate limit number counts down with each call from your address, and the language is what GitHub detects for the repository at the time.
Timeouts, limits and redirects
Client requests run under the limits below. RequestOptions holds the limits and Do sends a request with them; a Client keeps its own copy, changed with SetTimeout, SetIdleTimeout, SetMaxRedirects and SetMaxBody. idle_ms (30 seconds by default) is how long one read or write may stall, timeout_ms (off by default) is the time for the whole request including redirects, and max_body (256 MB by default) bounds the body, also after gzip is unpacked, so a small compressed answer cannot fill memory. Looking up a host name is done by the system resolver, and on systems other than Linux the connect itself waits the system default; neither is covered by these limits. A request that runs out of time reports the request timed out, and an answer cut short by a closing connection is an error rather than a smaller body.
Redirects are followed only when max_redirects is above zero. A 301 or 302 after a POST and every 303 turn into a GET without the body; 307 and 308 repeat the request as it was. When a redirect leads to another host, the Authorization and Cookie headers are dropped, and a redirect from https to http is refused. The final address is in the url field of the response.
The request is checked before anything is sent: a method, header name or address with a space or a control character, and a header value with a line break, are refused with a message in err, so a value taken from outside cannot add headers to the request. A Content-Length, Transfer-Encoding, Connection or Accept-Encoding header of yours is replaced by the one the client computes. The example sends a request to a server that answers late and one that never answers, follows a redirect and refuses an answer that is too large.
Ok for a 2xx status, Status for the code (0 when nothing answered), Error for the reason
A value you read from the request, such as Param or Form, belongs to that request and is freed when the handler returns. To keep it longer, in a global list or a session, store a copy made with str.Clone or a new string built with +.
true 200 GET t1 []
true ["sid=abc; Path=/; SameSite=Lax; HttpOnly"]
abc true true
POST a PUT t1 b
DELETE DELETE t1
PATCH c PATCH t1 d
OPTIONS OPTIONS t1
200 200
PUT e GET
POST raw f
200 7
q=hello%20world http://x.ir/s?q=hello%20world
2 en true 2
1 en false
PUT c1 g PATCH h
PUT i DELETE PATCH j OPTIONS 200
false true
The limits of a request: idle_ms for one stalled read or write (30000), timeout_ms for the whole request (0, none), max_body in bytes (256 MB) and max_redirects (0).
Name
Type
Description
idle_ms
int = 30000
How long one read or write may stall, in milliseconds.
timeout_ms
int = 0
The time for the whole request, redirects included; 0 means none.
max_body
int = 268435456
The largest body in bytes, measured after gzip is unpacked.
Frees the head and body of a response, for programs that keep making requests for a long time. Body and the head field point into it, so copy what you need first; do not use the response afterwards.
Sends the request head you wrote and n bytes of body from a pointer, reads until the server closes, keeps the body binary and decodes a chunked body. No time limit.
Turns the numeric id of the handler into a Context. Every function on this page takes either one, so this is a matter of taste: a struct to pass around and read fields from, or the bare id.
A pointer to the request body bytes, for uploads and other binary bodies that Body would cut at the first zero byte. It belongs to the request and is freed when the handler returns; copy what you keep, and do not free it.
Reads a multipart/form-data body into its parts, each with its name, file name, content type and bytes; no parts when the request is not multipart. The caller owns the result and frees it with mime.FreeMultipart.
Sends n bytes from a pointer as the body, with the given content type; binary safe, for files, images and archives. The bytes are copied, so the call takes nothing over: free the pointer afterwards only if you allocated it, and never free one the request owns, such as the one BodyBytes returns.
Sets one response header. A second call with the same name, spelled the same way, replaces the value; a different spelling such as cache-control adds a second header.
Reads the size and the modification time (Unix seconds) of a file with one system call, into the two variables you pass. It returns false when the file cannot be read. Outside Linux on x64 and arm64 the time is 0.
A pointer to the request body bytes, for uploads and other binary bodies that Body would cut at the first zero byte. It belongs to the request and is freed when the handler returns; copy what you keep, and do not free it.
Reads a multipart/form-data body into its parts, each with its name, file name, content type and bytes; no parts when the request is not multipart. The caller owns the result and frees it with mime.FreeMultipart.
Sets one response header. A second call with the same name, spelled the same way, replaces the value; a different spelling such as cache-control adds a second header.
Sends n bytes from a pointer as the body, with the given content type; binary safe, for files, images and archives. The bytes are copied, so the call takes nothing over: free the pointer afterwards only if you allocated it, and never free one the request owns, such as the one BodyBytes returns.
The address of the client that made the request, without the port. Empty when it cannot be read. It is the address of the connection, so behind a reverse proxy it is the proxy; read the forwarded headers yourself and only from a proxy you trust.
Hands a string the handler built to the context, so it is freed when the request ends; do not hand it a string that came from the context itself, such as the body.
Undoes percent encoding and turns + into a space. It never fails: a % not followed by two hex digits is kept as written. Use encoding.URLDecode when such input should be an error.
Runs the server in another thread and returns at once. True when listening on the port started, false when the port is not available, because another program holds it for instance.
Like RunBackground, and returns the port the server listens on, or 0 when it could not listen. With NewServer(0) the system picks a free port, so tests and tools that run side by side never fight over one.
net-http-RunBackgroundPort.salam
import net.http
import net.router
funchello(ctx: i64):
http.Text(ctx, "hi")
endfuncmain:
mut r := router.NewRouter()
router.Get(r, "/", hello)
mut s := http.NewServer(0)
http.Use(s, r)
port := http.RunBackgroundPort(s)
println port > 0println http.Body(http.Get("http://127.0.0.1:" + port + "/"))
end
Answers with a file from disk as the body, streamed in pieces so a large file never sits in memory; the length and the content type are set for you. The status and headers you set are kept, and a HEAD request gets only the headers. It returns false when the file cannot be opened, and then nothing is changed.
Like File but sends only length bytes starting at offset, for answers to a Range request; the caller sets the 206 status and the Content-Range header. It returns false when the part does not lie inside the file.