apikit

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2026 License: MIT Imports: 4 Imported by: 0

README

APIKit

Tests Go Report Card GoDoc

Code generator for Go HTTP handlers. Automatically generates request parsing, validation, and response handling from annotated handler functions.

Features

  • 🚀 Zero boilerplate - Focus on business logic, not HTTP parsing
  • 🔌 Multi-framework - Supports http, Fiber, Gin, and Echo
  • Validation - Built-in struct validation with go-playground/validator
  • 📝 Type-safe - Full type safety with generics
  • go:generate - Seamless integration with Go toolchain

Installation

go install github.com/kausys/apikit/cmd/apikit@latest

Quick Start

1. Define your handler
//go:generate apikit generate

// GetUserRequest defines the parameters for GetUser
type GetUserRequest struct {
    UserID string `path:"id" validate:"required,uuid"`
    Fields string `query:"fields"`
}

type GetUserResponse struct {
    ID    string `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

// apikit:handler
func GetUser(ctx context.Context, req GetUserRequest) (GetUserResponse, error) {
    // Your business logic here
    return GetUserResponse{ID: req.UserID, Name: "John"}, nil
}
2. Generate the wrapper
go generate ./...
3. Use with your framework
// Standard http
mux.HandleFunc("GET /users/{id}", getUserAPIKit(GetUser))

// Fiber
app.Get("/users/:id", getUserAPIKit(GetUser))

// Gin
router.GET("/users/:id", getUserAPIKit(GetUser))

// Echo
e.GET("/users/:id", getUserAPIKit(GetUser))

Parameter Sources

Tag Source Example
path:"name" URL path parameter /users/{id}
query:"name" Query string ?filter=active
header:"name" HTTP header X-API-Key
cookie:"name" Cookie session_id
form:"name" Form field multipart/form-data
json:"name" JSON body Request body

Validation

Uses go-playground/validator:

type CreateUserRequest struct {
    Email    string `json:"email" validate:"required,email"`
    Password string `json:"password" validate:"required,min=8"`
    Age      int    `json:"age" validate:"gte=18,lte=120"`
}

Framework Selection

# Standard http (default)
apikit generate

# Fiber
apikit generate --framework fiber

# Gin
apikit generate --framework gin

# Echo
apikit generate --framework echo

Special Fields

Access raw HTTP primitives when needed:

type StreamRequest struct {
    Request  *http.Request       // Access full request
    Writer   http.ResponseWriter // Access response writer
    RawBody  []byte              // Raw request body
}

File Uploads

type UploadRequest struct {
    File  *multipart.FileHeader   `form:"file"`
    Files []*multipart.FileHeader `form:"files"`
}

CLI Reference

apikit generate [flags]

Flags:
  -f, --file string        Source file (defaults to $GOFILE)
  -o, --output string      Output file (defaults to <source>_apikit.go)
      --framework string   Target framework: http, fiber, gin, echo (default "http")
      --force              Force regeneration
      --dry-run            Show output without writing
  -v, --verbose            Verbose output

License

MIT License - see LICENSE for details.

Documentation

Overview

Package apikit provides runtime helpers for APIKit-generated code

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInternalServer is a generic internal server error
	ErrInternalServer = InternalError("internal server error")

	// ErrSomethingWentWrong is a generic internal server error
	ErrSomethingWentWrong = InternalError("something went wrong")

	// ErrNotImplemented indicates the feature is not implemented
	ErrNotImplemented = NotImplemented("not implemented")

	// ErrUnauthorized indicates authentication is required
	ErrUnauthorized = Unauthorized("authentication required")

	// ErrForbidden indicates access is denied
	ErrForbidden = Forbidden("access denied")

	// ErrInvalidRequest indicates the request is invalid
	ErrInvalidRequest = BadRequest("invalid request")
)
View Source
var CommonTimeFormats = []string{
	time.RFC3339,
	"2006-01-02T15:04:05",
	"2006-01-02T15:04:05.999",
	"2006-01-02T15:04:05.999Z",
	"2006-01-02T15:04:05.999-07:00",
	"2006-01-02 15:04:05",
	"2006-01-02",
}

CommonTimeFormats are the formats tried by NewTimeFromString

Functions

func HandleError

func HandleError(w http.ResponseWriter, err error)

HandleError handles errors with custom status codes

func HandleResponse

func HandleResponse(w http.ResponseWriter, response any, err error)

HandleResponse handles both the response and error from a handler This is the main function used by generated code

func NewTimeFromString

func NewTimeFromString(s string) (time.Time, error)

NewTimeFromString parses a time string using common formats This function is used by APIKit-generated code to parse time.Time fields

Supported formats (tried in order):

  • RFC3339: "2006-01-02T15:04:05Z07:00"
  • "2006-01-02T15:04:05"
  • "2006-01-02T15:04:05.999"
  • "2006-01-02T15:04:05.999Z"
  • "2006-01-02T15:04:05.999-07:00"
  • "2006-01-02 15:04:05"
  • "2006-01-02"

Returns the parsed time.Time or an error if no format matches

func WriteJSON

func WriteJSON(w http.ResponseWriter, data any)

WriteJSON writes a JSON response with default 200 OK status

Types

type Error

type Error struct {
	// HTTP status code
	Code int `json:"code"`

	// Semantic error code for client handling
	ErrorCode string `json:"errorCode,omitempty"`

	// Human-readable error message
	Message string `json:"message"`

	// Additional error details
	Details any `json:"details,omitempty"`

	// Request ID for correlation
	RequestID string `json:"requestId,omitempty"`
	// contains filtered or unexported fields
}

Error represents an API error with an HTTP status code

func BadRequest

func BadRequest(message string) *Error

BadRequest creates a 400 error

func Conflict

func Conflict(message string) *Error

Conflict creates a 409 error

func Forbidden

func Forbidden(message string) *Error

Forbidden creates a 403 error

func GatewayTimeout

func GatewayTimeout(message string) *Error

GatewayTimeout creates a 504 error

func InternalError

func InternalError(message string) *Error

InternalError creates a 500 error

func NewError

func NewError(code int, message string) *Error

NewError creates a new API error with the given status code and message

func NewErrorWithDetails

func NewErrorWithDetails(code int, message string, details any) *Error

NewErrorWithDetails creates a new API error with additional details

func NewErrorf

func NewErrorf(code int, format string, args ...any) *Error

NewErrorf creates a new API error with a formatted message

func NotAcceptable

func NotAcceptable(message string) *Error

NotAcceptable creates a 406 error

func NotFound

func NotFound(resource string) *Error

NotFound creates a 404 error

func NotImplemented

func NotImplemented(message string) *Error

NotImplemented creates a 501 error

func ServiceUnavailable

func ServiceUnavailable(message string) *Error

ServiceUnavailable creates a 503 error

func Unauthorized

func Unauthorized(message string) *Error

Unauthorized creates a 401 error

func UnprocessableEntity

func UnprocessableEntity(message string) *Error

UnprocessableEntity creates a 422 error

func WrapError

func WrapError(code int, message string, cause error) *Error

WrapError wraps an existing error with an API error

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface

func (*Error) StatusCode

func (e *Error) StatusCode() int

StatusCode returns the HTTP status code for this error

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error for error chain support

func (*Error) WithCause

func (e *Error) WithCause(cause error) *Error

WithCause wraps an underlying error

func (*Error) WithDetails

func (e *Error) WithDetails(details any) *Error

WithDetails adds details to the error

func (*Error) WithRequestID

func (e *Error) WithRequestID(requestID string) *Error

WithRequestID adds request ID to the error

type HttpResponse

type HttpResponse struct {
	StatusCode  int               `json:"statusCode"`
	Body        any               `json:"body"`
	Headers     map[string]string `json:"headers"`
	ContentType string            `json:"contentType"`
}

HttpResponse represents an HTTP response with status code, body, headers, and content type

func NewHttpResponse

func NewHttpResponse(statusCode int, body any) *HttpResponse

NewHttpResponse creates a new HttpResponse with the given status code and body

func (*HttpResponse) WithContentType

func (r *HttpResponse) WithContentType(contentType string) *HttpResponse

WithContentType sets a custom content type

func (*HttpResponse) WithHeader

func (r *HttpResponse) WithHeader(key, value string) *HttpResponse

WithHeader adds a single header to the response

func (*HttpResponse) WithHeaders

func (r *HttpResponse) WithHeaders(headers map[string]string) *HttpResponse

WithHeaders adds custom headers to the response

Directories

Path Synopsis
Package ast provides generic AST parsing capabilities for Go source files.
Package ast provides generic AST parsing capabilities for Go source files.
cmd
apikit command
Package codegen generates Go code from parsed handler information using extractors
Package codegen generates Go code from parsed handler information using extractors
Package extractors provides framework-specific parameter extraction for HTTP handlers
Package extractors provides framework-specific parameter extraction for HTTP handlers
Package parser provides AST parsing capabilities for Go source files.
Package parser provides AST parsing capabilities for Go source files.
Package types provides a type system for converting string values to Go types during request parsing.
Package types provides a type system for converting string values to Go types during request parsing.

Jump to

Keyboard shortcuts

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