superkit/view/view.go

54 lines
1.5 KiB
Go
Raw Permalink Normal View History

2024-06-06 10:04:51 +02:00
package view
import (
"context"
2024-06-08 11:20:22 +02:00
"fmt"
"net/http"
2024-06-06 10:04:51 +02:00
"net/url"
2024-06-16 17:59:28 +02:00
"github.com/anthdm/superkit/kit"
"github.com/anthdm/superkit/kit/middleware"
2024-06-06 10:04:51 +02:00
)
// Asset is a view helper that returns the full asset path as a
2024-06-08 11:49:34 +02:00
// string based on the given asset name.
//
// view.Asset("styles.css") // => /public/assets/styles.css.
func Asset(name string) string {
return fmt.Sprintf("/public/assets/%s", name)
2024-06-08 11:20:22 +02:00
}
// getContextValue is a helper function to retrieve a value from the context.
// It returns the value if present, otherwise returns the provided default value.
func getContextValue[T any](ctx context.Context, key interface{}, defaultValue T) T {
value, ok := ctx.Value(key).(T)
if !ok {
return defaultValue
}
return value
}
2024-06-06 16:15:35 +02:00
// Auth is a view helper function that returns the current Auth.
// If Auth is not set, a default Auth will be returned.
2024-06-08 11:49:34 +02:00
//
// view.Auth(ctx)
2024-06-06 10:04:51 +02:00
func Auth(ctx context.Context) kit.Auth {
return getContextValue(ctx, kit.AuthKey{}, kit.DefaultAuth{})
2024-06-06 10:04:51 +02:00
}
// URL is a view helper that returns the current URL.
// The request path can be accessed with:
2024-06-08 11:49:34 +02:00
//
// view.URL(ctx).Path // => ex. /login
2024-06-06 10:04:51 +02:00
func URL(ctx context.Context) *url.URL {
return getContextValue(ctx, middleware.RequestKey{}, &http.Request{}).URL
}
// Request is a view helper that returns the current http request.
// The request can be accessed with:
//
// view.Request(ctx)
func Request(ctx context.Context) *http.Request {
return getContextValue(ctx, middleware.RequestKey{}, &http.Request{})
2024-06-06 10:04:51 +02:00
}