Skip to Content
HTTPRoutingRouting

Routing

GoFrame provides a powerful routing system that automatically discovers and generates routes based on special comments in your handler methods. The system supports hierarchical package organization and generates type-safe clients for both Go and TypeScript.

Overview

The routing system consists of several components:

Hierarchical Package Structure

GoFrame supports a hierarchical package structure where handlers can be organized into root packages and subfolders:

internal/ ├── v1handler/ # Root package │ ├── router.go # Generated router │ ├── registry.go # Generated registry │ ├── handler_user.go # Root level handlers │ ├── profile/ # Subpackage │ │ └── handler_profile.go │ └── admin/ # Subpackage │ └── handler_admin.go └── v2handler/ # Another root package ├── router.go ├── registry.go └── handler_user.go

Root packages contain both router.go and registry.go files and serve as entry points. Subpackages contain only handler files and are automatically discovered and included in the root package’s router.

Route Definition

Routes are can be defined using goframe:http_route annotations above handler methods:

handler_user.go
// goframe:http_route path=/users method=GET func (h *UserHandler) GetUsers() http.HandlerFunc { return httpx.Wrap(func(r *http.Request) (httpx.Response, error) { // Implementation return httpx.JSON.OK(users), nil }) } // goframe:http_route path=/users/{id} method=GET func (h *UserHandler) GetUser() http.HandlerFunc { return httpx.Wrap(func(r *http.Request) (httpx.Response, error) { id := r.PathValue("id") // Implementation return httpx.JSON.OK(user), nil }) }

The benefit of using apidoc Annotations is that it provides a clear and concise way to define routes and their corresponding handlers, making it easier to manage and maintain the routing logic of an application because it provides type save code generation for routes, TypeScript client and url helper generation.

Generated Router

The system automatically generates router registration code:

router.go
func Router(p RouterParams) { p.Mux.HandleFunc("GET /users", p.UserHandler.GetUsers()) p.Mux.HandleFunc("GET /users/{id}", p.UserHandler.GetUser()) // Handlers from subpackages are automatically included }

Routes follow Go 1.22 http.ServeMux syntax: HTTP method followed by the path. Path parameters are automatically extracted by params.Bind when tagged with path:"id".

Generation Commands

CommandDescription
bin/goframe g routerGenerate router registration code
bin/goframe g handler <name>Generate handler code
bin/goframe g route <handler name> <route name>Generate route code
bin/goframe g url-helperGenerate type-safe URL helpers
bin/goframe g clientGenerate TypeScript client
Last updated on