ron-example/internal/handlers/handlers.go

76 lines
1.6 KiB
Go

package handlers
import (
"context"
"fmt"
"log/slog"
"net/http"
"ron"
"ron-pets/internal/config"
"ron-pets/internal/repository"
"ron-pets/internal/sqlc"
)
type Handlers struct {
app *config.App
queries repository.ExtendedQuerier
}
func New(app *config.App, q repository.ExtendedQuerier) *Handlers {
return &Handlers{
app: app,
queries: q,
}
}
func (hq *Handlers) HelloWorld(c *ron.CTX, ctx context.Context) {
session, ok := ctx.Value("session").(*sqlc.SessionData)
if !ok || session == nil {
http.Error(c.W, "Unauthorized", http.StatusUnauthorized)
return
}
fmt.Fprintf(c.W, "User ID: %s, Role: %s", session.UserID, session.Role)
c.W.Write([]byte("hello world"))
}
func (hq *Handlers) AnotherHelloWorld(c *ron.CTX) {
val := c.R.Context().Value("key")
//val := context.Background().Value("key")
slog.Info("context value", "value", val)
c.W.Write([]byte("another hello world"))
}
func (hq *Handlers) HelloWorldJSON(c *ron.CTX) {
id := c.R.PathValue("id")
slog.Info("path value", "id", id)
c.JSON(200, ron.Data{"message": "hello world"})
}
func (hq *Handlers) HelloWorldHTML(c *ron.CTX) {
//pages := ron.Pages{
// TotalElements: len(elements),
// ElementsPerPage: 5,
//}
//
//pages.PaginationParams(c.R)
//elementsPaginated := pages.PaginateArray(elements)
//
//td := &ron.TemplateData{
// Data: ron.Data{"title": "hello world", "message": "hello world from html", "elements": elementsPaginated},
// Pages: pages,
//}
//
//c.HTML(200, "page.index.gohtml", td)
}
func (hq *Handlers) ComponentHTML(c *ron.CTX) {
c.HTML(200, "component.list.gohtml", nil)
}