HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Type classes

6 declarations
classclass RenderRoute site => Yesod site where
#

Define settings for a Yesod applications. All methods have intelligent defaults, and therefore no implementation is required.

Methods

  • approot :: Approot site

    An absolute URL to the root of the application. Do not include trailing slash.

    Default value: guessApproot. If you know your application root statically, it will be more efficient and more reliable to instead use ApprootStatic or ApprootMaster. If you do not need full absolute URLs, you can use ApprootRelative instead.

    Note: Prior to yesod-core 1.5, the default value was ApprootRelative.

  • catchHandlerExceptions :: MonadUnliftIO m => site -> m a -> (SomeException -> m a) -> m a

    allows the user to specify how exceptions are cought. by default all async exceptions are thrown and synchronous exceptions render a 500 page. To catch all exceptions (even async) to render a 500 page, set this to catchSyncOrAsync. Beware this may have negative effects with functions like timeout.

  • errorHandler :: ErrorResponse -> HandlerFor site TypedContent

    Output error response pages.

    Default value: defaultErrorHandler.

  • defaultLayout :: WidgetFor site () -> HandlerFor site Html

    Applies some form of layout to the contents of a page.

  • urlParamRenderOverride :: site -> Route site -> [(Text, Text)] -> Maybe Builder

    Override the rendering function for a particular URL and query string parameters. One use case for this is to offload static hosting to a different domain name to avoid sending cookies.

    For backward compatibility default implementation is in terms of urlRenderOverride, probably ineffective

    Since 1.4.23

  • isAuthorized :: Route site -> Bool -> HandlerFor site AuthResult

    Determine if a request is authorized or not.

    Return Authorized if the request is authorized, Unauthorized a message if unauthorized. If authentication is required, return AuthenticationRequired.

  • isWriteRequest :: Route site -> HandlerFor site Bool

    Determines whether the current request is a write request. By default, this assumes you are following RESTful principles, and determines this from request method. In particular, all except the following request methods are considered write: GET HEAD OPTIONS TRACE.

    This function is used to determine if a request is authorized; see isAuthorized.

  • authRoute :: site -> Maybe (Route site)

    The default route for authentication.

    Used in particular by isAuthorized, but library users can do whatever they want with it.

  • cleanPath :: site -> [Text] -> Either [Text] [Text]

    A function used to clean up path segments. It returns Right with a clean path or Left with a new set of pieces the user should be redirected to. The default implementation enforces:

    • No double slashes

    • There is no trailing slash.

    Note that versions of Yesod prior to 0.7 used a different set of rules involing trailing slashes.

  • joinPath :: site -> Text -> [Text] -> [(Text, Text)] -> Builder

    Builds an absolute URL by concatenating the application root with the pieces of a path and a query string, if any. Note that the pieces of the path have been previously cleaned up by cleanPath.

  • addStaticContent :: Text -> Text -> ByteString -> HandlerFor site (Maybe (Either Text (Route site, [(Text, Text)])))

    This function is used to store some static content to be served as an external file. The most common case of this is stashing CSS and JavaScript content in an external file; the Yesod.Widget module uses this feature.

    The return value is Nothing if no storing was performed; this is the default implementation. A Just Left gives the absolute URL of the file, whereas a Just Right gives the type-safe URL. The former is necessary when you are serving the content outside the context of a Yesod application, such as via memcached.

  • maximumContentLength :: site -> Maybe (Route site) -> Maybe Word64

    Maximum allowed length of the request body, in bytes. This method may be ignored if maximumContentLengthIO is overridden.

    If Nothing, no maximum is applied.

    Default: 2 megabytes.

  • maximumContentLengthIO :: site -> Maybe (Route site) -> IO (Maybe Word64)

    Maximum allowed length of the request body, in bytes. This is similar to maximumContentLength, but the result lives in IO. This allows you to dynamically change the maximum file size based on some external source like a database or an IORef.

    The default implementation uses maximumContentLength. Future version of yesod will remove maximumContentLength and use this method exclusively.

  • makeLogger :: site -> IO Logger

    Creates a Logger to use for log messages.

    Note that a common technique (endorsed by the scaffolding) is to create a Logger value and place it in your foundation datatype, and have this method return that already created value. That way, you can use that same Logger for printing messages during app initialization.

    Default: the defaultMakeLogger function.

  • messageLoggerSource :: site -> Logger -> Loc -> LogSource -> LogLevel -> LogStr -> IO ()

    Send a message to the Logger provided by getLogger.

    Default: the defaultMessageLoggerSource function, using shouldLogIO to check whether we should log.

  • jsLoader :: site -> ScriptLoadPosition site

    Where to Load sripts from. We recommend the default value, BottomOfBody.

  • jsAttributes :: site -> [(Text, Text)]

    Default attributes to put on the JavaScript script tag generated for julius files

  • jsAttributesHandler :: HandlerFor site [(Text, Text)]

    Same as jsAttributes but allows you to run arbitrary Handler code

    This is useful if you need to add a randomised nonce value to the script tag generated by widgetFile. If this function is overridden then jsAttributes is ignored.

  • makeSessionBackend :: site -> IO (Maybe SessionBackend)

    Create a session backend. Returning Nothing disables sessions. If you'd like to change the way that the session cookies are created, take a look at customizeSessionCookies.

    Default: Uses clientsession with a 2 hour timeout.

  • fileUpload :: site -> RequestBodyLength -> FileUpload

    How to store uploaded files.

    Default: When the request body is greater than 50kb, store in a temp file. For chunked request bodies, store in a temp file. Otherwise, store in memory.

  • shouldLogIO :: site -> LogSource -> LogLevel -> IO Bool

    Should we log the given log source/level combination.

    Default: the defaultShouldLogIO function.

    Since 1.2.4

  • yesodMiddleware :: ToTypedContent res => HandlerFor site res -> HandlerFor site res

    A Yesod middleware, which will wrap every handler function. This allows you to run code before and after a normal handler.

    Default: the defaultYesodMiddleware function.

    Since: 1.1.6

  • yesodWithInternalState :: site -> Maybe (Route site) -> (InternalState -> IO a) -> IO a

    How to allocate an InternalState for each request.

    The default implementation is almost always what you want. However, if you know that you are never taking advantage of the MonadResource instance in your handler functions, setting this to a dummy implementation can provide a small optimization. Only do this if you really know what you're doing, otherwise you can turn safe code into a runtime error!

    Since 1.4.2

  • defaultMessageWidget :: Html -> HtmlUrl (Route site) -> WidgetFor site ()

    Convert a title and HTML snippet into a Widget. Used primarily for wrapping up error messages for better display.

