October 6, 2026

Add Beautiful API Docs to Your Go Backend with Scalar

Add Beautiful API Docs to Your Go Backend with Scalar

Reference: Build a Go Backend with Gin, GORM, JWT and Docker and the code in my own kooza-collinz-portfolio-backend repository.

backstory

After I finished my Go backend, I had a problem. I had more than twenty endpoints, and I kept forgetting them.

  • Was it /users/verify-email or /users/verify?
  • Does the contact form need a name field, or just email and message?
  • Which routes need a token, and which ones are public?

I was testing everything with curl and Postman, and my frontend friends kept asking me, "What do I send to this endpoint?"

Then I found Scalar. It gives you a clean, dark-mode documentation website for your API, and the best part is that you can test your endpoints right inside the page. No Postman needed.

This guide shows you how I added it to my Go backend. I go slowly, one small step at a time, and every step answers three questions:

  1. What does it do?
  2. Why do it this way?
  3. What does it help with?

By the end you will have:

  • A documentation website at http://localhost:8080/docs
  • A raw OpenAPI file at http://localhost:8080/docs/openapi.json
  • Every endpoint listed, with the exact JSON it expects
  • A built-in tester where you can sign up, log in, paste your token, and call protected routes

[!NOTE] This guide uses the real endpoints from my portfolio backend (users, contact, audit logs, analytics). You can copy them as they are, or swap in your own.

what we are building

Here is a picture of how everything fits together:

   Browser  ->  http://localhost:8080/docs
                      |
                      v
        [docs.RegisterRoutes]  (our new package)
           |                         |
           v                         v
   GET /docs                  GET /docs/openapi.json
   (the pretty Scalar page)   (the raw API description)
           |                         |
           +-----------+-------------+
                       |
                       v
              OpenAPISpec()  <-- one Go string that describes ALL our endpoints

The new folder layout looks like this. Only the docs/ folder is new:

kooza-collinz-portfolio-backend/
├── cache/
├── config/
├── controllers/
├── docs/               <-- NEW
│   ├── openapi.go      <-- describes our API (the "menu")
│   └── routes.go       <-- serves the Scalar page
├── dtos/
├── initializers/
├── middleware/
├── models/
├── main.go
└── .env

what are OpenAPI and Scalar? (in simple words)

Two names will keep coming up, so let's explain them first.

OpenAPI is a standard way to describe an API in a JSON (or YAML) file. Think of it like a restaurant menu. The menu does not cook anything. It just lists what the kitchen can make, what each dish is called, and what you need to order it.

Our OpenAPI file lists:

  • every URL (like /api/v1/users/login)
  • the method each URL uses (GET, POST, PATCH, DELETE)
  • what JSON you must send
  • what JSON you get back
  • which routes need a login token

Scalar is the program that reads that menu and draws a beautiful website from it. It also adds a Test Request button, so you can "order" straight from the menu.

So the job is split in two:

PieceWho writes itWhat it is
The OpenAPI specWe write itThe menu (a big JSON string in Go)
The Scalar pageScalar makes itThe website that reads the menu

[!TIP] Because OpenAPI is a standard, the same JSON file also works in Postman, Insomnia, and code generators. Write it once, use it everywhere.

prerequisites

You need a working Go and Gin backend. If you don't have one yet, follow my Go backend guide first.

ToolWhy you need itHow to check (run this)
Go (1.22 or newer)The language we are coding ingo version
A Gin projectThe server we are adding docs toopen your main.go
A web browserTo see the docs page(you have this already 😄)

Your project should already have a go.mod file at the root and a main.go that creates a Gin router:

router := gin.Default()

If you see that line, you are ready.

step 1: install the Scalar package

Open your terminal in the project root (the folder that contains go.mod) and run:

go get github.com/MarceloPetrucio/go-scalar-api-reference
go mod tidy

What does each command do?

  • go get ... downloads the Scalar package and adds it to your go.mod file (your project's shopping list).
  • go mod tidy cleans up go.mod and go.sum. It removes things you don't use and adds anything missing.

Why this package? Scalar is a JavaScript project. This Go package wraps it, so we can create the whole Scalar page with a single Go function call, without writing HTML ourselves.

What does it help with? Without this step, Go will not know what scalar means, and your editor will show a red error.

[!WARNING] If you skip this step you will see this error in your editor: could not import github.com/MarceloPetrucio/go-scalar-api-reference (no required module provides package ...)

The fix is just to run the two commands above, then restart your Go language server (in VS Code press Ctrl+Shift+P and run Go: Restart Language Server).

Also, your spell checker (cSpell) may underline "Petrucio" as an unknown word. That is only the spell checker. It has nothing to do with Go and does not break anything.

step 2: create the docs folder

mkdir docs

What does it do? Makes a new folder called docs.

Why this way? In Go, every folder is a package. By putting all documentation code in its own package, main.go stays clean. main.go only needs one line to turn the docs on, and if you ever want to remove the docs, you delete one folder and one line.

What does it help with? It follows the same "one folder, one job" idea as controllers/, models/, and middleware/.

Now create two empty files inside it:

touch docs/openapi.go docs/routes.go
  • docs/openapi.go will hold the menu (the OpenAPI spec).
  • docs/routes.go will hold the code that serves the pages.

[!NOTE] On Windows PowerShell, touch may not work. Use New-Item docs/openapi.go and New-Item docs/routes.go, or just create the files in VS Code.

step 3: write the OpenAPI spec (the menu)

This is the biggest step, so we will build it in small pieces first, then put it all together.

The spec is a JSON document. We will keep it inside a Go function that returns a string. Open docs/openapi.go.

3a. the empty shell

package docs
 
// OpenAPISpec returns the OpenAPI 3.0 JSON spec.
func OpenAPISpec() string {
	return `{
  "openapi": "3.0.3",
  "info": {
    "title": "Kooza Collins Portfolio API",
    "description": "REST API for the Kooza Collins portfolio site. Built with Go, Gin and GORM.",
    "version": "1.0.0"
  },
  "servers": [
    { "url": "http://localhost:8080", "description": "Local development" }
  ],
  "tags": [
    { "name": "Users", "description": "Sign up, log in, verify email, reset password and manage profiles" },
    { "name": "Contact", "description": "Public contact form and admin inbox" },
    { "name": "OAuth", "description": "Social login (browser redirects)" },
    { "name": "Admin", "description": "Audit logs and analytics (admin only)" }
  ],
  "paths": {},
  "components": {}
}`
}

Let's go through it line by line.

LineWhat it doesWhy we need it
package docsSays this file belongs to the docs package.Must match the folder name, so other files can use docs.OpenAPISpec().
func OpenAPISpec() stringA function that returns text.routes.go will call it. One function means one source of truth.
return followed by a backtickStarts a raw string.Backticks let us write many lines and double quotes without escaping every ". This is what makes pasting JSON easy.
"openapi": "3.0.3"The version of the OpenAPI standard we follow.Scalar reads this first to know how to understand the rest.
"info"The title, description, and version of our API.Scalar shows this at the top of the page (the "Introduction").
"servers"The base URL of our API.When you click Send, Scalar sends the request to this address. In production, add your real domain here.
"tags"Groups for our endpoints.Each tag becomes a folder in the left sidebar (Users, Contact, ...).
"paths": {}The list of endpoints. Empty for now.This is where the real work goes (step 3b).
"components": {}Reusable pieces. Empty for now.Step 3c fills this in.

[!WARNING] Never use a backtick inside the JSON. A backtick would end the Go raw string early and break your code. JSON does not need backticks, so this is easy to avoid.

3b. describe one endpoint: sign up

Here is the sign-up endpoint. It goes inside "paths". It matches my real route POST /api/v1/users:

"/api/v1/users": {
  "post": {
    "tags": ["Users"],
    "summary": "Sign up",
    "description": "Creates a new account and emails a 6-digit verification code.",
    "requestBody": {
      "required": true,
      "content": {
        "application/json": {
          "schema": { "$ref": "#/components/schemas/CreateUserRequest" }
        }
      }
    },
    "responses": {
      "201": {
        "description": "Account created",
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/UserSuccess" }
          }
        }
      },
      "400": { "$ref": "#/components/responses/Error" },
      "409": { "$ref": "#/components/responses/Error" }
    }
  }
}

