Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 134 additions & 0 deletions .github/workflows/update-doc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# SPDX-FileCopyrightText: Copyright 2015-2026 go-swagger maintainers
# SPDX-License-Identifier: Apache-2.0

name: "Update documentation"

permissions:
contents: read

on:
push:
tags:
- v*
branches: [ "master" ]
paths:
- docs/**
- hack/doc-site/**
- .github/workflows/update-doc.yml

pull_request:
paths:
- docs/**
- hack/doc-site/**
- .github/workflows/update-doc.yml

concurrency:
group: "pages"
cancel-in-progress: false

defaults:
run:
shell: bash

jobs:
build-doc:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
fetch-depth: '1'
submodules: recursive
# No sparse-checkout: the `code` shortcode mounts the repo root
# (assets/examples ← ../../..) to embed the real example sources,
# which live in top-level dirs (cli/, task-tracker/, …), not under
# docs/. A sparse checkout of hack/+docs/ would leave those files
# absent and every `code` shortcode would fail to resolve its asset.
-
name: Get all tags [go-swagger repo]
if: ${{ github.repository == 'go-swagger/examples' }}
run: |
git fetch origin --prune --update-shallow --tags 'refs/tags/*:refs/tags/*'
-
name: Get all tags [fork]
if: ${{ github.repository != 'go-swagger/examples' }}
run: |
git remote add upstream "https://github.com/go-swagger/examples"
git fetch upstream --prune --update-shallow --tags 'refs/tags/*:refs/tags/*'
git fetch origin --prune --update-shallow --tags 'refs/tags/*:refs/tags/*'
-
name: Initialize theme
env:
RELEARN_VERSION: 9.0.3
run: |
cd hack/doc-site/hugo

# Clone theme
curl -sL -o relearn.tgz https://github.com/McShelby/hugo-theme-relearn/archive/refs/tags/"${RELEARN_VERSION}".tar.gz
tar xf relearn.tgz
rm -rf themes/hugo-relearn
mv "hugo-theme-relearn-${RELEARN_VERSION}" hugo-relearn
mv hugo-relearn themes/
-
name: Prepare config
run: |
# Builds a commit-dependant extra config to inject parameterization.
# HUGO doesn't support config from the command line.
#
# Set specific parameters that are used in some parameterized document.
# This is used to keep up-to-date installation instructions.
cd hack/doc-site/hugo

ROOT=$(git rev-parse --show-toplevel)
VERSION_MESSAGE="Documentation set for latest master."
REQUIRED_GO_VERSION=$(grep "^go\s" "${ROOT}"/go.mod|cut -d" " -f2)
LATEST_RELEASE=$(git tag --list --sort -version:refname 'v*' 2>/dev/null | head -1 || echo "dev")
BUILD_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

echo " Latest release: ${LATEST_RELEASE}"
echo " Go version: ${REQUIRED_GO_VERSION}"
echo " Build time: ${BUILD_TIME}"
echo " Version message: ${VERSION_MESSAGE}"

# Generate dynamic config
cat examples.yaml.template \
| sed "s|{{ GO_VERSION }}|${REQUIRED_GO_VERSION}|g" \
| sed "s|{{ LATEST_RELEASE }}|${LATEST_RELEASE}|g" \
| sed "s|{{ VERSION_MESSAGE }}|${VERSION_MESSAGE}|g" \
| sed "s|{{ BUILD_TIME }}|${BUILD_TIME}|g" \
> examples.yaml
-
name: Build site with Hugo
uses: crazy-max/ghaction-hugo@d629f74d3e4a9da53050610da35a59863ab9b26c # v3.3.0
with:
version: v0.153.3 # <- pin the HUGO version, as they often break things
extended: true
args: --config hugo.yaml,examples.yaml --buildDrafts --cleanDestinationDir --minify --printPathWarnings --ignoreCache --noBuildLock --logLevel info --source ${{ github.workspace }}/hack/doc-site/hugo
-
name: Upload artifact
uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
with:
path: hack/doc-site/hugo/public

deploy-doc:
if: ${{ github.event_name != 'pull_request' }}
needs: build-doc
outputs:
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
-
name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@cd2ce8fcbc39b97be8ca5fce6e763baed58fa128 # v5.0.0
-
name: Report URL
run: |
echo "::notice::Deployed doc site to ${{ steps.deployment.outputs.page_url }}"
4 changes: 4 additions & 0 deletions alias-compatibility/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,16 @@
// swagger:meta
package demo

// snippet:aliases

// Identifier represents a unique identifier.
type Identifier string

// UserID is an alias to Identifier for user-specific IDs.
type UserID = Identifier

// endsnippet:aliases

// User represents a user in the system.
type User struct {
ID UserID `json:"id"`
Expand Down
2 changes: 2 additions & 0 deletions authentication/restapi/configure_auth_sample.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,15 @@ func configureAPI(api *operations.AuthSampleAPI) http.Handler {
api.JSONProducer = runtime.JSONProducer()

// Applies when the "x-token" header is set
// snippet:keyauth
if api.KeyAuth == nil {
api.KeyAuth = func(token string) (*models.Principal, error) {
_ = token

return nil, errors.NotImplemented("api key auth (key) x-token from header param [x-token] has not yet been implemented")
}
}
// endsnippet:keyauth

// Set your custom authorizer if needed. Default one is security.Authorized()
// Expected interface runtime.Authorizer
Expand Down
2 changes: 2 additions & 0 deletions authentication/swagger.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ consumes:
- application/keyauth.api.v1+json
produces:
- application/keyauth.api.v1+json
# snippet:security
securityDefinitions:
key:
type: apiKey
in: header
name: x-token
security:
- key: []
# endsnippet:security
paths:
/customers:
post:
Expand Down
4 changes: 4 additions & 0 deletions auto-configure/implementation/todos_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ type TodosHandlerImpl struct {
idx int64
}

// snippet:add-one

func (i *TodosHandlerImpl) AddOne(params todos.AddOneParams, principal any) middleware.Responder {
_ = principal

Expand All @@ -41,6 +43,8 @@ func (i *TodosHandlerImpl) AddOne(params todos.AddOneParams, principal any) midd
return todos.NewAddOneCreated().WithPayload(newItem)
}

// endsnippet:add-one

func (i *TodosHandlerImpl) DestroyOne(params todos.DestroyOneParams, principal any) middleware.Responder {
_ = principal

Expand Down
4 changes: 4 additions & 0 deletions composed-auth/auth/authorizers.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ func init() {

// Customized authorizer methods for our sample API

// snippet:is-registered

// IsRegistered determines if the user is properly registered,
// i.e if a valid username:password pair has been provided.
func IsRegistered(user, pass string) (*models.Principal, error) {
Expand All @@ -66,6 +68,8 @@ func IsRegistered(user, pass string) (*models.Principal, error) {
}, nil
}

// endsnippet:is-registered

// IsReseller tells if the API key is a JWT signed by us with a claim to be a reseller.
func IsReseller(token string) (*models.Principal, error) {
claims, err := parseAndCheckToken(token)
Expand Down
2 changes: 2 additions & 0 deletions composed-auth/restapi/configure_multi_auth_example.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ func configureAPI(api *operations.MultiAuthExampleAPI) http.Handler {

api.JSONProducer = runtime.JSONProducer()

// snippet:wiring
api.HasRoleAuth = func(token string, scopes []string) (*models.Principal, error) {
// The header: Authorization: Bearer {base64 string} (or ?access_token={base 64 string} param) has already
// been decoded by the runtime as a token
Expand All @@ -59,6 +60,7 @@ func configureAPI(api *operations.MultiAuthExampleAPI) http.Handler {
api.Logger("ResellerQueryAuth handler called")
return auth.IsReseller(token)
}
// endsnippet:wiring

// Set your custom authorizer if needed. Default one is security.Authorized()
// Expected interface runtime.Authorizer
Expand Down
4 changes: 4 additions & 0 deletions composed-auth/swagger.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ schemes:
- http # https in a normal setup
basePath: /api
securityDefinitions:
# snippet:schemes
isRegistered:
# This scheme uses the header: "Authorization: Basic {base64 encoded string defined by username:password}"
# Scopes are not supported with this type of authorization.
Expand Down Expand Up @@ -71,6 +72,7 @@ securityDefinitions:
scopes:
customer: scope of registered customers
inventoryManager: scope of resellers acting as inventory managers
# endsnippet:schemes

# Default Security requirements for all operations
security:
Expand Down Expand Up @@ -140,13 +142,15 @@ paths:
Registered customers should be able to add purchase orders.
Registered inventory managers should be able to add replenishment orders.

# snippet:composed-security
security:
- isRegistered: []
hasRole: [ customer ]
- isReseller: []
hasRole: [ inventoryManager ]
- isResellerQuery: []
hasRole: [ inventoryManager ]
# endsnippet:composed-security
parameters:
- name: order
in: body
Expand Down
82 changes: 82 additions & 0 deletions docs/doc-site/_index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
---
title: "go-swagger examples"
type: home
description: 'Runnable examples and tutorials for go-swagger spec-first code generation'
weight: 1
---

A curated collection of **runnable examples** for
[`go-swagger`](https://github.com/go-swagger/go-swagger) — generating servers,
clients and CLIs from an OpenAPI 2.0 (Swagger) spec.

Every example here is committed to the
[go-swagger/examples](https://github.com/go-swagger/examples) repository and kept
in sync with the latest go-swagger release by automated regeneration.

### Status

{{% button href="https://github.com/go-swagger/examples/fork" hint="fork me on github" style=primary icon=code-fork %}}Fork me{{% /button %}}
Actively maintained. Regenerated weekly against `swagger@master`.

### Which site do I want?

These examples are all **spec-first**: you have an OpenAPI spec and want
`swagger generate` to produce typed code. The sibling sites cover the other two
approaches — pick by what you start from:

| I start from… | I want… | Go here |
|---------------|---------|---------|
| an **OpenAPI spec** | generate a typed server / client / CLI | **this site** |
| **Go interfaces**, no codegen | hand-wire an untyped client or server | [go-openapi/runtime](https://go-openapi.github.io/runtime/) |
| **Go code** | produce a spec *from* the code (code-first) | [go-openapi/codescan](https://go-openapi.github.io/codescan/) |

### New to go-swagger?

Install the toolchain and read the command reference on go-swagger's own site:

```cmd
go install github.com/go-swagger/go-swagger/cmd/swagger@latest
```

→ [go-swagger.io](https://goswagger.io/go-swagger/) for install, the `generate`
command families, and project-layout reference. This site assumes you have
`swagger` on your `PATH` and focuses on **what to build with it**.

### Where to go next

{{< cards >}}
{{% card title="Guides" %}}
The example catalog, grouped by concern — servers, clients & CLI, authentication,
streaming, and codegen customization. One page per example.

→ [guides](./guides/)
{{% /card %}}

{{% card title="Tutorials" %}}
Sequential, end-to-end walkthroughs. Start with the todo-list tutorial to build a
server and client from scratch.

→ [tutorials](./tutorials/)
{{% /card %}}

{{% card title="Project" %}}
Repository README, licensing, contributing guidelines and how the examples stay in
sync with go-swagger.

→ [project](./project/)
{{% /card %}}
{{< /cards >}}

## Licensing

`SPDX-FileCopyrightText: Copyright 2025 go-swagger maintainers`

These examples ship under the [Apache-2.0 license](./project/LICENSE.md).

## Contributing

Issues and pull requests welcome. See [project/](./project/) for guidelines.

---

{{< children type="card" description="true" >}}
14 changes: 14 additions & 0 deletions docs/doc-site/guides/_index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
title: Guides
weight: 2
description: |
The example catalog, grouped by concern. Each page covers one runnable example:
what it demonstrates, the spec excerpt, the generate command, how to run it, and
the key generated files to look at.
---

Browse by concern. Every guide maps to a directory in the
[go-swagger/examples](https://github.com/go-swagger/examples) repository, so you can
clone it and run the code alongside the page.

{{< children type="card" description="true" >}}
15 changes: 15 additions & 0 deletions docs/doc-site/guides/authentication/_index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
title: Authentication
weight: 3
description: |
Wiring security into a generated server — basic and API-key auth, composed
security requirements, and a full OAuth2 access-code handshake.
---

{{% notice info %}}
These examples wire authentication into **generated** servers. Looking to
hand-wire auth on an untyped runtime server instead? See the
[runtime auth examples](https://go-openapi.github.io/runtime/usage/examples/auth/).
{{% /notice %}}

{{< children type="card" description="true" >}}
Loading
Loading