Instances1Yesod
  • Yesod LiteAppDefined in yesod-core-1.6.26.0 · Yesod.Core.Internal.LiteApp

Breadcrumbs

classclass YesodBreadcrumbs site where
#

A type-safe, concise method of creating breadcrumbs for pages. For each resource, you declare the title of the page and the parent resource (if present).

Methods

Types

3 declarations
datadata ErrorResponse
#

Responses to indicate some form of an error occurred.

Constructors

  • NotFound

    The requested resource was not found. Examples of when this occurs include when an incorrect URL is used, or yesod-persistent's get404 doesn't find a value. HTTP status: 404.

  • InternalError !Text

    Some sort of unexpected exception. If your application uses throwIO or error to throw an exception, this is the form it would take. HTTP status: 500.

  • InvalidArgs ![Text]

    Indicates some sort of invalid or missing argument, like a missing query parameter or malformed JSON body. Examples Yesod functions that send this include requireCheckJsonBody and Yesod.Auth.GoogleEmail2. HTTP status: 400.

  • NotAuthenticated

    Indicates the user is not logged in. This is thrown when isAuthorized returns AuthenticationRequired. HTTP code: 401.

  • PermissionDenied !Text

    Indicates the user doesn't have permission to access the requested resource. This is thrown when isAuthorized returns Unauthorized. HTTP code: 403.

  • BadMethod !Method

    Indicates the URL would have been valid if used with a different HTTP method (e.g. a GET was used, but only POST is handled.) HTTP code: 405.

Instances5Eq, Show, Generic, NFData, Rep

Utilities

2 declarations

Defaults

3 declarations

Data types

2 declarations

Logging

15 declarations

