Study · Go · exact package 2.3.2

Learn CoAkka HTTP Runtime with Go

Start with one finite HTTP service in one process. This Study teaches package installation, Go syntax and observed outcomes; Product Knowledge remains the single owner of protocol, security, pressure and lifecycle semantics.

Beginner · 01 / 04

Install the Go connector and native SDK

Check the toolchain first. The Go connector uses cgo, so the compiler must produce a binary for the same OS/CPU as the SDK.

Terminal
go version
go env GOOS GOARCH CGO_ENABLED
cc --version

Download coakka-http-runtime-native-2.3.0-<target>.tar.gz and SHA256SUMS from the official release, verify SHA-256 and extract it to sdk/. Then create the module and install the exact major path:

Terminal
mkdir coakka-http-go-study
cd coakka-http-go-study
go mod init example.com/coakka-http-go-study
go get github.com/phuong-tran/coakka-http-runtime-go/[email protected]
/[email protected]
/v2 is part of the module/import path. 2.3 is the Core generation; .2 is the connector revision.
COAKKA_HTTP_SDK
Absolute extracted-SDK path; use Go connector 2.3.2 with native SDK 2.3.0.
CGO_CFLAGS
Points at $COAKKA_HTTP_SDK/include.
CGO_LDFLAGS
Points at $COAKKA_HTTP_SDK/lib and an appropriate deployed loader path.
Installation is not service configuration.

The SDK, compiler and loader path prepare build/run. Listener, route and limits are service intent in the next episode; keep those layers separate during diagnosis.

Read version and artifact identity · Download the Go/SDK release (optional)

Beginner · 02 / 04

Run the first request

Save the complete, v2.3.2-checked source below as main.go.

main.go
package main

import (
	"context"
	"errors"
	"log"
	"net/http"
	"os"
	"os/signal"

	coakkahttp "github.com/phuong-tran/coakka-http-runtime-go/v2"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	if err := serve(ctx); err != nil {
		log.Fatal(err)
	}
}

func serve(ctx context.Context) (err error) {
	service, err := coakkahttp.NewBuilder().
		Listen("127.0.0.1", 0).
		Get("/hello/{name}", func(request *coakkahttp.Request) (coakkahttp.Response, error) {
			name := request.PathParameters[0].EncodedValue
			return coakkahttp.Text(http.StatusOK, "hello "+name)
		}).
		Start()
	if err != nil {
		return err
	}
	defer func() {
		err = errors.Join(err, service.Close())
	}()

	port, err := service.Port()
	if err != nil {
		return err
	}
	log.Printf("listening on http://127.0.0.1:%d", port)
	<-ctx.Done()
	return nil
}

Run it in the terminal with the SDK environment:

Terminal
go run .

In a second terminal, replace the port with the printed value:

curl -i http://127.0.0.1:49321/hello/Ada

HTTP/1.1 200 OK
...
hello Ada
Listen("127.0.0.1", 0)
Bind loopback; zero asks the OS for an available port. Read the effective port only after Start().
Get("/hello/{name}", handler)
Register a GET route and Go handler. {name} is an encoded path capture.
Start()
Copy/freeze the declaration, validate it and create the live service. The builder is single-use.
service.Close()
Stop admission, wait for admitted work and close ownership. The example joins operation and close errors.

Follow the shared request lifecycle

Beginner · 03 / 04

Read the request and build a response

Inside the handler, *coakkahttp.Request is a safe Go-owned projection. The sample uses the first capture and returns a buffered response.

name := request.PathParameters[0].EncodedValue
return coakkahttp.Text(http.StatusOK, "hello "+name)
PathParameters
Captures follow route order. EncodedValue is not business-decoded; the application decodes and validates it.
Headers
Name lookup is case-insensitive; ordered entries and duplicate values remain available.
Bytes() / Text()
Read a buffered body within its bound. Large/incremental uploads belong to a stream route.
Text(status, body)
Build a buffered response. The application chooses business status/body; Core validates, accounts and writes transport.

Try /hello/a%2Fb?tag=one&tag=two. The capture keeps the encoded slash and query entries remain ordered. Do not split the raw URL or lose duplicates in a map.

Look up path, query, headers, body and trailers

Beginner · 04 / 04

Read the right failure stage and close the owner

Call /missing to see an HTTP 404 before the handler. Then have the handler return an error: that is an application failure and must not be collapsed with route miss, pressure or timeout.

