Início / API REST
Crie uma API REST
Perfil --api, disponível em 6.1.1-alpha. Requer Go 1.23+. O servidor escuta somente em 127.0.0.1:8080.
nextlang new ./MinhaAPI --api cd ./MinhaAPI code . nextlang check nextlang test nextlang run
Estrutura gerada
MinhaAPI/ ├── main.next ├── nextlang.toml ├── src/routes/routes.next ├── tests/json_test.next ├── assets/ ├── README.md └── .gitignore
Testes em outro PowerShell
Invoke-RestMethod http://127.0.0.1:8080/api/health
Invoke-RestMethod http://127.0.0.1:8080/api/echo -Method Post -ContentType 'application/json' -Body '{"name":"Maria"}'
Invoke-RestMethod http://127.0.0.1:8080/api/items/42
Invoke-RestMethod http://127.0.0.1:8080/api/items/42 -Method Put -ContentType 'application/json' -Body '{"name":"Ana"}'
Invoke-RestMethod http://127.0.0.1:8080/api/items/42 -Method Patch -ContentType 'application/json' -Body '{"name":"Ana"}'
Invoke-WebRequest http://127.0.0.1:8080/api/items/42 -Method Delete -UseBasicParsingGET health: 200 online; POST echo, PUT e PATCH: 200 com objeto enviado; GET item: 200 com id; DELETE: 204 sem corpo. JSON inválido: 400. Não há persistência nem autenticação automática. Não exponha sem proteção. nextlang build gera executável; nextlang diagnose valida geração, não substitui check. IR ainda não suporta este projeto completo.
Código da rota
module routes
import http
import json
fn health(req: http.Request) -> http.Response {
return http.json(200, {"status": "online"})
}
fn echo(req: http.Request) -> http.Response {
let data = json.decode(req.body())
if !data.ok {
return http.json(400, {"error": "Objeto JSON invalido"})
}
return http.json(200, data.value)
}
fn item(req: http.Request) -> http.Response {
return http.json(200, {"id": req.param("id")})
}
fn remove(req: http.Request) -> http.Response {
return http.text(204, "")
}
pub fn register(server: http.ServerHandle) {
server.route("GET", "/api/health", health)
server.post("/api/echo", echo)
server.route("GET", "/api/items/{id}", item)
server.put("/api/items/{id}", echo)
server.patch("/api/items/{id}", echo)
server.delete("/api/items/{id}", remove)
}
Documentação 6.2.0 alpha — recursos experimentais, não recomendados para produção sem validação.