Default formatting for log messages. When you use the template haskell logging functions for to log with information about the source location, that information will be appended to the end of the log. When you use the non-TH logging functions, like logDebugN, this function does not include source information. This currently works by checking to see if the package name is the string "<unknown>". This is a hack, but it removes some of the visual clutter from non-TH logs.

Since 1.4.10

valuelogDebug :: Q Exp
#

Generates a function that takes a Text and logs a LevelDebug message. Usage:

$(logDebug) "This is a debug log message"
valuelogOther :: Text -> Q Exp
#

Generates a function that takes a Text and logs a LevelOther message. Usage:

$(logOther "My new level") "This is a log message"
valuelogOtherS :: Q Exp
#

Generates a function that takes a LogSource, a level name and a Text and logs a LevelOther message. Usage:

$logOtherS "SomeSource" "My new level" "This is a log message"

Sessions

12 declarations
valueenvClientSessionBackend
  1. :: Int

    minutes

  2. -> String

    environment variable name

  3. -> IO SessionBackend
#

Create a SessionBackend which reads the session key from the named environment variable.

This can be useful if:

  1. You can't rely on a persistent file system (e.g. Heroku)

  2. Your application is open source (e.g. you can't commit the key)

By keeping a consistent value in the environment variable, your users will have consistent sessions without relying on the file system.

Note: A suitable value should only be obtained in one of two ways:

  1. Run this code without the variable set, a value will be generated and printed on devstdout/

  2. Use clientsession-generate

Since 1.4.5

Defends against session hijacking by setting the secure bit on session cookies so that browsers will not transmit them over http. With this setting on, it follows that the server will regard requests made over http as sessionless, because the session cookie will not be included in the request. Use this as part of a total security measure which also includes disabling HTTP traffic to the site or issuing redirects from HTTP urls, and composing sslOnlyMiddleware with the site's yesodMiddleware.

Since 1.4.7

Helps defend against CSRF attacks by setting the SameSite attribute on session cookies to Lax. With the Lax setting, the cookie will be sent with same-site requests, and with cross-site top-level navigations.

This option is liable to change in future versions of Yesod as the spec evolves. View more information here.

Helps defend against CSRF attacks by setting the SameSite attribute on session cookies to Strict. With the Strict setting, the cookie will only be sent with same-site requests.

This option is liable to change in future versions of Yesod as the spec evolves. View more information here.

valuesslOnlyMiddleware
  1. :: Int

    minutes

  2. -> HandlerFor site res
  3. -> HandlerFor site res
#

Apply a Strict-Transport-Security header with the specified timeout to all responses so that browsers will rewrite all http links to https until the timeout expires. For security, the max-age of the STS header should always equal or exceed the client sessions timeout. This defends against SSL-stripping man-in-the-middle attacks. It is only effective if a secure connection has already been made; Strict-Transport-Security headers are ignored over HTTP.

Since 1.4.7

CSRF protection

5 declarations
valuecsrfSetCookieMiddleware
  1. :: HandlerFor site res
  2. -> SetCookie
  3. -> HandlerFor site res
#

Takes a SetCookie and overrides its value with a CSRF token, then sets the cookie. See setCsrfCookieWithCookie.

For details, see the "AJAX CSRF protection" section of Yesod.Core.Handler.

Make sure to set the setCookiePath to the root path of your application, otherwise you'll generate a new CSRF token for every path of your app. If your app is run from from e.g. www.example.com/app1, use app1. The vast majority of sites will just use /.

Since 1.4.14

valuecsrfCheckMiddleware
  1. :: HandlerFor site res
  2. -> HandlerFor site Bool

    Whether or not to perform the CSRF check.

  3. -> CI ByteString

    The header name to lookup the CSRF token from.

  4. -> Text

    The POST parameter name to lookup the CSRF token from.

  5. -> HandlerFor site res
#

Looks up the CSRF token from the request headers or POST parameters. If the value doesn't match the token stored in the session, this function throws a PermissionDenied error.

For details, see the "AJAX CSRF protection" section of Yesod.Core.Handler.

Since 1.4.14

JS loaders

2 declarations

Generalizing type classes

2 declarations
classclass (MonadResource m, MonadLogger m) => MonadHandler (m :: Type -> Type) where
#

Associated types

Instances15MonadHandler, …
classclass MonadHandler m => MonadWidget (m :: Type -> Type) where
#

Methods

Instances13MonadWidget, …

Approot

3 declarations
valueguessApprootOr :: Approot site -> Approot site
#

Guess the approot based on request headers, with fall back to the specified AppRoot.

Since 1.4.16

Misc

3 declarations

LiteApp

12 declarations
newtypenewtype LiteApp
#
Instances11Semigroup, Monoid, YesodDispatch, Yesod, ParseRoute, RenderRoute, …
familydata family Route a
#

The type-safe URLs associated with a site argument.

Instances18RedirectUrl, Eq, Ord, Read, Show, Route, …
familydata family Route a
#

The type-safe URLs associated with a site argument.

Instances18RedirectUrl, Eq, Ord, Read, Show, Route, …

Low-level

1 declaration

Re-exports

18 declarations
classclass RenderMessage master message where
#

the RenderMessage is used to provide translations for a message types

The master argument exists so that it is possible to provide more than one set of translations for a message type. This is useful if a library provides a default set of translations, but the user of the library wants to provide a different set of translations.

Methods

Instances2RenderMessage
classclass ToMessage a where
#

ToMessage is used to convert the value inside #{ } to Text

The primary purpose of this class is to allow the value in #{ } to be a String or Text rather than forcing it to always be Text.

Methods

Instances2ToMessage
  • ToMessage StringDefined in shakespeare-2.1.0.1 · Text.Shakespeare.I18N
  • ToMessage TextDefined in shakespeare-2.1.0.1 · Text.Shakespeare.I18N
valuemkMessage
  1. :: String

    base name to use for translation type

  2. -> FilePath

    subdirectory which contains the translation files

  3. -> Lang

    default translation language

  4. -> Q [Dec]
#

generate translations from translation files

This function will:

  1. look in the supplied subdirectory for files ending in .msg

  2. generate a type based on the constructors found

  3. create a RenderMessage instance

typetype Lang = Text
#

an RFC1766 / ISO 639-1 language code (eg, fr, en-GB, etc).

typetype Html = Markup
#
Instances12ToHamletData, HasContentType, ToContent, ToTypedContent, ToWidget, ToWidgetBody, …
classclass (forall (m :: Type -> Type). Monad m => Monad (t m)) => MonadTrans (t :: (Type -> Type) -> Type -> Type) where
#

The class of monad transformers. For any monad m, the result t m should also be a monad, and lift should be a monad transformation from m to t m, i.e. it should satisfy the following laws:

Since 0.6.0.0 and for GHC 8.6 and later, the requirement that t m be a Monad is enforced by the implication constraint forall m. Monad m => Monad (t m) enabled by the QuantifiedConstraints extension.

Ambiguity error with GHC 9.0 to 9.2.2

These versions of GHC have a bug (https://gitlab.haskell.org/ghc/ghc/-/issues/20582) which causes constraints like

(MonadTrans t, forall m. Monad m => Monad (t m)) => ...

to be reported as ambiguous. For transformers 0.6 and later, this can be fixed by removing the second constraint, which is implied by the first.

Methods

  • lift :: Monad m => m a -> t m a

    Lift a computation from the argument monad to the constructed monad.

Instances24MonadTrans, …
classclass Monad m => MonadIO (m :: Type -> Type) where
#

Monads in which IO computations may be embedded. Any monad built by applying a sequence of monad transformers to the IO monad will be an instance of this class.

Instances should satisfy the following laws, which state that liftIO is a transformer of monads:

Methods

  • liftIO :: IO a -> m a

    Lift a computation from the IO monad. This allows us to run IO computations in any monadic stack, so long as it supports these kinds of operations (i.e. IO is the base monad for the stack).

    Example
    import Control.Monad.Trans.State -- from the "transformers" library
    
    printState :: Show s => StateT s IO ()
    printState = do
      state <- get
      liftIO $ print state

    Had we omitted liftIO, we would have ended up with this error:

    • Couldn't match type ‘IO’ with ‘StateT s IO’
     Expected type: StateT s IO ()
       Actual type: IO ()

    The important part here is the mismatch between StateT s IO () and IO ().

    Luckily, we know of a function that takes an IO a and returns an (m a): liftIO, enabling us to run the program and see the expected results:

    > evalStateT printState "hello"
    "hello"
    
    > evalStateT printState 3
    3
    
Instances32MonadIO, …
classclass MonadIO m => MonadUnliftIO (m :: Type -> Type) where
#

Monads which allow their actions to be run in IO.

While MonadIO allows an IO action to be lifted into another monad, this class captures the opposite concept: allowing you to capture the monadic context. Note that, in order to meet the laws given below, the intuition is that a monad must have no monadic state, but may have monadic context. This essentially limits MonadUnliftIO to ReaderT and IdentityT transformers on top of IO.

Laws. For any function run provided by withRunInIO, it must meet the monad transformer laws as reformulated for MonadUnliftIO:

  • run . return = return
  • run (m >>= f) = run m >>= run . f

Instances of MonadUnliftIO must also satisfy the following laws:

Identity law

withRunInIO (\run -> run m) = m

Inverse law

withRunInIO (\_ -> m) = liftIO m

As an example of an invalid instance, a naive implementation of MonadUnliftIO (StateT s m) might be

withRunInIO inner =
  StateT $ \s ->
    withRunInIO $ \run ->
      inner (run . flip evalStateT s)

This breaks the identity law because the inner run m would throw away any state changes in m.

Methods

  • withRunInIO :: ((forall a. m a -> IO a) -> IO b) -> m b

    Convenience function for capturing the monadic context and running an IO action with a runner function. The runner function is used to run a monadic action m in IO.

Instances9MonadUnliftIO, …
classclass MonadIO m => MonadResource (m :: Type -> Type) where
#

A Monad which allows for safe resource allocation. In theory, any monad transformer stack which includes a ResourceT can be an instance of MonadResource.

Note: runResourceT has a requirement for a MonadUnliftIO m monad, which allows control operations to be lifted. A MonadResource does not have this requirement. This means that transformers such as ContT can be an instance of MonadResource. However, the ContT wrapper will need to be unwrapped before calling runResourceT.

Since 0.3.0

Methods

Instances19MonadResource, …
classclass Monad m => MonadLogger (m :: Type -> Type) where
#

A Monad which has the ability to log messages in some manner.

Instances20MonadLogger, …

Commonly referenced functions/datatypes

1 declaration

The WAI application.

Note that, since WAI 3.0, this type is structured in continuation passing style to allow for proper safe resource handling. This was handled in the past via other means (e.g., ResourceT). As a demonstration:

app :: Application
app req respond = bracket_
    (putStrLn "Allocating scarce resource")
    (putStrLn "Cleaning up")
    (respond $ responseLBS status200 [] "Hello World")
Instances2ToApplication
  • ToApplication ApplicationDefined in wai-extra-3.1.16 · Network.Wai.UrlMap
  • ToApplication UrlMapDefined in wai-extra-3.1.16 · Network.Wai.UrlMap

Utilities

2 declarations

Shakespeare

0 declarations

Hamlet

valuehamlet :: QuasiQuoter
#

Hamlet quasi-quoter. May only be used to generate expressions.

Generated expression have type HtmlUrl url, for some url.

data MyRoute = Home

render :: Render MyRoute
render Home _ = "/home"

>>> putStrLn (renderHtml ([hamlet|<a href=@{Home}>Home|] render))
<a href="/home">Home</a>
valueshamlet :: QuasiQuoter
#

"Simple Hamlet" quasi-quoter. May only be used to generate expressions.

Generated expressions have type Html.

>>> putStrLn (Text.Blaze.Html.Renderer.renderHtml [shamlet|<div>Hello, world!|])
<div>Hello, world!</div>

Julius

valuerenderJavascriptUrl
  1. :: url -> [(Text, Text)] -> Text
  2. -> JavascriptUrl url
  3. -> Text
#

render with route interpolation. If using this module standalone, apart from type-safe routes, a dummy renderer can be used:

renderJavascriptUrl (\_ _ -> undefined) javascriptUrl

When using Yesod, a renderer is generated for you, which can be accessed within the GHandler monad: getUrlRenderParams.

Cassius/Lucius

valuelucius :: QuasiQuoter
#
Example1 expression
renderCss ([lucius|foo{bar:baz}|] undefined)"foo{bar:baz}"