# HTTP server

> A small JSON HTTP server in Langoost using http.serve and a handler that routes on method and path and returns string responses with status prefixes.

# HTTP server

Serve an API with `http.serve`. The handler receives `method`, `path`, `query`,
and `body`, and returns a string. A leading status code sets the HTTP status;
responses starting with `{` or `[` are sent as JSON automatically.

```goost
import http
import strings
import json

fn handle(method: string, path: string, query: string, body: string): string {
    if path == "/health" {
        return "{\"status\": \"ok\"}"
    }

    if path == "/echo" && method == "POST" {
        return body
    }

    if path == "/greet" {
        let name = "World"
        if strings.contains(query, "name=") {
            let parts = strings.splitN(query, "name=", 2)
            name = parts[1]
        }
        let data: json = {message: "Hello"}
        return json.setString(data, "message", "Hello, " + name + "!")
    }

    return "404 Not Found"
}

http.serve(8080, handle)
```

Try it:

```
$ langoost run server.goost
$ curl localhost:8080/health
{"status": "ok"}
$ curl "localhost:8080/greet?name=Ada"
{"message":"Hello, Ada!"}
```