Compare commits
13 Commits
hlog/v0.10
...
hws/v0.2.2
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c66e6dd66 | |||
| 614be4ed0e | |||
| da8e3c2d10 | |||
| 51045537b2 | |||
| bdae21ec0b | |||
| ddd570230b | |||
| a255ee578e | |||
| 1b1fa12a45 | |||
| 90976ca98b | |||
| 328adaadee | |||
| 5be9811afc | |||
| 52341aba56 | |||
| 7471ae881b |
13
RULES.md
13
RULES.md
@@ -8,11 +8,11 @@ Documentation is done in a few ways:
|
|||||||
- wiki
|
- wiki
|
||||||
|
|
||||||
The README for each module should be laid out as follows:
|
The README for each module should be laid out as follows:
|
||||||
- Title and description
|
- Title and description with version number
|
||||||
- Feature list (DO NOT USE EMOTICONS)
|
- Feature list (DO NOT USE EMOTICONS)
|
||||||
- Installation (go get)
|
- Installation (go get)
|
||||||
- Quick Start (brief example of setting up and using)
|
- Quick Start (brief example of setting up and using)
|
||||||
- Documentation links to the wiki
|
- Documentation links to the wiki (path is `../golib/wiki/<package>.md`)
|
||||||
- Additional information (e.g. supported databases if package has database features)
|
- Additional information (e.g. supported databases if package has database features)
|
||||||
- License
|
- License
|
||||||
- Contributing
|
- Contributing
|
||||||
@@ -24,7 +24,8 @@ Any Config structs with environment variables should have their docstrings match
|
|||||||
where the required and default fields are only present if relevant to that variable
|
where the required and default fields are only present if relevant to that variable
|
||||||
|
|
||||||
The wiki is located at ~/projects/golib-wiki and should be laid out as follows:
|
The wiki is located at ~/projects/golib-wiki and should be laid out as follows:
|
||||||
- Title and description with version number (i will manually handle commits and versioning)
|
- Link to wiki page from the Home page
|
||||||
|
- Title and description with version number
|
||||||
- Installation
|
- Installation
|
||||||
- Key Concepts and features
|
- Key Concepts and features
|
||||||
- Quick start
|
- Quick start
|
||||||
@@ -39,5 +40,7 @@ The wiki is located at ~/projects/golib-wiki and should be laid out as follows:
|
|||||||
2. All features should have tests.
|
2. All features should have tests.
|
||||||
Any changes to existing features or additional features implemented should have tests created and/or updated
|
Any changes to existing features or additional features implemented should have tests created and/or updated
|
||||||
|
|
||||||
3. NEVER COMMIT
|
3. Version control
|
||||||
I will handle and manage all version control
|
Version numbers are specified using git tags.
|
||||||
|
Do not change version numbers. When updating documentation, append the branch name to the version number.
|
||||||
|
Changes made to the golib-wiki repo should be made under the same branch name as the changes made in this repo
|
||||||
|
|||||||
21
hlog/LICENSE
Normal file
21
hlog/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 haelnorr
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
73
hlog/README.md
Normal file
73
hlog/README.md
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
# HLog - v0.10.3
|
||||||
|
|
||||||
|
A structured logging package for Go built on top of [zerolog](https://github.com/rs/zerolog). HLog provides simple configuration via environment variables, flexible output options, and automatic log file management.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Multiple output modes: console, file, or both simultaneously
|
||||||
|
- Configurable log levels: trace, debug, info, warn, error, fatal, panic
|
||||||
|
- Environment variable-based configuration with ConfigFromEnv
|
||||||
|
- Automatic log file management with append or overwrite modes
|
||||||
|
- Built on zerolog for high performance and structured logging
|
||||||
|
- Error stack trace support via pkg/errors integration
|
||||||
|
- Unix timestamp format
|
||||||
|
- Console-friendly output formatting
|
||||||
|
- Multi-writer support for simultaneous console and file output
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go get git.haelnorr.com/h/golib/hlog
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"git.haelnorr.com/h/golib/hlog"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Load configuration from environment variables
|
||||||
|
cfg, err := hlog.ConfigFromEnv()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a new logger
|
||||||
|
logger, err := hlog.NewLogger(cfg, os.Stdout)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
defer logger.CloseLogFile()
|
||||||
|
|
||||||
|
// Start logging
|
||||||
|
logger.Info().Msg("Application started")
|
||||||
|
logger.Debug().Str("user", "john").Msg("User logged in")
|
||||||
|
logger.Error().Err(err).Msg("Something went wrong")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
For detailed documentation, see the [HLog Wiki](https://git.haelnorr.com/h/golib/wiki/HLog.md).
|
||||||
|
|
||||||
|
Additional API documentation is available at [GoDoc](https://pkg.go.dev/git.haelnorr.com/h/golib/hlog).
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
This project is licensed under the MIT License - see the LICENSE file for details.
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
Contributions are welcome! Please feel free to submit a Pull Request.
|
||||||
|
|
||||||
|
## Related Projects
|
||||||
|
|
||||||
|
- [env](https://git.haelnorr.com/h/golib/env) - Environment variable helper used by hlog for configuration
|
||||||
|
- [zerolog](https://github.com/rs/zerolog) - The underlying logging library
|
||||||
44
hlog/doc.go
44
hlog/doc.go
@@ -24,18 +24,22 @@
|
|||||||
//
|
//
|
||||||
// # Configuration
|
// # Configuration
|
||||||
//
|
//
|
||||||
// hlog can be configured via environment variables:
|
// hlog can be configured via environment variables using ConfigFromEnv:
|
||||||
//
|
//
|
||||||
// LOG_LEVEL=info # trace, debug, info, warn, error, fatal, panic (default: info)
|
// LOG_LEVEL=info # trace, debug, info, warn, error, fatal, panic (default: info)
|
||||||
// LOG_OUTPUT=console # console, file, or both (default: console)
|
// LOG_OUTPUT=console # console, file, or both (default: console)
|
||||||
// LOG_DIR=/var/log/app # Required when LOG_OUTPUT is "file" or "both"
|
// LOG_DIR=/var/log/app # Required when LOG_OUTPUT is "file" or "both"
|
||||||
|
// LOG_FILE_NAME=server.log # Required when LOG_OUTPUT is "file" or "both"
|
||||||
|
// LOG_APPEND=true # Append to existing file or overwrite (default: true)
|
||||||
//
|
//
|
||||||
// Or programmatically:
|
// Or programmatically:
|
||||||
//
|
//
|
||||||
// cfg := &hlog.Config{
|
// cfg := &hlog.Config{
|
||||||
// LogLevel: hlog.InfoLevel,
|
// LogLevel: hlog.InfoLevel,
|
||||||
// LogOutput: "both",
|
// LogOutput: "both",
|
||||||
// LogDir: "/var/log/myapp",
|
// LogDir: "/var/log/myapp",
|
||||||
|
// LogFileName: "server.log",
|
||||||
|
// LogAppend: true,
|
||||||
// }
|
// }
|
||||||
//
|
//
|
||||||
// # Log Levels
|
// # Log Levels
|
||||||
@@ -52,13 +56,27 @@
|
|||||||
// # Output Modes
|
// # Output Modes
|
||||||
//
|
//
|
||||||
// - console: Logs to the provided io.Writer (typically os.Stdout or os.Stderr)
|
// - console: Logs to the provided io.Writer (typically os.Stdout or os.Stderr)
|
||||||
// - file: Logs to a file named "server.log" in the configured directory
|
// - file: Logs to a file in the configured directory
|
||||||
// - both: Logs to both console and file simultaneously
|
// - both: Logs to both console and file simultaneously using zerolog.MultiLevelWriter
|
||||||
//
|
//
|
||||||
// # File Management
|
// # File Management
|
||||||
//
|
//
|
||||||
// When using file output, hlog creates a file named "server.log" in the
|
// When using file output, hlog creates a file with the specified name in the
|
||||||
// specified directory. The file is opened in append mode, so logs persist
|
// configured directory. The file can be opened in append mode (default) to
|
||||||
// across application restarts. Remember to call CloseLogFile() when shutting
|
// preserve logs across application restarts, or in overwrite mode to start
|
||||||
// down your application to ensure all logs are flushed.
|
// fresh each time. Remember to call CloseLogFile() when shutting down your
|
||||||
|
// application to ensure all logs are flushed to disk.
|
||||||
|
//
|
||||||
|
// # Error Stack Traces
|
||||||
|
//
|
||||||
|
// hlog automatically configures zerolog to include stack traces for errors
|
||||||
|
// wrapped with github.com/pkg/errors. This provides detailed error context
|
||||||
|
// when using errors.Wrap or errors.WithStack.
|
||||||
|
//
|
||||||
|
// # Integration
|
||||||
|
//
|
||||||
|
// hlog integrates with:
|
||||||
|
// - git.haelnorr.com/h/golib/env: For environment variable configuration
|
||||||
|
// - github.com/rs/zerolog: The underlying logging implementation
|
||||||
|
// - github.com/pkg/errors: For error stack trace support
|
||||||
package hlog
|
package hlog
|
||||||
|
|||||||
@@ -1,21 +1,19 @@
|
|||||||
# HWS (H Web Server)
|
# HWS (H Web Server) - v0.2.2
|
||||||
|
|
||||||
[](https://pkg.go.dev/git.haelnorr.com/h/golib/hws)
|
A lightweight, opinionated HTTP web server framework for Go built on top of the standard library's net/http.
|
||||||
|
|
||||||
A lightweight, opinionated HTTP web server framework for Go built on top of the standard library's `net/http`.
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- 🚀 Built on Go 1.22+ routing patterns with method and path matching
|
- Built on Go 1.22+ routing patterns with method and path matching
|
||||||
- 🎯 Structured error handling with customizable error pages
|
- Structured error handling with customizable error pages
|
||||||
- 📝 Integrated logging with zerolog via hlog
|
- Integrated logging with zerolog via hlog
|
||||||
- 🔧 Middleware support with predictable execution order
|
- Middleware support with predictable execution order
|
||||||
- 🗜️ GZIP compression support
|
- GZIP compression support
|
||||||
- 🔒 Safe static file serving (prevents directory listing)
|
- Safe static file serving (prevents directory listing)
|
||||||
- ⚙️ Environment variable configuration
|
- Environment variable configuration with ConfigFromEnv
|
||||||
- ⏱️ Request timing and logging middleware
|
- Request timing and logging middleware
|
||||||
- 💚 Graceful shutdown support
|
- Graceful shutdown support
|
||||||
- 🏥 Built-in health check endpoint
|
- Built-in health check endpoint
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
@@ -30,8 +28,8 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"git.haelnorr.com/h/golib/hws"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"git.haelnorr.com/h/golib/hws"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -79,34 +77,13 @@ func getUserHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
Comprehensive documentation is available in the [Wiki](https://git.haelnorr.com/h/golib/wiki/hws).
|
For detailed documentation, see the [HWS Wiki](https://git.haelnorr.com/h/golib/wiki/HWS.md).
|
||||||
|
|
||||||
### Key Topics
|
Additional API documentation is available at [GoDoc](https://pkg.go.dev/git.haelnorr.com/h/golib/hws).
|
||||||
|
|
||||||
- [Configuration](https://git.haelnorr.com/h/golib/wiki/hws#configuration)
|
|
||||||
- [Routing](https://git.haelnorr.com/h/golib/wiki/hws#routing)
|
|
||||||
- [Middleware](https://git.haelnorr.com/h/golib/wiki/hws#middleware)
|
|
||||||
- [Error Handling](https://git.haelnorr.com/h/golib/wiki/hws#error-handling)
|
|
||||||
- [Logging](https://git.haelnorr.com/h/golib/wiki/hws#logging)
|
|
||||||
- [Static Files](https://git.haelnorr.com/h/golib/wiki/hws#static-files)
|
|
||||||
- [Graceful Shutdown](https://git.haelnorr.com/h/golib/wiki/hws#graceful-shutdown)
|
|
||||||
- [Complete Examples](https://git.haelnorr.com/h/golib/wiki/hws#complete-production-example)
|
|
||||||
|
|
||||||
## Environment Variables
|
|
||||||
|
|
||||||
| Variable | Description | Default |
|
|
||||||
|----------|-------------|---------|
|
|
||||||
| `HWS_HOST` | Host to listen on | `127.0.0.1` |
|
|
||||||
| `HWS_PORT` | Port to listen on | `3000` |
|
|
||||||
| `HWS_TRUSTED_HOST` | Trusted hostname/domain | Same as Host |
|
|
||||||
| `HWS_GZIP` | Enable GZIP compression | `false` |
|
|
||||||
| `HWS_READ_HEADER_TIMEOUT` | Header read timeout (seconds) | `2` |
|
|
||||||
| `HWS_WRITE_TIMEOUT` | Write timeout (seconds) | `10` |
|
|
||||||
| `HWS_IDLE_TIMEOUT` | Idle connection timeout (seconds) | `120` |
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
This project is licensed under the MIT License - see the LICENSE file for details.
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
@@ -114,6 +91,6 @@ Contributions are welcome! Please feel free to submit a Pull Request.
|
|||||||
|
|
||||||
## Related Projects
|
## Related Projects
|
||||||
|
|
||||||
- [HWSAuth](https://git.haelnorr.com/h/golib/hwsauth) - JWT authentication middleware for HWS
|
- [hwsauth](https://git.haelnorr.com/h/golib/hwsauth) - JWT authentication middleware for HWS
|
||||||
- [hlog](https://git.haelnorr.com/h/golib/hlog) - Structured logging with zerolog
|
- [hlog](https://git.haelnorr.com/h/golib/hlog) - Structured logging with zerolog
|
||||||
- [jwt](https://git.haelnorr.com/h/golib/jwt) - JWT token generation and validation
|
- [jwt](https://git.haelnorr.com/h/golib/jwt) - JWT token generation and validation
|
||||||
|
|||||||
144
hws/doc.go
Normal file
144
hws/doc.go
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
// Package hws provides a lightweight HTTP web server framework built on top of Go's standard library.
|
||||||
|
//
|
||||||
|
// HWS (H Web Server) is an opinionated framework that leverages Go 1.22+ routing patterns
|
||||||
|
// with built-in middleware, structured error handling, and production-ready defaults. It
|
||||||
|
// integrates seamlessly with other golib packages like hlog for logging and hwsauth for
|
||||||
|
// authentication.
|
||||||
|
//
|
||||||
|
// # Basic Usage
|
||||||
|
//
|
||||||
|
// Create a server with environment-based configuration:
|
||||||
|
//
|
||||||
|
// cfg, err := hws.ConfigFromEnv()
|
||||||
|
// if err != nil {
|
||||||
|
// log.Fatal(err)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// server, err := hws.NewServer(cfg)
|
||||||
|
// if err != nil {
|
||||||
|
// log.Fatal(err)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// routes := []hws.Route{
|
||||||
|
// {
|
||||||
|
// Path: "/",
|
||||||
|
// Method: hws.MethodGET,
|
||||||
|
// Handler: http.HandlerFunc(homeHandler),
|
||||||
|
// },
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// server.AddRoutes(routes...)
|
||||||
|
// server.AddMiddleware()
|
||||||
|
//
|
||||||
|
// ctx := context.Background()
|
||||||
|
// server.Start(ctx)
|
||||||
|
//
|
||||||
|
// <-server.Ready()
|
||||||
|
//
|
||||||
|
// # Configuration
|
||||||
|
//
|
||||||
|
// HWS can be configured via environment variables using ConfigFromEnv:
|
||||||
|
//
|
||||||
|
// HWS_HOST=127.0.0.1 # Host to listen on (default: 127.0.0.1)
|
||||||
|
// HWS_PORT=3000 # Port to listen on (default: 3000)
|
||||||
|
// HWS_GZIP=false # Enable GZIP compression (default: false)
|
||||||
|
// HWS_READ_HEADER_TIMEOUT=2 # Header read timeout in seconds (default: 2)
|
||||||
|
// HWS_WRITE_TIMEOUT=10 # Write timeout in seconds (default: 10)
|
||||||
|
// HWS_IDLE_TIMEOUT=120 # Idle connection timeout in seconds (default: 120)
|
||||||
|
//
|
||||||
|
// Or programmatically:
|
||||||
|
//
|
||||||
|
// cfg := &hws.Config{
|
||||||
|
// Host: "0.0.0.0",
|
||||||
|
// Port: 8080,
|
||||||
|
// GZIP: true,
|
||||||
|
// ReadHeaderTimeout: 5 * time.Second,
|
||||||
|
// WriteTimeout: 15 * time.Second,
|
||||||
|
// IdleTimeout: 120 * time.Second,
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// # Routing
|
||||||
|
//
|
||||||
|
// HWS uses Go 1.22+ routing patterns with method-specific handlers:
|
||||||
|
//
|
||||||
|
// routes := []hws.Route{
|
||||||
|
// {
|
||||||
|
// Path: "/users/{id}",
|
||||||
|
// Method: hws.MethodGET,
|
||||||
|
// Handler: http.HandlerFunc(getUser),
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// Path: "/users/{id}",
|
||||||
|
// Method: hws.MethodPUT,
|
||||||
|
// Handler: http.HandlerFunc(updateUser),
|
||||||
|
// },
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// Path parameters can be accessed using r.PathValue():
|
||||||
|
//
|
||||||
|
// func getUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// id := r.PathValue("id")
|
||||||
|
// // ... handle request
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// # Middleware
|
||||||
|
//
|
||||||
|
// HWS supports middleware with predictable execution order. Built-in middleware includes
|
||||||
|
// request logging, timing, and GZIP compression:
|
||||||
|
//
|
||||||
|
// server.AddMiddleware()
|
||||||
|
//
|
||||||
|
// Custom middleware can be added using standard http.Handler wrapping:
|
||||||
|
//
|
||||||
|
// server.AddMiddleware(customMiddleware)
|
||||||
|
//
|
||||||
|
// # Error Handling
|
||||||
|
//
|
||||||
|
// HWS provides structured error handling with customizable error pages:
|
||||||
|
//
|
||||||
|
// errorPageFunc := func(w http.ResponseWriter, r *http.Request, status int) {
|
||||||
|
// w.WriteHeader(status)
|
||||||
|
// fmt.Fprintf(w, "Error: %d", status)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// server.AddErrorPage(errorPageFunc)
|
||||||
|
//
|
||||||
|
// # Logging
|
||||||
|
//
|
||||||
|
// HWS integrates with hlog for structured logging:
|
||||||
|
//
|
||||||
|
// logger, _ := hlog.NewLogger(loggerCfg, os.Stdout)
|
||||||
|
// server.AddLogger(logger)
|
||||||
|
//
|
||||||
|
// The server will automatically log requests, errors, and server lifecycle events.
|
||||||
|
//
|
||||||
|
// # Static Files
|
||||||
|
//
|
||||||
|
// HWS provides safe static file serving that prevents directory listing:
|
||||||
|
//
|
||||||
|
// server.AddStaticFiles("/static", "./public")
|
||||||
|
//
|
||||||
|
// # Graceful Shutdown
|
||||||
|
//
|
||||||
|
// HWS supports graceful shutdown via context cancellation:
|
||||||
|
//
|
||||||
|
// ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
// defer cancel()
|
||||||
|
//
|
||||||
|
// server.Start(ctx)
|
||||||
|
//
|
||||||
|
// // Wait for shutdown signal
|
||||||
|
// sigChan := make(chan os.Signal, 1)
|
||||||
|
// signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
|
||||||
|
// <-sigChan
|
||||||
|
//
|
||||||
|
// // Cancel context to trigger graceful shutdown
|
||||||
|
// cancel()
|
||||||
|
//
|
||||||
|
// # Integration
|
||||||
|
//
|
||||||
|
// HWS integrates with:
|
||||||
|
// - git.haelnorr.com/h/golib/hlog: For structured logging with zerolog
|
||||||
|
// - git.haelnorr.com/h/golib/hwsauth: For JWT-based authentication
|
||||||
|
// - git.haelnorr.com/h/golib/jwt: For JWT token management
|
||||||
|
package hws
|
||||||
@@ -1,19 +1,19 @@
|
|||||||
# HWSAuth
|
# HWSAuth - v0.3.2
|
||||||
|
|
||||||
[](https://pkg.go.dev/git.haelnorr.com/h/golib/hwsauth)
|
JWT-based authentication middleware for the HWS web framework.
|
||||||
|
|
||||||
JWT-based authentication middleware for the [HWS](https://git.haelnorr.com/h/golib/hws) web framework.
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- 🔐 JWT-based authentication with access and refresh tokens
|
- JWT-based authentication with access and refresh tokens
|
||||||
- 🔄 Automatic token rotation and refresh
|
- Automatic token rotation and refresh
|
||||||
- 🎯 Generic over user model and transaction types
|
- Generic over user model and transaction types
|
||||||
- 💾 ORM-agnostic transaction handling (works with GORM, Bun, sqlx, etc.)
|
- ORM-agnostic transaction handling (works with GORM, Bun, sqlx, database/sql)
|
||||||
- ⚙️ Environment variable configuration
|
- Environment variable configuration with ConfigFromEnv
|
||||||
- 🛡️ Middleware for protecting routes
|
- Middleware for protecting routes
|
||||||
- 🔒 SSL cookie security support
|
- SSL cookie security support
|
||||||
- 📦 Type-safe with Go generics
|
- Type-safe with Go generics
|
||||||
|
- Path ignoring for public routes
|
||||||
|
- Automatic re-authentication handling
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
@@ -29,9 +29,9 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"net/http"
|
||||||
"git.haelnorr.com/h/golib/hwsauth"
|
"git.haelnorr.com/h/golib/hwsauth"
|
||||||
"git.haelnorr.com/h/golib/hws"
|
"git.haelnorr.com/h/golib/hws"
|
||||||
"github.com/rs/zerolog"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
@@ -69,6 +69,15 @@ func main() {
|
|||||||
serverCfg, _ := hws.ConfigFromEnv()
|
serverCfg, _ := hws.ConfigFromEnv()
|
||||||
server, _ := hws.NewServer(serverCfg)
|
server, _ := hws.NewServer(serverCfg)
|
||||||
|
|
||||||
|
// Create logger
|
||||||
|
logger, _ := hlog.NewLogger(loggerCfg, os.Stdout)
|
||||||
|
|
||||||
|
// Create error page function
|
||||||
|
errorPageFunc := func(w http.ResponseWriter, r *http.Request, status int) {
|
||||||
|
w.WriteHeader(status)
|
||||||
|
fmt.Fprintf(w, "Error: %d", status)
|
||||||
|
}
|
||||||
|
|
||||||
// Create authenticator
|
// Create authenticator
|
||||||
auth, _ := hwsauth.NewAuthenticator[User, *sql.Tx](
|
auth, _ := hwsauth.NewAuthenticator[User, *sql.Tx](
|
||||||
cfg,
|
cfg,
|
||||||
@@ -93,7 +102,7 @@ func main() {
|
|||||||
// Add authentication middleware
|
// Add authentication middleware
|
||||||
server.AddMiddleware(auth.Authenticate())
|
server.AddMiddleware(auth.Authenticate())
|
||||||
|
|
||||||
// Optionally ignore public paths
|
// Ignore public paths
|
||||||
auth.IgnorePaths("/", "/login", "/register", "/static")
|
auth.IgnorePaths("/", "/login", "/register", "/static")
|
||||||
|
|
||||||
// Start server
|
// Start server
|
||||||
@@ -106,18 +115,9 @@ func main() {
|
|||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
Comprehensive documentation is available in the [Wiki](https://git.haelnorr.com/h/golib/wiki/hwsauth).
|
For detailed documentation, see the [HWSAuth Wiki](https://git.haelnorr.com/h/golib/wiki/HWSAuth.md).
|
||||||
|
|
||||||
### Key Topics
|
Additional API documentation is available at [GoDoc](https://pkg.go.dev/git.haelnorr.com/h/golib/hwsauth).
|
||||||
|
|
||||||
- [Configuration](https://git.haelnorr.com/h/golib/wiki/hwsauth#configuration)
|
|
||||||
- [User Model](https://git.haelnorr.com/h/golib/wiki/hwsauth#user-model)
|
|
||||||
- [Authentication Flow](https://git.haelnorr.com/h/golib/wiki/hwsauth#authentication-flow)
|
|
||||||
- [Login & Logout](https://git.haelnorr.com/h/golib/wiki/hwsauth#login-logout)
|
|
||||||
- [Route Protection](https://git.haelnorr.com/h/golib/wiki/hwsauth#route-protection)
|
|
||||||
- [Token Refresh](https://git.haelnorr.com/h/golib/wiki/hwsauth#token-refresh)
|
|
||||||
- [Using with ORMs](https://git.haelnorr.com/h/golib/wiki/hwsauth#using-with-orms)
|
|
||||||
- [Security Best Practices](https://git.haelnorr.com/h/golib/wiki/hwsauth#security-best-practices)
|
|
||||||
|
|
||||||
## Supported ORMs
|
## Supported ORMs
|
||||||
|
|
||||||
@@ -128,7 +128,7 @@ Comprehensive documentation is available in the [Wiki](https://git.haelnorr.com/
|
|||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.
|
This project is licensed under the MIT License - see the LICENSE file for details.
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
@@ -138,4 +138,4 @@ Contributions are welcome! Please feel free to submit a Pull Request.
|
|||||||
|
|
||||||
- [hws](https://git.haelnorr.com/h/golib/hws) - The web server framework
|
- [hws](https://git.haelnorr.com/h/golib/hws) - The web server framework
|
||||||
- [jwt](https://git.haelnorr.com/h/golib/jwt) - JWT token generation and validation
|
- [jwt](https://git.haelnorr.com/h/golib/jwt) - JWT token generation and validation
|
||||||
|
- [hlog](https://git.haelnorr.com/h/golib/hlog) - Structured logging with zerolog
|
||||||
|
|||||||
@@ -179,18 +179,18 @@
|
|||||||
//
|
//
|
||||||
// # Environment Variables
|
// # Environment Variables
|
||||||
//
|
//
|
||||||
// The following environment variables are supported:
|
// The following environment variables are supported when using ConfigFromEnv:
|
||||||
//
|
//
|
||||||
// - HWSAUTH_SSL: Enable SSL mode (default: false)
|
// - HWSAUTH_SSL: Enable SSL secure cookies (default: false)
|
||||||
// - HWSAUTH_TRUSTED_HOST: Trusted host for SSL (required if SSL is true)
|
// - HWSAUTH_TRUSTED_HOST: Full server address for SSL (required if SSL is true)
|
||||||
// - HWSAUTH_SECRET_KEY: Secret key for signing tokens (required)
|
// - HWSAUTH_SECRET_KEY: Secret key for signing JWT tokens (required)
|
||||||
// - HWSAUTH_ACCESS_TOKEN_EXPIRY: Access token expiry in minutes (default: 5)
|
// - HWSAUTH_ACCESS_TOKEN_EXPIRY: Access token expiry in minutes (default: 5)
|
||||||
// - HWSAUTH_REFRESH_TOKEN_EXPIRY: Refresh token expiry in minutes (default: 1440)
|
// - HWSAUTH_REFRESH_TOKEN_EXPIRY: Refresh token expiry in minutes (default: 1440)
|
||||||
// - HWSAUTH_TOKEN_FRESH_TIME: Token fresh time in minutes (default: 5)
|
// - HWSAUTH_TOKEN_FRESH_TIME: Token fresh time in minutes (default: 5)
|
||||||
// - HWSAUTH_LANDING_PAGE: Landing page for logged in users (default: "/profile")
|
// - HWSAUTH_LANDING_PAGE: Redirect destination for authenticated users (default: "/profile")
|
||||||
// - HWSAUTH_JWT_TABLE_NAME: Custom JWT table name (optional)
|
// - HWSAUTH_DATABASE_TYPE: Database type - postgres, mysql, sqlite, mariadb (default: "postgres")
|
||||||
// - HWSAUTH_DATABASE_TYPE: Database type (e.g., "postgres", "mysql")
|
// - HWSAUTH_DATABASE_VERSION: Database version string (default: "15")
|
||||||
// - HWSAUTH_DATABASE_VERSION: Database version (e.g., "15")
|
// - HWSAUTH_JWT_TABLE_NAME: Custom JWT blacklist table name (default: "jwtblacklist")
|
||||||
//
|
//
|
||||||
// # Security Considerations
|
// # Security Considerations
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -1,20 +1,19 @@
|
|||||||
# JWT Package
|
# JWT - v0.10.1
|
||||||
|
|
||||||
[](https://pkg.go.dev/git.haelnorr.com/h/golib/jwt)
|
|
||||||
|
|
||||||
JWT (JSON Web Token) generation and validation with database-backed token revocation support.
|
JWT (JSON Web Token) generation and validation with database-backed token revocation support.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- 🔐 Access and refresh token generation
|
- Access and refresh token generation
|
||||||
- ✅ Token validation with expiration checking
|
- Token validation with expiration checking
|
||||||
- 🚫 Token revocation via database blacklist
|
- Token revocation via database blacklist
|
||||||
- 🗄️ Multi-database support (PostgreSQL, MySQL, SQLite, MariaDB)
|
- Multi-database support (PostgreSQL, MySQL, SQLite, MariaDB)
|
||||||
- 🔧 Compatible with database/sql, GORM, and Bun
|
- Compatible with database/sql, GORM, and Bun ORMs
|
||||||
- 🤖 Automatic table creation and management
|
- Automatic table creation and management
|
||||||
- 🧹 Database-native automatic cleanup
|
- Database-native automatic cleanup
|
||||||
- 🔄 Token freshness tracking
|
- Token freshness tracking for sensitive operations
|
||||||
- 💾 "Remember me" functionality
|
- "Remember me" functionality with session vs persistent tokens
|
||||||
|
- Manual cleanup method for on-demand token cleanup
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
@@ -41,7 +40,7 @@ func main() {
|
|||||||
|
|
||||||
// Create a transaction getter function
|
// Create a transaction getter function
|
||||||
txGetter := func(ctx context.Context) (jwt.DBTransaction, error) {
|
txGetter := func(ctx context.Context) (jwt.DBTransaction, error) {
|
||||||
return db.Begin()
|
return db.BeginTx(ctx, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create token generator
|
// Create token generator
|
||||||
@@ -78,16 +77,9 @@ func main() {
|
|||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
Comprehensive documentation is available in the [Wiki](https://git.haelnorr.com/h/golib/wiki/JWT).
|
For detailed documentation, see the [JWT Wiki](https://git.haelnorr.com/h/golib/wiki/JWT.md).
|
||||||
|
|
||||||
### Key Topics
|
Additional API documentation is available at [GoDoc](https://pkg.go.dev/git.haelnorr.com/h/golib/jwt).
|
||||||
|
|
||||||
- [Configuration](https://git.haelnorr.com/h/golib/wiki/JWT#configuration)
|
|
||||||
- [Token Generation](https://git.haelnorr.com/h/golib/wiki/JWT#token-generation)
|
|
||||||
- [Token Validation](https://git.haelnorr.com/h/golib/wiki/JWT#token-validation)
|
|
||||||
- [Token Revocation](https://git.haelnorr.com/h/golib/wiki/JWT#token-revocation)
|
|
||||||
- [Cleanup](https://git.haelnorr.com/h/golib/wiki/JWT#cleanup)
|
|
||||||
- [Using with ORMs](https://git.haelnorr.com/h/golib/wiki/JWT#using-with-orms)
|
|
||||||
|
|
||||||
## Supported Databases
|
## Supported Databases
|
||||||
|
|
||||||
@@ -98,8 +90,13 @@ Comprehensive documentation is available in the [Wiki](https://git.haelnorr.com/
|
|||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
See LICENSE file in the repository root.
|
This project is licensed under the MIT License - see the LICENSE file for details.
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
Contributions are welcome! Please open an issue or submit a pull request.
|
Contributions are welcome! Please feel free to submit a Pull Request.
|
||||||
|
|
||||||
|
## Related Projects
|
||||||
|
|
||||||
|
- [hwsauth](https://git.haelnorr.com/h/golib/hwsauth) - JWT-based authentication middleware for HWS
|
||||||
|
- [hws](https://git.haelnorr.com/h/golib/hws) - HTTP web server framework
|
||||||
|
|||||||
Reference in New Issue
Block a user