我试图找出如何使用haskell / yesod实现基本auth,这是一个有效的基本实现,从类似的问题中引用。
module Handler.BasicAuth where
import Import
import Network.Wai
import Network.HTTP.Types as Import
( status200 )
httpBasicAuth :: Handler ()
{-getBasicAuthR = error "Not yet implemented: getBasicAuthR"-}
httpBasicAuth = do
request <- waiRequest
case lookup "Authorization" (requestHeaders request) of
Just "Basic base64encodedusernameandpassword" -> return ()
_ -> do
addHeader "WWW-Authenticate" "Basic Realm=\"My Realm\""
permissionDenied "Authentication required"
getBasicAuthR :: Handler ()
getBasicAuthR = httpBasicAuth >>
sendResponseStatus status200 ()
我想修改我的实现,不仅返回http响应代码200,还返回读取{"hello": "world"}
的自定义JSON。
我怎样才能做到这一点?
修改
正如以下各方所建议的那样,我应该将getBasicAuthR
写为
getBasicAuthR :: Handler Value
getBasicAuthR = httpBasicAuth >> sendResponse $ object ["hello" .= "world"]
但这只是给我一个错误,说
Handler/BasicAuth.hs:27:17:
Couldn't match expected type ‘Value -> Handler Value’
with actual type ‘HandlerT App IO b0’
The first argument of ($) takes one argument,
but its type ‘HandlerT App IO b0’ has none
In the expression:
httpBasicAuth >> sendResponse $ object ["hello" .= "world"]
In an equation for ‘getBasicAuthR’:
getBasicAuthR
= httpBasicAuth >> sendResponse $ object ["hello" .= "world"]
Handler/BasicAuth.hs:27:34:
Couldn't match expected type ‘HandlerT App IO b0’
with actual type ‘c0 -> m0 a0’
Probable cause: ‘sendResponse’ is applied to too few arguments
In the second argument of ‘(>>)’, namely ‘sendResponse’
In the expression: httpBasicAuth >> sendResponse
答案 0 :(得分:1)
首先,如果您想要使用JSON对象进行响应,则可以更改处理程序的类型。由于yesod-core
使用aeson
,因此相应的类型为Handler Value
:
getBasicAuthR :: Handler Value
由于monad法律,httpBasicAuth >>
会停留,但后跟sendResponse
(或sendResponseStatus 200
)并附加一个对象:
getBasicAuthR = httpBasicAuth >> sendResponse (object ["hello" .= "world"])
答案 1 :(得分:0)
这个答案取自Zeta的评论:
getBasicAuthR :: Handler JSON
getBasicAuthR = httpBasicAuth >> sendResponse (object ["hello" .= "world])