Line by line:

LineWhat it doesWhy we need it
"/api/v1/users"The URL path.Must match the route in main.go exactly: v1.Group("/users") plus users.POST("").
"post"The HTTP method.The same URL can have get, post, patch, delete side by side.
"tags": ["Users"]Puts this endpoint under the Users group.Must match a name from the tags list above.
"summary"A short title.This is the name you see in the sidebar.
"description"A longer explanation.Helps your teammates understand what really happens.
"requestBody"What the client must send.Scalar uses it to build the Body editor with example JSON.
"required": trueThe body cannot be empty.Scalar warns you if it is.
"application/json"The body type is JSON.Matches c.ShouldBindJSON(...) in the controller.
"$ref": "#/components/schemas/CreateUserRequest""Look it up in the components section."$ref is a pointer. We write the shape once and reuse it, instead of copying it everywhere.
"responses"Every possible answer.Each status code is a different outcome.
"201"Success. A new user was created.Matches http.StatusCreated in SignUpWithToken.
"400"Bad input, such as a missing field.Matches the validation error in the controller.
"409"The email is already taken.Matches http.StatusConflict in the controller.

What does it help with? Anyone who opens the docs now knows exactly how to create a user, what comes back, and what can go wrong.

[!TIP] Always compare your spec with your controller code. The spec is a promise. If your controller returns 409 for a duplicate email, then your docs should say 409 too.

3c. describe a protected endpoint

Some endpoints need a login token. Here is GET /api/v1/users/validate:

"/api/v1/users/validate": {
  "get": {
    "tags": ["Users"],
    "summary": "Validate current session",
    "description": "Returns the logged-in user. Requires a valid token.",
    "security": [{ "bearerAuth": [] }],
    "responses": {
      "200": {
        "description": "Current user",
        "content": {
          "application/json": {
            "schema": { "$ref": "#/components/schemas/UserSuccess" }
          }
        }
      },
      "401": { "$ref": "#/components/responses/Error" }
    }
  }
}

The new line is this one:

"security": [{ "bearerAuth": [] }]

What does it do? It says "this endpoint needs the security scheme called bearerAuth." We define that scheme in the components section (next step).

Why this way? In main.go, this route has middleware.RequireAuthWithToken. This line is the documentation version of that middleware. Scalar will show a small lock icon and will automatically add the Authorization: Bearer <token> header when you send a request.

What about public routes? Just leave "security" out. That is why Sign up has no lock.

3d. endpoints with a path parameter

Some URLs contain an ID, like /api/v1/users/5. In OpenAPI we write the ID inside curly braces:

"/api/v1/users/{id}": {
  "get": {
    "tags": ["Users"],
    "summary": "Get user by ID",
    "security": [{ "bearerAuth": [] }],
    "parameters": [
      { "name": "id", "in": "path", "required": true, "schema": { "type": "integer" }, "example": 1 }
    ],
    "responses": {
      "200": {
        "description": "The user",
        "content": { "application/json": { "schema": { "$ref": "#/components/schemas/UserSuccess" } } }
      },
      "404": { "$ref": "#/components/responses/Error" }
    }
  }
}
LineWhat it doesWhy we need it
"/api/v1/users/{id}"The curly braces mean "this part changes."In Gin we write /:id. In OpenAPI the same idea is written as {id}. Don't mix them up.
"parameters"Extra inputs that are not in the body.Scalar shows a small input box for id.
"in": "path"The value lives in the URL path.Other options are query (like ?page=2) and header.
"type": "integer"The ID is a number.In my project User.ID is a uint, so it is a whole number.
"example": 1A pre-filled value.Saves you from typing it every time you test.

3e. the components section: reusable pieces

At the bottom of the spec we define the things we pointed at with $ref. This is the "components" part:

"components": {
  "securitySchemes": {
    "bearerAuth": {
      "type": "http",
      "scheme": "bearer",
      "bearerFormat": "JWT",
      "description": "Paste the token you got from the Login endpoint."
    }
  },
  "schemas": {
    "CreateUserRequest": {
      "type": "object",
      "required": ["first_name", "last_name", "email", "password"],
      "properties": {
        "first_name": { "type": "string", "minLength": 2, "maxLength": 100, "example": "Kooza" },
        "last_name":  { "type": "string", "minLength": 2, "maxLength": 100, "example": "Collins" },
        "email":      { "type": "string", "format": "email", "example": "kooza@example.com" },
        "password":   { "type": "string", "minLength": 6, "maxLength": 100, "example": "secret123" }
      }
    }
  },
  "responses": {
    "Error": {
      "description": "Something went wrong",
      "content": {
        "application/json": {
          "schema": { "$ref": "#/components/schemas/ErrorResponse" }
        }
      }
    }
  }
}

securitySchemes is where we define bearerAuth:

  • "type": "http" and "scheme": "bearer" mean "send the token in the Authorization: Bearer ... header."
  • "bearerFormat": "JWT" is just a label that tells the reader the token is a JWT.
  • This creates the Select Auth Type box on the Scalar page, where you paste your token once.

schemas are the shapes of our JSON. Look at CreateUserRequest. It is the same as my Go DTO:

type CreateUserRequest struct {
	FirstName string `json:"first_name" binding:"required,min=2,max=100"`
	LastName  string `json:"last_name" binding:"required,min=2,max=100"`
	Email     string `json:"email" binding:"required,email"`
	Password  string `json:"password" binding:"required,min=6,max=100"`
}

See how each part lines up:

Go DTO tagOpenAPI schema
json:"first_name"the key "first_name"
binding:"required"listed in "required": [...]
min=2,max=100"minLength": 2, "maxLength": 100
email"format": "email"
string"type": "string"

And the "example" values are what Scalar puts in the Body editor for you. Choose realistic ones, because they are what readers will click Send with.

responses holds reusable answers. We define Error once and point to it from every endpoint with { "$ref": "#/components/responses/Error" }. That way we never repeat ourselves.

[!NOTE] My API wraps every answer in the same envelope: success, data, message, error. That is why our schemas below have a success field and a data field. Your docs should show the real response shape, not just the inner data.

3f. the complete docs/openapi.go

Here is the whole file, with all my real endpoints. Copy it into docs/openapi.go.

package docs
 
