wsframe

package module
v0.0.0-...-3bf7bdd Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 19, 2025 License: GPL-3.0 Imports: 19 Imported by: 0

README

🧩 WSFrame

WSFrame is a lightweight Go framework for real-time, dynamic web applications using WebSockets, templates, and PostgreSQL. It is designed to work with wsrooms for bi-directional client-server communication.


🚀 Features

  • 📡 WebSocket routing via regular expressions
  • 🔄 Dynamic HTML rendering via Go templates
  • 🔐 Built-in user registration and login with secure cookies
  • 🗂️ PostgreSQL persistence using JSON columns
  • ⚡ Hot-swappable route handling
  • 🧠 Template helpers for common operations (currency, math, HTML escaping, etc.)

🧰 Components

  • Routes: Declarative or programmatic, privilege-aware
  • Render Engine: Go templates with built-in helpers
  • WebSocket Server: Integrated via wsrooms
  • Database Access: Auto-creates tables, supports dynamic access via keys
  • Authentication: Salted SHA-256 hashes with cookie-based sessions

📦 Directory Structure

wsframe/
├── app.go           # Main App struct, startup logic
├── auth.go          # Register/login/logout handlers
├── db.go            # PostgreSQL logic (CRUD)
├── render.go        # Template rendering and response
├── routes.go        # Route matching and configuration
├── templatefuncs.go # Custom template functions

🧱 Route Configuration

A Route object can specify:

  • A regex path match
  • Optional admin and authorized variants
  • Data table and key for dynamic loading
  • Template to render
  • Controllers to execute in frontend

Example:

{
  "route": "/articles/([a-z0-9-]+)",
  "authorized": {
    "privilege": "user",
    "template": "article",
    "controllers": "articleController",
    "table": "articles",
    "key": "$1"
  }
}

🧪 Custom Handlers

You can register WebSocket route handlers programmatically:

app.AddRoute("^/test/(.*)$", func(c *wsrooms.Conn, msg *wsrooms.Message, matches []string) {
    app.Render(c, msg, "test-view", []string{"test"}, nil)
})

🛠 Template Helpers

  • usd, add, subtract, multiply, divide
  • tokey, fromkey
  • sha1sum, css, unescaped

Use them in your templates:

<p>{{ usd .Price }}</p>

🧪 WSFrame Example App

This is a minimal example application using WSFrame, a Go WebSocket framework for real-time routing and template rendering.


🔧 Features

  • Hash-based routing (e.g. #/test/foo)
  • Real-time template + controller updates
  • Dynamic path-based data loading
  • User registration & login with secure cookies

🚀 Quickstart

1. Clone
git clone https://github.com/joncody/wsframe.git
cd wsframe/example
2. Setup Database

Create a PostgreSQL database matching the config:

CREATE DATABASE mydatabase;
CREATE USER myuser WITH PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON DATABASE mydatabase TO myuser;
3. Run
go run main.go

Open in your browser:

http://localhost:9001

🗂️ Project Structure

.
├── main.go              # Entry point with custom handler
├── config.json          # App config
├── static/
│   ├── views/           # Go templates
│   └── js/              # Frontend client
└── wsframe/             # Framework (submodule or local copy)

🔒 Auth Endpoints

Method Path Description
POST /register Register new user
POST /login Log in with alias/passhash
POST /logout Logout and clear cookie

🧪 Custom Route

Inside main.go:

app.AddRoute("^/test/(.*)$", testHandler)

func testHandler(c *wsrooms.Conn, msg *wsrooms.Message, matches []string) {
	log.Println(matches)
	app.Render(c, msg, "index-added", []string{"index"}, nil)
}

Visit http://localhost:9001/#/test/hello to see it in action.


🌐 Frontend: static/js/app.js

  • Listens for hash changes
  • Sends request to WebSocket
  • Receives response with:
    • HTML template to inject
    • JS controllers to run

✨ Example HTML Controller

<a data-href="/test/hello">Go to Hello</a>

Triggers:

  1. location.hash = "/test/hello"
  2. WebSocket sends request
  3. Server responds with rendered index-added view

📜 License

See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var TemplateFuncs = template.FuncMap{
	"unescaped": func(x string) interface{} {
		return template.HTML(x)
	},
	"sha1sum": func(x string) string {
		return fmt.Sprintf("%x", sha1.Sum([]byte(x)))
	},
	"subtract": func(a, b int) int {
		return a - b
	},
	"add": func(a, b int) int {
		return a + b
	},
	"multiply": func(a, b int) int {
		return a * b
	},
	"divide": func(a, b int) int {
		return a / b
	},
	"usd": func(x int) string {
		return fmt.Sprintf("$%.2f", float64(x)/float64(100))
	},
	"css": func(s string) template.CSS {
		return template.CSS(s)
	},
	"tokey":   ToKey,
	"fromkey": FromKey,
}

Functions

func FromKey

func FromKey(s string) string

func ToKey

func ToKey(s string) string

Types

type AddedRoute

type AddedRoute struct {
	Route   string
	Handler func(c *wsrooms.Conn, msg *wsrooms.Message, matches []string)
}

type App

type App struct {
	Name         string `json:"name"`
	HashKey      string `json:"hashkey"`
	BlockKey     string `json:"blockkey"`
	SecureCookie *securecookie.SecureCookie
	Templates    *template.Template
	Port         string   `json:"port"`
	SSLPort      string   `json:"sslport"`
	Database     DBConfig `json:"database"`
	Driver       *sql.DB
	Routes       []Route `json:"routes"`
	Added        []AddedRoute
	Router       *mux.Router
}

func NewApp

func NewApp(cj string) *App

func (*App) AddRoute

func (wfa *App) AddRoute(path string, handler func(c *wsrooms.Conn, msg *wsrooms.Message, matches []string))

func (*App) GetRow

func (wfa *App) GetRow(table, key string) map[string]interface{}

func (*App) GetRows

func (wfa *App) GetRows(table string) []map[string]interface{}

func (*App) InsertRow

func (wfa *App) InsertRow(table, key, value string) error

func (*App) ReadCookie

func (wfa *App) ReadCookie(r *http.Request) map[string]string

func (*App) Render

func (wfa *App) Render(c *wsrooms.Conn, msg *wsrooms.Message, template string, controllers []string, data interface{})

func (*App) SetCookie

func (wfa *App) SetCookie(w http.ResponseWriter, r *http.Request, value map[string]string, logout bool)

func (*App) Start

func (wfa *App) Start()

type Auth

type Auth struct {
	Alias     string `json:"alias,omitempty"`
	Passhash  string `json:"passhash"`
	Salt      string `json:"salt"`
	Hash      string `json:"hash"`
	Privilege string `json:"privilege"`
}

type DBConfig

type DBConfig struct {
	User     string `json:"user"`
	Password string `json:"password"`
	Name     string `json:"name"`
}

type Route

type Route struct {
	Route      string      `json:"route"`
	Admin      RouteConfig `json:"admin"`
	Authorized RouteConfig `json:"authorized"`
	RouteConfig
}

type RouteConfig

type RouteConfig struct {
	Table       string `json:"table"`
	Key         string `json:"key"`
	Template    string `json:"template"`
	Controllers string `json:"controllers"`
	Privilege   string `json:"privilege,omitempty"` // Only used for Authorized routes
}

type RoutePayload

type RoutePayload struct {
	Template    string   `json:"template"`
	Controllers []string `json:"controllers"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL