How can I change my code to return custom JSON instead of status 200?

I am trying to figure out how to implement basic auth with haskell / yesod, and this is a basic implementation that works, citing similar questions.

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 () 

I would like to change my implementation to return not only an HTTP 200 response code, but also a custom JSON that reads {"hello": "world"} .

How can i achieve this?

EDIT

As suggested by different people below, I have to write getBasicAuthR as

 getBasicAuthR :: Handler Value getBasicAuthR = httpBasicAuth >> sendResponse $ object ["hello" .= "world"] 

But it just gives me an error that says

 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 
+6
source share
2 answers

First, if you want to respond using a JSON object, you must change the type of handler. Since yesod-core uses aeson , the corresponding type is Handler Value :

 getBasicAuthR :: Handler Value 

Due to the laws of the monad, httpBasicAuth >> remains, but it is followed by sendResponse (or sendResponseStatus 200 ) with an additional object:

 getBasicAuthR = httpBasicAuth >> sendResponse (object ["hello" .= "world"]) 
+1
source

This answer is taken from Zeta's comment:

 getBasicAuthR :: Handler JSON getBasicAuthR = httpBasicAuth >> sendResponse (object ["hello" .= "world]) 
0
source

Source: https://habr.com/ru/post/979611/


All Articles