// OpenAPISpec returns the OpenAPI 3.0 JSON spec.
func OpenAPISpec() string {
	return `{
  "openapi": "3.0.3",
  "info": {
    "title": "Kooza Collins Portfolio API",
    "description": "REST API for the Kooza Collins portfolio site. Built with Go, Gin and GORM.",
    "version": "1.0.0"
  },
  "servers": [
    { "url": "http://localhost:8080", "description": "Local development" }
  ],
  "tags": [
    { "name": "Users", "description": "Sign up, log in, verify email, reset password and manage profiles" },
    { "name": "Contact", "description": "Public contact form and admin inbox" },
    { "name": "OAuth", "description": "Social login (browser redirects)" },
    { "name": "Admin", "description": "Audit logs and analytics (admin only)" }
  ],
  "paths": {
    "/api/v1/users": {
      "post": {
        "tags": ["Users"],
        "summary": "Sign up",
        "description": "Creates a new account and emails a 6-digit verification code.",
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateUserRequest" } } }
        },
        "responses": {
          "201": {
            "description": "Account created",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/UserSuccess" } } }
          },
          "400": { "$ref": "#/components/responses/Error" },
          "409": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/v1/users/login": {
      "post": {
        "tags": ["Users"],
        "summary": "Login",
        "description": "Returns a JWT token. The email must be verified first.",
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoginUserRequest" } } }
        },
        "responses": {
          "200": {
            "description": "Login successful",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoginSuccess" } } }
          },
          "400": { "$ref": "#/components/responses/Error" },
          "401": { "$ref": "#/components/responses/Error" },
          "403": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/v1/users/validate": {
      "get": {
        "tags": ["Users"],
        "summary": "Validate current session",
        "description": "Returns the logged-in user. Requires a valid token.",
        "security": [{ "bearerAuth": [] }],
        "responses": {
          "200": {
            "description": "Current user",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/UserSuccess" } } }
          },
          "401": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/v1/users/verify-email": {
      "post": {
        "tags": ["Users"],
        "summary": "Verify email with code",
        "description": "Checks the 6-digit code from the email. On success the account is verified and a token is returned.",
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/VerifyEmailRequest" } } }
        },
        "responses": {
          "200": {
            "description": "Email verified",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LoginSuccess" } } }
          },
          "400": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/v1/users/resend-verification": {
      "post": {
        "tags": ["Users"],
        "summary": "Resend verification code",
        "description": "Always answers with the same message, whether the account exists or not.",
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/EmailRequest" } } }
        },
        "responses": {
          "200": {
            "description": "Code sent (if the account exists)",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MessageSuccess" } } }
          }
        }
      }
    },
    "/api/v1/users/forgot-password": {
      "post": {
        "tags": ["Users"],
        "summary": "Request a password reset",
        "description": "Emails a reset link. Always answers with the same message, whether the account exists or not.",
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/EmailRequest" } } }
        },
        "responses": {
          "200": {
            "description": "Reset email sent (if the account exists)",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MessageSuccess" } } }
          }
        }
      }
    },
    "/api/v1/users/reset-password": {
      "post": {
        "tags": ["Users"],
        "summary": "Reset password with token",
        "description": "Uses the token from the reset email link. The token works only once.",
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResetPasswordRequest" } } }
        },
        "responses": {
          "200": {
            "description": "Password changed",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MessageSuccess" } } }
          },
          "400": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/v1/users/{id}": {
      "get": {
        "tags": ["Users"],
        "summary": "Get user by ID",
        "security": [{ "bearerAuth": [] }],
        "parameters": [
          { "name": "id", "in": "path", "required": true, "schema": { "type": "integer" }, "example": 1 }
        ],
        "responses": {
          "200": {
            "description": "The user",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/UserSuccess" } } }
          },
          "401": { "$ref": "#/components/responses/Error" },
          "404": { "$ref": "#/components/responses/Error" }
        }
      },
      "patch": {
        "tags": ["Users"],
        "summary": "Update user profile",
        "description": "Send only the fields you want to change.",
        "security": [{ "bearerAuth": [] }],
        "parameters": [
          { "name": "id", "in": "path", "required": true, "schema": { "type": "integer" }, "example": 1 }
        ],
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/UpdateUserRequest" } } }
        },
        "responses": {
          "200": {
            "description": "Updated user",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/UserSuccess" } } }
          },
          "401": { "$ref": "#/components/responses/Error" },
          "404": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/v1/contact": {
      "post": {
        "tags": ["Contact"],
        "summary": "Send a contact message",
        "description": "Public endpoint. Limited to 5 messages per IP address per hour.",
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateContactMessageRequest" } } }
        },
        "responses": {
          "201": {
            "description": "Message saved",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ContactMessageSuccess" } } }
          },
          "400": { "$ref": "#/components/responses/Error" },
          "429": { "$ref": "#/components/responses/Error" }
        }
      },
      "get": {
        "tags": ["Contact"],
        "summary": "List contact messages (admin)",
        "description": "Newest first. The list is cached in Redis for 60 seconds.",
        "security": [{ "bearerAuth": [] }],
        "responses": {
          "200": {
            "description": "All messages",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ContactMessageListSuccess" } } }
          },
          "401": { "$ref": "#/components/responses/Error" },
          "403": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/v1/contact/{id}": {
      "get": {
        "tags": ["Contact"],
        "summary": "Get one contact message (admin)",
        "security": [{ "bearerAuth": [] }],
        "parameters": [
          { "name": "id", "in": "path", "required": true, "schema": { "type": "integer" }, "example": 1 }
        ],
        "responses": {
          "200": {
            "description": "The message",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ContactMessageSuccess" } } }
          },
          "401": { "$ref": "#/components/responses/Error" },
          "403": { "$ref": "#/components/responses/Error" },
          "404": { "$ref": "#/components/responses/Error" }
        }
      },
      "patch": {
        "tags": ["Contact"],
        "summary": "Update a contact message (admin)",
        "security": [{ "bearerAuth": [] }],
        "parameters": [
          { "name": "id", "in": "path", "required": true, "schema": { "type": "integer" }, "example": 1 }
        ],
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/UpdateContactMessageRequest" } } }
        },
        "responses": {
          "200": {
            "description": "Updated message",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ContactMessageSuccess" } } }
          },
          "401": { "$ref": "#/components/responses/Error" },
          "403": { "$ref": "#/components/responses/Error" },
          "404": { "$ref": "#/components/responses/Error" }
        }
      },
      "delete": {
        "tags": ["Contact"],
        "summary": "Delete a contact message (admin)",
        "security": [{ "bearerAuth": [] }],
        "parameters": [
          { "name": "id", "in": "path", "required": true, "schema": { "type": "integer" }, "example": 1 }
        ],
        "responses": {
          "200": {
            "description": "Message deleted",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MessageSuccess" } } }
          },
          "401": { "$ref": "#/components/responses/Error" },
          "403": { "$ref": "#/components/responses/Error" },
          "404": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/v1/audit-logs": {
      "get": {
        "tags": ["Admin"],
        "summary": "List audit logs (admin)",
        "description": "A history of important actions such as signups, logins and password resets.",
        "security": [{ "bearerAuth": [] }],
        "responses": {
          "200": {
            "description": "Paginated audit logs",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/GenericSuccess" } } }
          },
          "401": { "$ref": "#/components/responses/Error" },
          "403": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/v1/analytics/overview": {
      "get": {
        "tags": ["Admin"],
        "summary": "Analytics overview (admin)",
        "security": [{ "bearerAuth": [] }],
        "responses": {
          "200": {
            "description": "Overview numbers for the dashboard",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/GenericSuccess" } } }
          },
          "401": { "$ref": "#/components/responses/Error" },
          "403": { "$ref": "#/components/responses/Error" }
        }
      }
    },
    "/api/v1/auth/google": {
      "get": {
        "tags": ["OAuth"],
        "summary": "Continue with Google",
        "description": "Open this URL in the browser. It redirects to Google. After sign-in, Google sends the user back to the frontend with a token in the URL. Test this in a browser tab, not with the Send button.",
        "responses": { "302": { "description": "Redirect to Google" } }
      }
    },
    "/api/v1/auth/github": {
      "get": {
        "tags": ["OAuth"],
        "summary": "Continue with GitHub",
        "description": "Open this URL in the browser. It redirects to GitHub. After sign-in, GitHub sends the user back to the frontend with a token in the URL.",
        "responses": { "302": { "description": "Redirect to GitHub" } }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT",
        "description": "Paste the token you got from the Login endpoint."
      }
    },
    "schemas": {
      "CreateUserRequest": {
        "type": "object",
        "required": ["first_name", "last_name", "email", "password"],
        "properties": {
          "first_name": { "type": "string", "minLength": 2, "maxLength": 100, "example": "Kooza" },
          "last_name": { "type": "string", "minLength": 2, "maxLength": 100, "example": "Collins" },
          "email": { "type": "string", "format": "email", "example": "kooza@example.com" },
          "password": { "type": "string", "minLength": 6, "maxLength": 100, "example": "secret123" }
        }
      },
      "LoginUserRequest": {
        "type": "object",
        "required": ["email", "password"],
        "properties": {
          "email": { "type": "string", "format": "email", "example": "kooza@example.com" },
          "password": { "type": "string", "minLength": 6, "maxLength": 100, "example": "secret123" },
          "remember_me": { "type": "boolean", "example": false, "description": "true keeps you logged in for 30 days, false for 24 hours" }
        }
      },
      "VerifyEmailRequest": {
        "type": "object",
        "required": ["email", "code"],
        "properties": {
          "email": { "type": "string", "format": "email", "example": "kooza@example.com" },
          "code": { "type": "string", "example": "042817", "description": "The 6-digit code from the email" }
        }
      },
      "EmailRequest": {
        "type": "object",
        "required": ["email"],
        "properties": {
          "email": { "type": "string", "format": "email", "example": "kooza@example.com" }
        }
      },
      "ResetPasswordRequest": {
        "type": "object",
        "required": ["token", "password"],
        "properties": {
          "token": { "type": "string", "description": "The token from the reset link in the email" },
          "password": { "type": "string", "minLength": 6, "maxLength": 100, "example": "newSecret456" }
        }
      },
      "UpdateUserRequest": {
        "type": "object",
        "properties": {
          "first_name": { "type": "string", "example": "Kooza" },
          "last_name": { "type": "string", "example": "Collins" },
          "job_title": { "type": "string", "example": "Photographer" },
          "bio": { "type": "string", "example": "I tell stories with a camera." },
          "avatar": { "type": "string", "example": "https://example.com/avatar.jpg" }
        }
      },
      "CreateContactMessageRequest": {
        "type": "object",
        "required": ["name", "email", "message"],
        "properties": {
          "name": { "type": "string", "example": "Jane Doe" },
          "email": { "type": "string", "format": "email", "example": "jane@example.com" },
          "message": { "type": "string", "example": "Hi! I loved your portfolio. Are you free for a project next month?" }
        }
      },
      "UpdateContactMessageRequest": {
        "type": "object",
        "properties": {
          "read": { "type": "boolean", "example": true },
          "reply": { "type": "string", "example": "Thanks Jane! Yes, let's talk." }
        }
      },
      "User": {
        "type": "object",
        "properties": {
          "id": { "type": "integer", "example": 1 },
          "first_name": { "type": "string", "example": "Kooza" },
          "last_name": { "type": "string", "example": "Collins" },
          "email": { "type": "string", "format": "email", "example": "kooza@example.com" },
          "role": { "type": "string", "enum": ["ADMIN", "USER"], "example": "USER" },
          "avatar": { "type": "string", "example": "" },
          "job_title": { "type": "string", "example": "" },
          "active": { "type": "boolean", "example": true },
          "created_at": { "type": "string", "format": "date-time" },
          "updated_at": { "type": "string", "format": "date-time" }
        }
      },
      "LoginData": {
        "type": "object",
        "properties": {
          "id": { "type": "integer", "example": 1 },
          "first_name": { "type": "string", "example": "Kooza" },
          "last_name": { "type": "string", "example": "Collins" },
          "email": { "type": "string", "format": "email", "example": "kooza@example.com" },
          "role": { "type": "string", "example": "USER" },
          "token": { "type": "string", "description": "The JWT. Copy it and use it as the Bearer token." },
          "expires_in": { "type": "integer", "example": 86400, "description": "Seconds until the token expires" }
        }
      },
      "ContactMessage": {
        "type": "object",
        "properties": {
          "id": { "type": "integer", "example": 1 },
          "name": { "type": "string", "example": "Jane Doe" },
          "email": { "type": "string", "format": "email", "example": "jane@example.com" },
          "message": { "type": "string", "example": "Hi! I loved your portfolio." },
          "read": { "type": "boolean", "example": false },
          "replied": { "type": "boolean", "example": false },
          "reply": { "type": "string", "nullable": true },
          "replied_at": { "type": "string", "format": "date-time", "nullable": true },
          "created_at": { "type": "string", "format": "date-time" }
        }
      },
      "UserSuccess": {
        "type": "object",
        "properties": {
          "success": { "type": "boolean", "example": true },
          "message": { "type": "string", "example": "User retrieved successfully" },
          "data": { "$ref": "#/components/schemas/User" }
        }
      },
      "LoginSuccess": {
        "type": "object",
        "properties": {
          "success": { "type": "boolean", "example": true },
          "message": { "type": "string", "example": "Login successful" },
          "data": { "$ref": "#/components/schemas/LoginData" }
        }
      },
      "MessageSuccess": {
        "type": "object",
        "properties": {
          "success": { "type": "boolean", "example": true },
          "message": { "type": "string", "example": "Done" }
        }
      },
      "ContactMessageSuccess": {
        "type": "object",
        "properties": {
          "success": { "type": "boolean", "example": true },
          "message": { "type": "string", "example": "Thanks for reaching out! I'll get back to you soon" },
          "data": { "$ref": "#/components/schemas/ContactMessage" }
        }
      },
      "ContactMessageListSuccess": {
        "type": "object",
        "properties": {
          "success": { "type": "boolean", "example": true },
          "data": { "type": "array", "items": { "$ref": "#/components/schemas/ContactMessage" } }
        }
      },
      "GenericSuccess": {
        "type": "object",
        "properties": {
          "success": { "type": "boolean", "example": true },
          "data": { "type": "object" }
        }
      },
      "ErrorResponse": {
        "type": "object",
        "properties": {
          "success": { "type": "boolean", "example": false },
          "error": { "type": "string", "example": "Invalid email or password" },
          "message": { "type": "string" }
        }
      }
    },
    "responses": {
      "Error": {
        "description": "Something went wrong",
        "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }
      }
    }
  }
}`
}

[!NOTE] A few field names in this spec (the verify-email code, the reset-password token, and the contact reply) come from how my controllers work. If your DTOs use different names, change them here so the docs match your real code. The docs are only as good as they are accurate.

Why one big string instead of a .json file? Because a Go string is compiled into your program. When you deploy, there is no extra file to forget to upload. It is also the simplest thing that works.

What does it help with? We now have one place that describes the whole API. Both the Scalar page and the raw JSON link read from this one function.

step 4: write docs/routes.go (serve the docs)

Open docs/routes.go and paste this:

package docs
 
import (
	"net/http"
 
	scalar "github.com/MarceloPetrucio/go-scalar-api-reference"
	"github.com/gin-gonic/gin"
)
 
// RegisterRoutes mounts:
//
//	GET /docs              -> Scalar interactive API reference
//	GET /docs/openapi.json -> OpenAPI 3.0 spec
func RegisterRoutes(r *gin.Engine) {
	r.GET("/docs/openapi.json", func(c *gin.Context) {
		c.Header("Content-Type", "application/json")
		c.String(http.StatusOK, OpenAPISpec())
	})
 
	r.GET("/docs", func(c *gin.Context) {
		html, err := scalar.ApiReferenceHTML(&scalar.Options{
			SpecContent: OpenAPISpec(),
			CustomOptions: scalar.CustomOptions{
				PageTitle: "Kooza Collins Portfolio — API Reference",
			},
			DarkMode: true,
		})
		if err != nil {
			c.String(http.StatusInternalServerError, "Error generating docs: "+err.Error())
			return
		}
		c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(html))
	})
}

This is a short file, but every line matters. Let's go through all of it.

the imports

import (
	"net/http"
 
	scalar "github.com/MarceloPetrucio/go-scalar-api-reference"
	"github.com/gin-gonic/gin"
)
ImportWhat it doesWhy we need it
"net/http"Go's built-in HTTP package.It gives us readable status names like http.StatusOK (200) and http.StatusInternalServerError (500), so we don't type magic numbers.
scalar "github.com/..."The Scalar package we installed in step 1.The word scalar before the path is an alias. The package's real name is long, so we give it a short nickname.
"github.com/gin-gonic/gin"The Gin web framework.We need gin.Engine and gin.Context to build routes.

