Docs/Core Concepts/API Route Handlers

API Route Handlers

Create powerful, typed backend REST API endpoints using App Router file-based conventions.

GoKS lets you build pure backend REST APIs alongside your frontend without leaving theapp/directory. Simply place aroute.goinsideapp/api/**/.

Security Isolation:Files insideapp/api/are strictly server-side. The GoKS compiler ensures they are never bundled into the client WebAssembly binary.

Supported HTTP Methods

Export uppercase Go functions matching HTTP verbs:GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD:

app/api/users/route.go
go
package users

import (
	"net/http"
	"github.com/misbakhul29/goks/pkg/router"
)

type CreateUserRequest struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

// GET /api/users
func GET(c *router.Context) error {
	role := c.Query("role") // Query parameter (?role=admin)
	return c.JSON(http.StatusOK, map[string]string{"status": "ok", "role": role})
}

// POST /api/users
func POST(c *router.Context) error {
	var body CreateUserRequest
	if err := c.BindJSON(&body); err != nil {
		return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid json"})
	}

	return c.JSON(http.StatusCreated, map[string]any{
		"message": "user created",
		"user":    body,
	})
}

Dynamic Path Parameters

Support for path parameters works with both[id](Next.js style) or:id(Go style) folder naming:

app/api/users/[id]/route.go
go
package details

import (
	"net/http"
	"github.com/misbakhul29/goks/pkg/router"
)

// GET /api/users/:id or /api/users/[id]
func GET(c *router.Context) error {
	userID := c.Param("id")
	return c.JSON(http.StatusOK, map[string]string{
		"id":   userID,
		"name": "Jane Doe",
	})
}

Helper Context Methods

  • c.BindJSON(&dest): Parses and validates incoming JSON payload.
  • c.JSON(statusCode, data): Serializes data as JSON response.
  • c.Param("key"): Extracts dynamic URL path segment.
  • c.Query("key"): Reads URL query string value.
  • c.Header("name"): Reads incoming HTTP header.
Powered byGoKS WASM16 topics