Guidedog Handbuch 0.6.3
Sprache
Auf dieser Seite
Guidedog / Dokumentation 0.6.3

fetch/testserver

Package testserver is a small HTTP/1.1 server on the loopback interface, for tests of code that sends HTTP requests (lib/fetch, and the clients built on it). It answers one request per connection, one connection at a time, with what a handler procedure returns. It is a test fixture: it speaks enough HTTP for libcurl and WinHTTP, and nothing more. Each request is answered in an arena of the server thread’s own.

Example:

import "lib/fetch/testserver"
hello :: proc(r: testserver.Request, user: rawptr) -> testserver.Reply {
    return {status = 200, body = "hello"}
}
s, ok := testserver.start(hello, nil)
if !ok do return
defer testserver.stop(s)
url := testserver.url(s, "/path") // http://127.0.0.1:PORT/path

Types

testserver.Handler :: #type proc(r: Request, user: rawptr) -> Reply

Handler answers a request; it runs on the server’s thread, with user as start got it.

testserver.Reply :: struct

Reply is a handler’s answer. Its strings must live until the handler is next called.

status: int
headers: []string

whole header lines, such as „Location: /elsewhere“.

body: string
close: bool

close the connection without answering, as a lost answer.

testserver.Request :: struct

Request is one request the server received. Its strings live until the handler returns.

method: string
path: string
headers: map[string]string

names in lowercase.

body: []u8
testserver.Server :: struct

Server is a running server; stop ends it and frees it.

socket: net.TCP_Socket
port: int
handler: Handler
user: rawptr
stopping: bool
served: int

requests answered so far; read with sync.atomic_load.

worker: ^thread.Thread

Procedures

testserver.start :: proc(handler: Handler, user: rawptr) -> (^Server, bool)

start listens on a free loopback port and serves requests with handler, which is called on the server’s thread with user. It returns false when no port could be opened.

testserver.stop :: proc(s: ^Server)

stop ends the server, waits for its thread, and frees it.

testserver.url :: proc(s: ^Server, path: string) -> string

url is the server’s URL for path, allocated with context.allocator.

Constants

testserver.MAX_REQUEST :: 64 * 1024 * 1024

MAX_REQUEST is the largest request the server reads; a larger one is answered with 413.