Even though Gothic Framework leverages HTMX for most interactions, there are cases where you need to return JSON responses instead of HTML. For example, when building endpoints for external clients, mobile apps, or third-party integrations.
For these cases, you can create API routes in the src/api folder. These routes follow the same file-based routing pattern and are automatically registered, but instead of returning HTML templates, they return JSON or other data formats.
Here is a simple example of an API route that returns a JSON response:
// src/api/hello.go
package api
import (
"encoding/json"
"net/http"
routes "github.com/felipegenef/gothicframework/v2/pkg/helpers/routes"
)
type HelloWorldResponse struct {
Message string `json:"message"`
}
var HelloWorldConfig = routes. ApiRouteConfig {
HttpMethod: routes. GET ,
}
func HelloWorld (w http.ResponseWriter , r *http.Request ) {
response, _ := json.Marshal(HelloWorldResponse{
Message: "Hello World from GOTH API ROUTE" ,
})
w.Header().Set( "Content-Type" , "application/json" )
w.WriteHeader(http.StatusOK)
w.Write(response)
} The route will be automatically registered at /api/hello based on the file location. When called, it returns:
{
"message" : "Hello World from GOTH API ROUTE"
} Note: Unlike page routes that use RouteConfig, API routes use ApiRouteConfig. The only required field is HttpMethod. You can also set Type (STATIC, ISR, or DYNAMIC) and RevalidateInSec to control how API responses are cached. By default, API routes are DYNAMIC (no caching).
Here is an example of a cached API route using ISR (Incremental Static Regeneration) that revalidates every 60 seconds:
var HelloWorldConfig = routes. ApiRouteConfig {
HttpMethod: routes. GET ,
Type: routes. ISR ,
RevalidateInSec: 60 ,
} With ISR, the first request renders and caches the response. Subsequent requests within the TTL window are served from cache. After expiration, the next request triggers a fresh render and re-caches the result. Use STATIC for responses that never change, or DYNAMIC (the default) for responses that should always be fresh.
Now that you know how to create API routes, learn how to improve navigation with the Link Component for preloading pages!