ObservationRead it in GoDo not infer
Start() errorPreserve *coakkahttp.StartError/*coakkahttp.Error and structured result.A partially ready service.
HTTP 404/503/504Identify the stage and runtime/application owner.Every 5xx came from the handler.
Close() errorInspect *coakkahttp.CloseError; keep the service when RuntimeRetained.The owner may be dropped or restarted.
Context/signal endsApp-host intent begins close.Admitted work already settled.

High-level Service.Close owns the graceful sequence; do not invent another Drain() on this API. Low-level Runtime requires the caller to keep readers/handlers progressing, then use Drain/WaitDrained before close.

Failure stages · Finite shutdown

Advanced · 05

Learn one capability at a time, then combine them

Each first file opens one endpoint to preserve one mental model. Once the three contracts are clear, open the integration exercise to compare them in one service.

01 · File deliveryAuthority, relative path and limits; CoAkka HTTP Runtime selects sendfile when eligible.
file.go
package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"

	coakkahttp "github.com/phuong-tran/coakka-http-runtime-go/v2"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	if err := serveFile(ctx); err != nil {
		panic(err)
	}
}

func serveFile(ctx context.Context) (err error) {
	root, err := os.MkdirTemp("", "coakka-http-file-")
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, os.RemoveAll(root)) }()
	if err = os.WriteFile(filepath.Join(root, "manual.txt"), []byte("CoAkka file delivery\n"), 0o600); err != nil {
		return err
	}

	service, err := coakkahttp.NewBuilder().
		Listen("127.0.0.1", 0).
		FileAuthority(coakkahttp.FileAuthority{
			ID: 1, RootPath: root, MaxActiveFiles: 4, MaxFileBytes: 1024,
		}).
		Get("/download", func(*coakkahttp.Request) (coakkahttp.Response, error) {
			return coakkahttp.ServeFile(http.StatusOK, coakkahttp.Headers{}, 1, "/manual.txt")
		}).
		Start()
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, service.Close()) }()

	port, err := service.Port()
	if err != nil {
		return err
	}
	fmt.Printf("curl http://127.0.0.1:%d/download\n", port)
	<-ctx.Done()
	return nil
}
Run
go run file.go
02 · Server-Sent EventsTwo one-way events, typed fields and a finite terminal.
sse.go
package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"os/signal"

	coakkahttp "github.com/phuong-tran/coakka-http-runtime-go/v2"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	if err := serveSSE(ctx); err != nil {
		panic(err)
	}
}

func serveSSE(ctx context.Context) (err error) {
	events, err := coakkahttp.NewSSEResponse(coakkahttp.Headers{}, func(writer *coakkahttp.SSEWriter) error {
		if writeErr := writer.Write(coakkahttp.SSEEvent{
			Data: []byte("ready"), EventType: "state", ID: "1", RetryMillis: 1000,
			HasEventType: true, HasID: true, HasRetry: true,
		}); writeErr != nil {
			return writeErr
		}
		return writer.Write(coakkahttp.SSEEvent{Data: []byte("done")})
	})
	if err != nil {
		return err
	}

	service, err := coakkahttp.NewBuilder().
		Listen("127.0.0.1", 0).
		Get("/events", func(*coakkahttp.Request) (coakkahttp.Response, error) {
			return events, nil
		}).
		Start()
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, service.Close()) }()

	port, err := service.Port()
	if err != nil {
		return err
	}
	fmt.Printf("curl -N http://127.0.0.1:%d/events\n", port)
	<-ctx.Done()
	return nil
}
Run
go run sse.go
03 · WebSocketSubprotocol, OPEN and TEXT within one bidirectional session.
websocket.go
package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"os/signal"

	coakkahttp "github.com/phuong-tran/coakka-http-runtime-go/v2"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	if err := serveWebSocket(ctx); err != nil {
		panic(err)
	}
}

func serveWebSocket(ctx context.Context) (err error) {
	socket, err := coakkahttp.NewWebSocketResponse(
		"coakka.demo",
		func(session *coakkahttp.WebSocketSession, event coakkahttp.SocketEvent) error {
			switch event.Kind {
			case coakkahttp.WebSocketOpen:
				return session.SendText("ready")
			case coakkahttp.WebSocketText:
				return session.SendText("echo: " + string(event.Data))
			}
			return nil
		},
	)
	if err != nil {
		return err
	}

	service, err := coakkahttp.NewBuilder().
		Listen("127.0.0.1", 0).
		WebSocket("/socket", func(*coakkahttp.Request) (coakkahttp.Response, error) {
			return socket, nil
		}).
		Start()
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, service.Close()) }()

	port, err := service.Port()
	if err != nil {
		return err
	}
	fmt.Printf("new WebSocket('ws://127.0.0.1:%d/socket', 'coakka.demo')\n", port)
	<-ctx.Done()
	return nil
}
Run
go run websocket.go
04 · Combine them in one serviceAn optional integration exercise with three endpoints.
advanced.go
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"

	coakkahttp "github.com/phuong-tran/coakka-http-runtime-go/v2"
)

const fileAuthorityID uint64 = 1

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	if err := serveAdvanced(ctx); err != nil {
		log.Fatal(err)
	}
}

func serveAdvanced(ctx context.Context) (err error) {
	root, err := os.MkdirTemp("", "coakka-http-advanced-")
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, os.RemoveAll(root)) }()
	if err = os.WriteFile(filepath.Join(root, "manual.txt"), []byte("CoAkka file delivery\n"), 0o600); err != nil {
		return err
	}

	events, err := coakkahttp.NewSSEResponse(coakkahttp.Headers{}, func(writer *coakkahttp.SSEWriter) error {
		if writeErr := writer.Write(coakkahttp.SSEEvent{
			Data: []byte("ready"), EventType: "state", ID: "1", RetryMillis: 1000,
			HasEventType: true, HasID: true, HasRetry: true,
		}); writeErr != nil {
			return writeErr
		}
		return writer.Write(coakkahttp.SSEEvent{Data: []byte("done")})
	})
	if err != nil {
		return err
	}

	socket, err := coakkahttp.NewWebSocketResponse(
		"coakka.demo",
		func(session *coakkahttp.WebSocketSession, event coakkahttp.SocketEvent) error {
			switch event.Kind {
			case coakkahttp.WebSocketOpen:
				return session.SendText("ready")
			case coakkahttp.WebSocketText:
				return session.SendText("echo: " + string(event.Data))
			case coakkahttp.WebSocketClose:
				log.Printf("WebSocket closed with code %d", event.CloseCode)
			}
			return nil
		},
	)
	if err != nil {
		return err
	}

	service, err := coakkahttp.NewBuilder().
		Listen("127.0.0.1", 0).
		FileAuthority(coakkahttp.FileAuthority{
			ID: fileAuthorityID, RootPath: root, MaxActiveFiles: 4, MaxFileBytes: 1024,
		}).
		Get("/download", func(*coakkahttp.Request) (coakkahttp.Response, error) {
			return coakkahttp.ServeFile(http.StatusOK, coakkahttp.Headers{}, fileAuthorityID, "/manual.txt")
		}).
		Get("/events", func(*coakkahttp.Request) (coakkahttp.Response, error) {
			return events, nil
		}).
		WebSocket("/socket", func(*coakkahttp.Request) (coakkahttp.Response, error) {
			return socket, nil
		}).
		Start()
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, service.Close()) }()

	port, err := service.Port()
	if err != nil {
		return err
	}
	fmt.Printf("file: curl http://127.0.0.1:%d/download\n", port)
	fmt.Printf("SSE:  curl -N http://127.0.0.1:%d/events\n", port)
	fmt.Printf("WS:   new WebSocket('ws://127.0.0.1:%d/socket', 'coakka.demo')\n", port)
	<-ctx.Done()
	return nil
}
Run the integration
go run advanced.go

Look up parameters, failures and monitoring signals.

TaskGo 2.3.2 surfaceRead the contract
Incremental uploadPostStream and request body readerRequest stream
Multi-chunk responseNewStreamingResponse, ResponseStreamWriter.WriteWritability + terminal
Authorized fileFileAuthority, ServeFileConfined authority
Server-Sent EventsNewSSEResponse, SSEWriter.WriteSSE session
WebSocketNewWebSocketResponse, WebSocketSessionFrame/session bounds

Every producer stays finite, respects write pressure and returns on cancellation/close. The connector copies submitted chunks; that never permits an unbounded application queue in front of the writer.

Find all feature guides · Try gzip · Run the upload labs · Resume a large upload

Advanced · 06

Call outbound HTTP through a logical target

Keep the episode 2 server running. Create client/main.go from the complete source below and pass its port.

client/main.go
package main

import (
	"errors"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"
	"time"

	coakkahttp "github.com/phuong-tran/coakka-http-runtime-go/v2"
)

func main() {
	if len(os.Args) != 2 {
		log.Fatal("usage: go run ./client <server-port>")
	}
	port, err := strconv.ParseUint(os.Args[1], 10, 16)
	if err != nil || port == 0 {
		log.Fatalf("invalid server port %q", os.Args[1])
	}
	if err := call(uint16(port)); err != nil {
		log.Fatal(err)
	}
}

func call(port uint16) (err error) {
	const host = "127.0.0.1"
	target := coakkahttp.OutboundTarget{
		Name:       "hello",
		Generation: 1,
		Endpoints: []coakkahttp.OutboundEndpoint{{
			NodeID:        "local",
			ConnectHost:   host,
			ConnectPort:   port,
			HTTPAuthority: net.JoinHostPort(host, strconv.Itoa(int(port))),
		}},
	}
	service, err := coakkahttp.NewBuilder().OutboundTarget(target).Start()
	if err != nil {
		return err
	}
	defer func() {
		err = errors.Join(err, service.Close())
	}()

	callID, err := service.SubmitOutbound(coakkahttp.ClientRequest{
		LogicalTarget: target.Name,
		Method:        http.MethodGet,
		Target:        "/hello/Ada",
		TimeoutMillis: 3000,
	})
	if err != nil {
		return err
	}
	result, err := service.TakeOutbound(5 * time.Second)
	if err != nil {
		return err
	}
	if result == nil {
		return errors.New("no outbound result within five seconds")
	}
	if result.Call != callID || result.Reason != coakkahttp.OutboundResponse {
		return fmt.Errorf("unexpected outbound result for %v: %s", result.Call, result.Reason)
	}
	fmt.Printf("%d %s\n", result.ResponseStatus, result.ResponseBody)
	return nil
}
Terminal 2
go run ./client 
200 hello Ada
LogicalTarget
A declared dependency name; caller input does not select an arbitrary destination.
ConnectHost/Port
The TCP destination. HTTPAuthority is HTTP authority; TLS peer identity is a third fact under TLS.
TimeoutMillis
A call progress budget, not proof that an effect did not happen.
Call + Reason
Match exact call identity and typed terminal. HTTP 404/500 is still OutboundResponse.

Read reason, phase, retry and certainty before retrying

Advanced · 07

Live control and Monitor without local guesses

The Go surface projects effective route/control facts and bounded Monitor. Treat them as Core truth, not a local cache.

TaskGo APIInvariant
Read the route cutservice.Routes()Complete coherent snapshot; errors return no partial guess.
Change a handlerPrepareHandler + RebindHandlerExpected generation/revision; admitted requests keep old binding.
Change structurePublishRoutesOne complete route generation, not individual patches.
Read health/livenessHealth + bounded probeDirect truth does not require Monitor.
Enable/read MonitorBuilder.Monitor, config/snapshot/read/wait/interruptReserve before start; cursor/loss facts; one waiter.

Handler rebind, route publication and retirement · Health, liveness, Monitor and exporter boundary

Advanced · 08

Capacity, lifecycle and Go quick reference

Zero-valued optional limits select bounded Core defaults. After Start, call service.RuntimeInfo() and read info.Limits rather than echoing builder input.

High-level service
NewBuilder → routes/options → Start → handler work → checked Close.
Low-level runtime
Open(Config) → Start → one goroutine per take lane → respond/release → drain/wait → close.
Buffered response
Text, Bytes, Empty; Core copies submitted bytes synchronously.
Failure
*coakkahttp.Error, StartError, DrainError, CloseError; branch on typed facts.
Evidence
Module + SDK hash, loaded path, OS/CPU, RuntimeInfo/info.Limits, workload, terminal/loss/drain facts.
  • Pair the Go connector 2.3.2 with native SDK 2.3.0.
  • Bind loopback for Study; public ingress is a separate deployment decision.
  • Keep every queue/body/stream/wait finite.
  • Never retry business work from timeout or a runtime retry hint alone.
  • Do not drop a service when close reports a retained owner.

Cross-check the package guide on GitHub (optional)