the function

func RegisterRoutes(r *gin.Engine) {

What does it do? Creates a function that takes our Gin router (r) and adds two routes to it.

Why this way? RegisterRoutes starts with a capital letter, so it is exported. That means other packages (like main) can call it. Putting all the doc routes inside one function means main.go needs just one line to switch the docs on.

route 1: the raw spec

r.GET("/docs/openapi.json", func(c *gin.Context) {
	c.Header("Content-Type", "application/json")
	c.String(http.StatusOK, OpenAPISpec())
})
LineWhat it doesWhy we need it
r.GET("/docs/openapi.json", ...)Creates a GET route at this URL.Anyone can download the spec here.
func(c *gin.Context) { ... }The handler, which runs on each request.c holds the request and the response.
c.Header("Content-Type", "application/json")Tells the browser "this is JSON."Without it, the browser may treat it as plain text. Tools like Postman need the right type to import it.
c.String(http.StatusOK, OpenAPISpec())Sends the spec with status 200.We use c.String and not c.JSON because the spec is already a JSON string. c.JSON would encode it a second time and wrap it in quotes.

What does it help with? You can import this URL into Postman or Insomnia, and it also lets other developers generate client code from it.

route 2: the pretty page

r.GET("/docs", func(c *gin.Context) {
	html, err := scalar.ApiReferenceHTML(&scalar.Options{
		SpecContent: OpenAPISpec(),
		CustomOptions: scalar.CustomOptions{
			PageTitle: "Kooza Collins Portfolio — API Reference",
		},
		DarkMode: true,
	})
LineWhat it doesWhy we need it
r.GET("/docs", ...)A GET route at /docs.This is the page you open in your browser.
html, err := scalar.ApiReferenceHTML(...)Asks the Scalar package to build a complete HTML page and return it as text.Go functions often return two things: the result and an error.
&scalar.Options{ ... }A settings object. The & passes it by pointer, which is what the package expects.This is where we customize the page.
SpecContent: OpenAPISpec()Gives Scalar our menu directly, as text.Important. See the warning below.
CustomOptions: scalar.CustomOptions{ PageTitle: ... }Sets the browser tab title.You see this text on the tab. Make it your project's name.
DarkMode: trueTurns on the dark theme.Matches most developer tools. Set it to false for light mode.

Then comes the error check and the response:

	if err != nil {
		c.String(http.StatusInternalServerError, "Error generating docs: "+err.Error())
		return
	}
	c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(html))
})
LineWhat it doesWhy we need it
if err != nil { ... }If building the page failed, stop here.Go makes you handle errors yourself. Skipping this can hide real problems.
c.String(http.StatusInternalServerError, ...)Sends a 500 with the reason.This is the message that helped me find the Windows bug (see "common errors" below).
returnLeaves the handler.Without it the code would continue and send a second response.
c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(html))Sends the page as HTML.c.Data sends raw bytes with a content type we choose. []byte(html) converts the text to bytes. charset=utf-8 makes sure characters like the — in our title show correctly.

[!WARNING] Why SpecContent and not SpecURL? The first time I set this up, I used SpecURL: "/docs/openapi.json" (which is what the starter kit does). On my Windows machine I got this error:

Error generating docs: error parsing URL: parse "file://D:\\PROJECTS\\...\\docs\\openapi.json": invalid port ...

What happened? The Go package reads the spec on the server, before it sends the page. When it sees a path like /docs/openapi.json (not a full http:// address), it treats it as a file on your hard drive and tries to build a file:// URL. Windows paths contain D:\, and Go cannot parse that.

The fix is SpecContent. We hand over the spec as text, so the package never has to look for a file. It works on Windows, Mac, and Linux.

step 5: connect it in main.go

Open main.go. Add the import for the new package:

import (
	"log"
 
	"github.com/MUKE-coder/gorm-studio/studio"
	"github.com/Watuulo-Richard/kooza-collins-portfolio-backend/config"
	"github.com/Watuulo-Richard/kooza-collins-portfolio-backend/controllers"
	"github.com/Watuulo-Richard/kooza-collins-portfolio-backend/docs" // <-- NEW
	"github.com/Watuulo-Richard/kooza-collins-portfolio-backend/initializers"
	"github.com/Watuulo-Richard/kooza-collins-portfolio-backend/middleware"
	"github.com/Watuulo-Richard/kooza-collins-portfolio-backend/models"
	"github.com/gin-gonic/gin"
)

Then call it right after the router and CORS middleware are created:

func main() {
	router := gin.Default()
	router.Use(middleware.CORSMiddleware())
 
	docs.RegisterRoutes(router) // <-- NEW
 
	v1 := router.Group("/api/v1")
	{
		// ...all your existing routes stay exactly as they are...
	}
 
	// ...OAuth, audit logs, analytics, GORM Studio...
 
	router.Run()
}

What does it do? Calls our function, which adds /docs and /docs/openapi.json to the router.

Why here? We put it after gin.Default() because we need a router to attach routes to. We put it after the CORS middleware so the docs routes also get CORS headers. It sits before the v1 group only so the file reads nicely. Gin does not care about the order of different routes.

What does it help with? Your docs now live in the same server as your API. There is nothing extra to deploy.

[!NOTE] The import path must start with your module name from go.mod. Mine is github.com/Watuulo-Richard/kooza-collins-portfolio-backend. If yours is different, use yours.

step 6: run it and open the docs

Start your server. I use Air for hot reload:

air

(Or just go run . if you don't use Air.)

Look at the terminal. You should see these two new lines among the Gin route logs:

[GIN-debug] GET    /docs/openapi.json        --> .../docs.RegisterRoutes.func1 (4 handlers)
[GIN-debug] GET    /docs                     --> .../docs.RegisterRoutes.func2 (4 handlers)

That means both routes were registered. Now open your browser:

URLWhat you should see
http://localhost:8080/docsThe Scalar documentation page (dark mode)
http://localhost:8080/docs/openapi.jsonThe raw JSON of your spec

On the docs page you will see:

  • Left sidebar: your tags (Users, Contact, OAuth, Admin) and the endpoints inside each.
  • Middle: the description of the selected endpoint.
  • Right side: a Server box, an Authentication box, and code samples (curl, Node.js, Python, and more).

If you see all that, congratulations, Scalar is working! 🎉

[!TIP] If the page is blank, open http://localhost:8080/docs/openapi.json first. If that shows an error or looks broken, your JSON has a typo (usually a missing comma or an extra trailing comma). Fix the JSON and refresh.

step 7: test your API inside Scalar

This is the best part. You don't need Postman anymore. Let's do a full real test, from creating an account to calling a protected route.

7a. sign up (a public endpoint)

  1. In the left sidebar, click Users → Sign up. The page scrolls to that endpoint.
  2. Click the Test Request button (top right of the endpoint panel).
  3. Open the Body tab and make sure JSON is selected. Scalar pre-fills the example values we wrote in the spec.
  4. Change the values to a real email you can open:
{
  "first_name": "Kooza",
  "last_name": "Collins",
  "email": "kooza@example.com",
  "password": "secret123"
}
  1. Click Send.

You should get a 201 Created response like this:

{
  "success": true,
  "message": "Account created! Please check your email for a 6-digit verification code",
  "data": {
    "id": 1,
    "first_name": "Kooza",
    "last_name": "Collins",
    "email": "kooza@example.com",
    "role": "USER"
  }
}

[!NOTE] If you use Mailhog for local development, open http://localhost:8026 to read the verification email. Otherwise check your real inbox.

7b. verify the email

Login is blocked until the email is verified. Click Users → Verify email with code, press Test Request, and send:

{
  "email": "kooza@example.com",
  "code": "042817"
}

Use the real code from your email. A successful answer verifies the account and returns a token.

7c. log in and copy the token

Click Users → Login, press Test Request, and send:

{
  "email": "kooza@example.com",
  "password": "secret123",
  "remember_me": false
}

The response contains a long token:

{
  "success": true,
  "message": "Login successful",
  "data": {
    "id": 1,
    "first_name": "Kooza",
    "last_name": "Collins",
    "email": "kooza@example.com",
    "role": "USER",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "expires_in": 86400
  }
}

Copy the token value (only the long text, without the quotes).

7d. paste the token (once)

  1. Scroll to the top, to the Introduction page (or use the Authentication box on any endpoint).
  2. In the Authentication box, click Select Auth Type.
  3. Choose Bearer Token.
  4. Paste your token.

From now on, every request you send from Scalar includes Authorization: Bearer <your token> automatically. This works because of the bearerAuth scheme we defined in the spec.

7e. call a protected endpoint

Click Users → Validate current session, press Test Request, then Send. You should get your own profile back with 200 OK.

If you remove the token, you get 401 Unauthorized. That is how you can prove your middleware really works.

7f. what about admin endpoints?

Try Contact → List contact messages (admin) with the same token. You will get:

{
  "success": false,
  "error": "Forbidden - Admin access required"
}

(The exact message depends on your RequireAdmin middleware.) That is correct! A normal user must not read the admin inbox. To test it as an admin, open GORM Studio at http://localhost:8080/studio, change that user's role to ADMIN, log in again to get a new token, and paste it in.

7g. test the public contact form

Click Contact → Send a contact message and send:

{
  "name": "Jane Doe",
  "email": "jane@example.com",
  "message": "Hi! I loved your portfolio. Are you free for a project next month?"
}

You should get 201. Try sending it 6 times in one hour from the same IP, and the 6th request returns 429 Too many requests. That is the Redis rate limit working, and now you have tested it without leaving the docs page.

[!TIP] Don't test the OAuth routes (Google, GitHub) with the Send button. They are browser redirects, so open them in a normal browser tab instead, for example http://localhost:8080/api/v1/auth/google.

step 8: protect the docs in production (optional but smart)

Right now anyone can open /docs. For a portfolio project that may be fine, because public docs can even look impressive. But for a real product you may want to hide them. You have two simple options.

option 1: only turn docs on in development

In main.go:

if gin.Mode() != gin.ReleaseMode {
	docs.RegisterRoutes(router)
}

What does it do? gin.Mode() returns debug, release, or test. This code registers the docs only when you are not in release mode.

Why this way? In your .env, you set GIN_MODE=debug on your computer and GIN_MODE=release on your server. So the docs exist on your laptop and disappear in production, with no extra work.

option 2: password-protect the docs

Change RegisterRoutes in docs/routes.go to put the routes inside a group that asks for a username and password:

package docs
 
import (
	"net/http"
	"os"
 
	scalar "github.com/MarceloPetrucio/go-scalar-api-reference"
	"github.com/gin-gonic/gin"
)
 
func RegisterRoutes(r *gin.Engine) {
	docsGroup := r.Group("/docs", gin.BasicAuth(gin.Accounts{
		os.Getenv("DOCS_USER"): os.Getenv("DOCS_PASSWORD"),
	}))
 
	docsGroup.GET("/openapi.json", func(c *gin.Context) {
		c.Header("Content-Type", "application/json")
		c.String(http.StatusOK, OpenAPISpec())
	})
 
	docsGroup.GET("", func(c *gin.Context) {
		html, err := scalar.ApiReferenceHTML(&scalar.Options{
			SpecContent: OpenAPISpec(),
			CustomOptions: scalar.CustomOptions{
				PageTitle: "Kooza Collins Portfolio — API Reference",
			},
			DarkMode: true,
		})
		if err != nil {
			c.String(http.StatusInternalServerError, "Error generating docs: "+err.Error())
			return
		}
		c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(html))
	})
}

And add two lines to your .env:

DOCS_USER=admin
DOCS_PASSWORD=pick-a-long-random-password
LineWhat it doesWhy we need it
r.Group("/docs", gin.BasicAuth(...))Makes a group of routes that all start with /docs and all need a password.The browser shows a login popup before the page loads.
os.Getenv("DOCS_USER")Reads the value from the environment.Never hard-code passwords in your code.
docsGroup.GET("", ...)The page at /docs.An empty string means "the group's own path."
docsGroup.GET("/openapi.json", ...)The spec at /docs/openapi.json.Protected too, so nobody can sneak around the page.

[!WARNING] os.Getenv only sees values that are already loaded. In this project config.Load() loads .env inside init(), which runs before main(), and we call docs.RegisterRoutes inside main(). So the values are ready. If you ever call os.Getenv in a package-level var, it runs too early and will be empty. This is the same trap we met with OAuth in my backend guide.

an alternative: Scalar without the Go package

You don't have to use the Go package. Scalar is only a web page that loads one JavaScript file. You can serve it yourself:

const scalarHTML = `<!doctype html>
<html>
  <head>
    <title>Kooza Collins Portfolio — API Reference</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
  </head>
  <body>
    <script id="api-reference" data-url="/docs/openapi.json" data-configuration='{"darkMode": true}'></script>
    <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
  </body>
</html>`
 
func RegisterRoutes(r *gin.Engine) {
	r.GET("/docs/openapi.json", func(c *gin.Context) {
		c.Header("Content-Type", "application/json")
		c.String(http.StatusOK, OpenAPISpec())
	})
 
	r.GET("/docs", func(c *gin.Context) {
		c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(scalarHTML))
	})
}

What is different?

  • No go get. There is no extra Go dependency.
  • data-url="/docs/openapi.json" is read by the browser, not by Go. The browser downloads the spec from your running server, so the Windows file:// problem cannot happen.
  • The page loads Scalar's JavaScript from a CDN (cdn.jsdelivr.net), so the visitor's browser needs internet access.

Which one should you use? Both work. I use the Go package with SpecContent because it is a single function call and the spec is baked right into the page. Use the CDN version if you want zero extra dependencies.

[!NOTE] If you later add a strict Content-Security-Policy header to your server, remember to allow cdn.jsdelivr.net, or the page will not load its script.

common errors and fixes

These are the real errors I hit (or almost hit) while building this.

1. could not import github.com/MarceloPetrucio/go-scalar-api-reference (no required module provides package ...) You haven't installed the package yet. Run go get github.com/MarceloPetrucio/go-scalar-api-reference and go mod tidy in the folder that contains go.mod. Then restart the Go language server in your editor. If it still fails, check that you are in the right folder, and that your network or proxy is not blocking Go downloads.

2. "Petrucio": Unknown word (cSpell) This is only your spell-checker. It is not a Go error, and your code builds fine. To silence it, add Petrucio to your cSpell dictionary (right-click the word, then choose Add to dictionary).

3. Error generating docs: error parsing URL: parse "file://D:\\..." (500 error on /docs) You used SpecURL: "/docs/openapi.json". The package treats a plain path as a file on disk, and Go cannot parse a Windows drive letter in a file:// URL. Replace SpecURL with SpecContent: OpenAPISpec(). See step 4.

4. The /docs page is blank or says the spec is invalid Open /docs/openapi.json directly. A JSON typo is the usual cause. Common ones: a missing comma between two items, an extra comma after the last item, or an unclosed bracket. Paste the JSON into any JSON validator to find the exact line.

5. Scalar says a $ref cannot be resolved A $ref points at something that doesn't exist, often a typo like #/components/schemas/CreateUserRequst. Names are case-sensitive and must match the schema's key exactly.

6. The Body editor is empty on an endpoint That endpoint has no requestBody in the spec. Add one with a $ref to a schema, as in step 3b.

7. 401 Unauthorized on a protected endpoint, even though I'm logged in You forgot to paste the token in the Authentication box (step 7d), or the token expired (sessions last 24 hours, or 30 days with remember_me). Log in again and paste the new one.

8. 403 Forbidden on contact list, audit logs, or analytics Your user is not an admin. Change the role to ADMIN in GORM Studio, log in again to get a fresh token, and paste it into Scalar.

9. 429 Too many requests when testing the contact form That's the rate limit doing its job (5 per hour per IP). Wait, or clear the key in Redis, or restart the Redis container.

10. My new endpoint doesn't show in the docs Scalar only knows what is in the spec. A new route in main.go does not appear automatically. Add it to docs/openapi.go too, then refresh the page. (Air rebuilds on save, so you only need to refresh the browser.)

11. The docs show a wrong URL when I deploy Update "servers" in the spec. Change http://localhost:8080 to your real API address (for example https://api.yoursite.com), or add it as a second entry so you can switch between local and live.

keeping your docs honest

A hand-written spec is simple, but it has one weakness. If you change a controller and forget to change the spec, the docs lie. Here are three habits that keep them truthful:

  1. Update the spec in the same commit as the route. Make it part of "done."
  2. Test from the docs page. If the Body example in Scalar fails against your real API, one of them is wrong.
  3. Check status codes. Every c.JSON(http.Status..., ...) in a controller should have a matching code in that endpoint's responses.

If your API grows very large, look at swaggo/swag. It generates the spec from comments above your controller functions. You can then give its output to Scalar the same way: pass the generated JSON text as SpecContent.

day-to-day commands

# Install the Scalar package (only once)
go get github.com/MarceloPetrucio/go-scalar-api-reference
go mod tidy
 
# Start the API with hot reload
air
 
# Or run once without reload
go run .
 
# Check for compile errors and common mistakes
go build ./...
go vet ./...

Where to look in the browser while developing:

final checklist

Tick every box. If you can, your docs are ready.

  • go get github.com/MarceloPetrucio/go-scalar-api-reference finished without errors
  • docs/openapi.go and docs/routes.go exist and the project builds (go build ./...)
  • main.go imports the docs package and calls docs.RegisterRoutes(router)
  • The terminal shows GET /docs and GET /docs/openapi.json when the server starts
  • http://localhost:8080/docs shows the Scalar page
  • http://localhost:8080/docs/openapi.json shows valid JSON
  • You can sign up and log in from the Test Request panel
  • You pasted the token in Select Auth Type → Bearer Token
  • Validate current session returns your user
  • A normal user gets 403 on an admin endpoint
  • The servers entry matches the address of your API
  • You decided whether /docs should be public, hidden, or password-protected in production

conclusion

You just gave your backend a real documentation website. Let's recap:

  1. We installed the Scalar Go package with go get.
  2. We made a docs package so the documentation code stays in one place.
  3. We wrote an OpenAPI spec, the "menu" that describes every endpoint, request, response, and lock.
  4. We served the pretty page at /docs and the raw JSON at /docs/openapi.json.
  5. We learned why SpecContent is safer than SpecURL (the Windows file:// bug).
  6. We connected everything with one line in main.go.
  7. We tested sign up, verify, login, a protected route, an admin route, and the rate limit, all without leaving the docs page.
  8. We learned how to hide or password-protect the docs in production.

The best part is how little code it took. Two small Go files and one line in main.go, and now your teammates, your frontend developers, and future you can see exactly how your API works, and try it with one click.

Now go open /docs, and click Test Request. 🚀

resources