hclapi

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 2 Imported by: 0

README

hclapi

Go Reference Release CI

hclapi is a declarative backend runtime distributed as a single static binary. It compiles HashiCorp Configuration Language (HCL) manifests, SQL queries, and sandboxed Starlark scripts into production HTTP APIs with native connection pooling, schema validation, and OpenAPI documentation.

Manifests are parsed and executed at runtime. hclapi does not generate or compile Go code.

Documentation · Why hclapi · Patterns · Examples

Supported connectors

hclapi connects to any data source using native connection pooling and zero-CGO pure Go drivers:

Category Driver Supported engines
Relational SQL "postgres" PostgreSQL, Supabase, TimescaleDB, AWS Aurora
"sqlite" SQLite3, Turso, LibSQL
"mysql" MySQL, MariaDB, PlanetScale, TiDB
"sqlserver" Microsoft SQL Server, Azure SQL
"oracle" Oracle Database 11g – 23ai
"cockroachdb" CockroachDB Dedicated & Serverless
Analytical SQL "clickhouse" ClickHouse Cloud & Self-Hosted
"duckdb" DuckDB Embedded Columnar
Key-Value / Cache "redis" Redis, Valkey, AWS ElastiCache
Blob Storage "s3" Amazon S3, Cloudflare R2, MinIO, GCS

Example

A production user registration endpoint with input normalization, parameterized SQL insertion, constraint collision interception, and structured RFC 9457 error responses:

server {
  host          = "0.0.0.0"
  port          = 8080
  max_body_size = "5MB"
}

connection "postgres" "main" {
  url = env("DATABASE_URL")

  pool {
    max_open_conns    = 25
    conn_max_lifetime = "30m"
  }
}

schema "user_create" {
  field "email" {
    type        = string
    required    = true
    format      = "email"
    description = "Primary user login and notification email"
  }

  field "full_name" {
    type       = string
    required   = true
    min_length = 2
    max_length = 100
  }

  field "role" {
    type    = string
    default = "member"
    enum    = ["admin", "member", "viewer"]
  }
}

endpoint "POST /api/v1/users" {
  description = "Registers a new user account and provisions a default workspace."

  request {
    body = schema.user_create
  }

  pipeline {
    # 1. Sandboxed data transformation
    starlark "normalize" {
      source = <<-STARLARK
        def execute(ctx):
          email = ctx.request.body.get("email", "").strip().lower()
          name = ctx.request.body.get("full_name", "").strip()
          return {
            "email": email,
            "name": name,
            "handle": email.split("@")[0]
          }
      STARLARK
    }

    # 2. Parameterized SQL insert with constraint interception
    sql "insert_user" {
      connection = connection.postgres.main
      query      = <<-SQL
        INSERT INTO users (email, name, role)
        VALUES (@email, @name, @role)
        RETURNING id, email, name, role, created_at
      SQL
      args = {
        email = steps.normalize.result.email
        name  = steps.normalize.result.name
        role  = ctx.request.body.role
      }

      # Intercept PostgreSQL unique violation (code 23505)
      catch "23505" {
        status  = 409
        headers = { 
          "X-Error" = "Conflict" 
        }
        body    = problem(409, "A user with this email address already exists", "email-collision")
      }
    }

    # 3. Terminal 201 response with created record
    respond {
      status  = 201
      headers = { 
        "Location" = "/api/v1/users/${steps.insert_user.row.id}" 
      }
      body    = steps.insert_user.row
    }
  }
}

Installation

Download precompiled binaries from the releases page or install via Go:

go install github.com/ju4n97/hclapi/cmd/hclapi@latest
hclapi serve -c ./api

See Installation for detailed setup and Quickstart for a 5-minute tutorial.

Embedding in Go

hclapi implements the standard http.Handler interface and mounts directly into any Go HTTP router:

package main

import (
 "log"
 "net/http"

 "github.com/ju4n97/hclapi"
)

func main() {
  engine, err := hclapi.NewEngine(hclapi.Options{
    ConfigPath:   "./api",
    StrictTyping: true,
  })
  if err != nil {
    log.Fatalf("failed to initialize hclapi: %v", err)
  }
  defer engine.Close()

  mux := http.NewServeMux()

  mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("OK"))
  })

  mux.Handle("/", engine.Handler())

  log.Println("Server running on :8080")
  http.ListenAndServe(":8080", mux)
}

See Go integration for custom error handlers, logging, and registering native Go steps.

Documentation

Full reference documentation covering the request lifecycle, manifest block syntax, and patterns is available at: https://ju4n97.github.io/hclapi/

Contributing

See CONTRIBUTING.md for architecture details, package layouts, and local development instructions.

License

MIT

Documentation

Overview

Package hclapi provides a declarative, embeddable API runtime engine.

Index

Constants

This section is empty.

Variables

View Source
var DefaultErrorHandler = core.DefaultErrorHandler

DefaultErrorHandler returns a ProblemDetails with default values.

Functions

This section is empty.

Types

type ByteSize

type ByteSize = core.ByteSize

ByteSize represents a quantity of bytes that can be unmarshaled from text.

type Context

type Context = core.Context

Context represents the state passed sequentially across a pipeline execution.

type ContextOption

type ContextOption = core.ContextOption

ContextOption configures optional behavior during Context creation.

type Duration

type Duration = core.Duration

Duration wraps a time.Duration with universal text deserialization.

type Engine

type Engine = engine.Engine

Engine is the root coordinator managing manifests, step registries, and HTTP routing.

func NewEngine

func NewEngine(options Options) (*Engine, error)

NewEngine initializes an Engine by parsing manifests and registering route endpoints.

type ErrorHandler

type ErrorHandler = core.ErrorHandler

ErrorHandler defines the contract for customizing API error serialization.

type InvalidParam

type InvalidParam = core.InvalidParam

InvalidParam represents a single field validation failure.

type Options

type Options = core.Options

Options defines the configuration options for the hclapi engine.

type ProblemDetailsError

type ProblemDetailsError = core.ProblemDetailsError

ProblemDetailsError represents an RFC 9457 compliant error object.

type RequestState

type RequestState = core.RequestState

RequestState represents normalized HTTP request metadata extracted at runtime.

type Server

type Server = core.Server

Server defines the resolved HTTP server configuration.

type StepHandler

type StepHandler = core.StepHandler

StepHandler defines the signature for custom native Go step callbacks.

type StepResult

type StepResult = core.StepResult

StepResult represents arbitrary step-specific outputs.

Directories

Path Synopsis
cmd
hclapi command
examples
05_go_embedded command
internal
engine
Package engine provides route binding, HTTP multiplexing, and pipeline initialization.
Package engine provides route binding, HTTP multiplexing, and pipeline initialization.
eval
Package eval translates runtime core.Context data into HCL EvalContext structures and dynamically evaluates HCL AST expressions back into Go primitives.
Package eval translates runtime core.Context data into HCL EvalContext structures and dynamically evaluates HCL AST expressions back into Go primitives.
steps/xrespond
Package xrespond serializes payloads and writes final HTTP headers and status codes.
Package xrespond serializes payloads and writes final HTTP headers and status codes.
validator
Package validator enforces OpenAPI 3.1 schema types, format constraints, and default value normalization.
Package validator enforces OpenAPI 3.1 schema types, format constraints, and default value normalization.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL