Documentation
¶
Overview ¶
Package database provides database connectivity and context management.
It supports both SQLite and MySQL databases with automatic configuration for Hostsharing environments. The package provides context-based database access through HTTP middleware integration.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Get ¶
Get retrieves the database connection from the request context. It panics if the database connection was not previously set using Set().
Example:
func handleGetUser(w http.ResponseWriter, r *http.Request) {
db := database.Get(r.Context())
var user User
if err := db.First(&user, id).Error; err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Render user response
}
func Open ¶
Open opens a database connection based on the provided configuration.
If no database type is specified, it defaults to SQLite. For SQLite, if the DSN is empty, it defaults to "./data.db" in the current directory, or within the Hostsharing data directory if available. For MySQL, a DSN must be provided.
The returned *gorm.DB can be used to execute queries, create migrations, or be injected into context via Set() for use in HTTP handlers.
func Set ¶
Set stores the database connection in the context and returns the new context. This is typically called by SetMiddleware(), but can be used manually for testing.
Example:
db, err := database.Open(database.Config{Type: database.SQLite})
if err != nil {
log.Fatal(err)
}
ctx := database.Set(context.Background(), db)
// Now Get(ctx) will return the database connection
func SetMiddleware ¶
SetMiddleware returns an HTTP middleware that injects the database connection into the request context. This allows handlers to access the database via Get().
Example:
db, err := database.Open(database.Config{Type: database.SQLite})
if err != nil {
log.Fatal(err)
}
router.Use(database.SetMiddleware(db))
router.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
db := database.Get(r.Context())
// Use db to query users
})