Documentation

NexGo Reference

Complete documentation for the NexGo web framework — the Go-powered alternative to Next.js.

v1.0.5 Go 1.22+ Zero Dependencies

Quick Start

Get a NexGo project running in under 2 minutes.

1. Install NexGo

$go install github.com/salmanfaris22/nexgo/cmd/nexgo@v1.0.5

⚠️ PATH Setup (Important):

export PATH=$PATH:$(go env GOPATH)/bin
echo 'export PATH=$PATH:$(go env GOPATH)/bin' >> ~/.bashrc && source ~/.bashrc

2. Create a New Project

nexgo create my-app
cd my-app
go mod tidy
nexgo dev

Open http://localhost:3000 — your app is live with hot reload enabled.

Project Structure

Running nexgo create my-app generates this structure:

my-app/
├── main.go                  # Application entry point
├── nexgo.config.json        # Framework configuration
├── go.mod
│
├── pages/                   # File-based routes
│   ├── index.html           #   → /
│   ├── about.html           #   → /about
│   ├── blog/
│   │   ├── index.html       #   → /blog
│   │   └── [slug].html      #   → /blog/:slug (dynamic)
│   └── api/
│       └── hello.go         #   → /api/hello
│
├── layouts/
│   └── default.html         # Default layout
├── components/              # Reusable partials
├── static/                  # Static assets → /static/
│   ├── css/global.css
│   └── js/
└── .nexgo/out/              # Build output (generated)

File-Based Routing

Drop HTML files in pages/ and NexGo creates routes automatically — no manual registration needed.

File Path URL Pattern Example
pages/index.html//
pages/about.html/about/about
pages/blog/index.html/blog/blog
pages/blog/[slug].html/blog/:slug/blog/my-post
pages/docs/[...path].html/docs/*/docs/api/auth
pages/api/users.go/api/users/api/users

Dynamic Routes

Use [param] syntax for dynamic URL segments:

pages/
├── users/
│   ├── [id].html          → /users/123
│   └── [id]/posts.html    → /users/123/posts
└── [...catchall].html     → /any/path/here

Access parameters in templates:

<h1>User </h1>
<p>Post: </p>

Layouts & Components

Layouts wrap page content. NexGo walks up the directory tree to find the nearest layout:

<!-- layouts/default.html -->
<!DOCTYPE html>
<html>
<head>
  <title>nexgo-website</title>
  <link rel="stylesheet" href="/static/css/global.css">
</head>
<body>
  <nav>...</nav>
  
  <footer>...</footer>
</body>
</html>

Reusable template partials stored in components/:

<!-- components/card.html -->
<div class="card">

</div>

<!-- Usage in pages -->

Template Engine

NexGo uses Go's html/template package. Every page receives a PageData struct:

type PageData struct {
    Title        string
    Description  string
    Path         string                 // Current URL path
    Params       map[string]string      // Route params
    Query        map[string]string      // Query string
    Props        map[string]interface{} // From DataLoader
    DevMode      bool
    BuildID      string
}

API Routes

Create .go files in pages/api/ to build REST endpoints:

// pages/api/hello.go
package api

import (
    "net/http"
    "github.com/salmanfaris22/nexgo/pkg/api"
    "github.com/salmanfaris22/nexgo/pkg/router"
)

func init() {
    router.RegisterAPI("/api/hello", Hello)
}

func Hello(w http.ResponseWriter, r *http.Request) {
    api.JSON(w, map[string]interface{}{
        "message": "Hello from NexGo!",
        "method":  r.Method,
    })
}

Data Loaders

Data loaders work like Next.js getServerSideProps — fetch data server-side before rendering:

// main.go
srv.RegisterDataLoader("/blog/[slug]", func(
    req *http.Request,
    params map[string]string,
) (map[string]interface{}, error) {
    slug := params["slug"]
    post, err := db.GetPost(slug)
    if err != nil {
        return nil, err
    }
    return map[string]interface{}{"post": post}, nil
})
<!-- pages/blog/[slug].html -->
<h1></h1>


    
    

Middleware

Built-in middleware is applied in this order:

Request → Recover → Logger → SecurityHeaders → [Gzip] → Handler
MiddlewareDescription
RecoverCatches panics, returns 500
LoggerLogs method, path, status, duration
SecurityHeadersX-Content-Type-Options, X-Frame-Options, etc.
GzipCompresses responses (configurable)
CORS(origins...)Configurable CORS headers
Cache(maxAge)Sets Cache-Control headers

Hot Reload (HMR)

Run nexgo dev — file watcher polls every 500ms, broadcasts reload via SSE to all connected browsers.

nexgo dev
# [NexGo] Dev server → http://localhost:3000
# [NexGo] Hot reload enabled. Press Ctrl+C to stop.

DevTools Panel

In dev mode, visit http://localhost:3000/_nexgo/devtools:

TabShows
RoutesAll routes with type badges (PAGE / API)
RequestsLive log with method, status, path, duration
LogsServer logs, HMR events, errors
PerformanceTotal requests, avg response time, error rate
ConfigCurrent server and build configuration

Building for Production

nexgo build       # Static site generation → .nexgo/out/
nexgo start       # Production server (no HMR, Gzip on)
nexgo start --port 4000

Deploying

NexGo compiles to a single binary — deploy anywhere Go runs:

# Build the binary
go build -o myapp ./main.go

# Copy to server
scp myapp server:/opt/myapp/
scp -r pages/ layouts/ static/ nexgo.config.json server:/opt/myapp/

# Run on server
ssh server '/opt/myapp/myapp'

Configuration

// nexgo.config.json
{
  "projectName": "my-app",
  "port": 3000,
  "host": "localhost",
  "pagesDir": "pages",
  "staticDir": "static",
  "layoutsDir": "layouts",
  "componentsDir": "components",
  "outputDir": ".nexgo/out",
  "hotReload": true,
  "compression": true,
  "minify": true,
  "defaultRenderMode": "ssr"
}

Template Functions Reference

String

FunctionUsageDescription
upperHELLOUppercase
lowerhiLowercase
titleHello WorldTitle case
trimhiTrim whitespace
replaceheyReplace substring
split[a b]Split to slice

Utility

FunctionDescription
json .DataJSON encode a value
safeHTML "<b>bold</b>"Render as raw HTML (trusted content only)
dict "key" "val"Create a key-value map
asset "/static/css/app.css"Cache-busted asset URL
default "fallback" .ValueDefault if nil/empty
times 5Iterate n times

API Helpers Reference

import "github.com/salmanfaris22/nexgo/pkg/api"

// Responses
api.JSON(w, data)               // 200 + JSON
api.JSONStatus(w, 201, data)    // Custom status
api.Error(w, 400, "bad input")  // JSON error

// Status shortcuts
api.BadRequest(w, "invalid id") // 400
api.NotFound(w, "not found")    // 404
api.Unauthorized(w)             // 401
api.InternalError(w, err)       // 500

// Request parsing
var input CreateUserInput
if !api.Decode(w, r, &input) { return }

// Method routing
api.Route(w, r, api.Methods{
    "GET":  listUsers,
    "POST": createUser,
})

// Pagination
page, limit := api.Paginate(r) // ?page=2&limit=10

CLI Commands

CommandDescription
nexgo create <name>Scaffold a new NexGo project
nexgo devStart dev server with hot reload
nexgo buildStatic site generation (SSG)
nexgo startStart production server
nexgo versionPrint version
nexgo helpShow help

💬 Need help? Open an issue on GitHub, or reach out to salmanfariskalm@gmail.com.