Problem redirecting and using gorilla sessions in golang - go

Hello everyone I ask for help because I have a problem when I want to redirect and save sessions with gorilla sessions, I have a url which validates an http post request, and this is the code:
if err != nil {
// here i create a session using gorilla sessions with a function that i created
flash := NewFlashSession("errors", c)
// and here i set the error with a function that i also created
flash.Set("general", "Error :(")
// and i guess this is where the error starts
flash.Save()
http.Redirect(r.Writer, r.Request, "url", statusCode)
}
Actually I have a bit more complex model to explain it all in this question, but in summary what the "flash.Save()" function does is use the ".Save()" method of gorilla sessions, which receives an object "*http.Request" and "http.ResponseWriter".
And the variable "err" is an error caused by some error in validation, but when an error occurs and I want to redirect, I get the following error:
http: superfluous answer. WriteHeader call
And after doing some research, I realized that this was the cause of the problem, but. How can I save a session using Gorilla Sessions and then do a redirect? Or is there any other way to do it?
I hope you have understood me, if I do not explain myself well or if you need more information, I will try to show more of the code, I did not do it because it seems to me that the error is when I save the session and then do the redirection, and it seems to me needless to show the rest of the code. Thank you in advance :D.

I tried your code, and as they put in the comments, when adding a return there is no longer an error:
if err != nil {
// here i create a session using gorilla sessions with a function that i created
flash := NewFlashSession("errors", c)
// and here i set the error with a function that i also created
flash.Set("general", "Error :(")
// and i guess this is where the error starts
flash.Save()
http.Redirect(r.Writer, r.Request, "url", statusCode)
return;
}

Related

Deleting a non-existing identity in DynamoDB Golang

I am having a golang project where I am using dynamoDB as my backend database. I wanted to return the error when we are trying to Delete a non-existing entity. But the DynamoDB.DeleteItem does not return an error on that thing. Please help me with that.
You can actually do it using the response you will get from DeleteItem method in dynamoDB.
Ex:
resp, err := dynamoDB.DeleteItem(input)
if resp.ConsumedCapacity != nil {
\\entity not found error
}
Actually, the first struct returned by the DeleteItem function is a DeleteItemOutput
There's a comment that addresses how this object would be present
This map appears in the response only if ReturnValues was specified as ALL_OLD in the request.
You can adjust your logic accordingly and it might solve your problem

Retain original URL in redirect error message

I'm trying to determine if a webpage exists on a particular website, by sending a GET request to the specific page. However, if the webpage doesn't exist, the website redirects the request to the home page.
To overcome this, I've implemented the redirection prevention, as stated here, which looks something like
func RedirectCheck(req *http.Request, via []*http.Request) error {
if req.Response.StatusCode == 200 {
// no redirection occured
return nil
}
// return error code
return errors.New("webpage doesn't exist")
}
The redirection prevention works fine, but, if I made a get request to https://someurl.com/page1, the error message that I recieve is
Get "https://someurl.com": webpage doesn't exist
How do I configure the error message so that the original URL is retained in the error message?
The error message should then be
Get "https://someurl.com/page1": webpage doesn't exist
The Client.CheckRedirect documentation says:
As a special case, if CheckRedirect returns ErrUseLastResponse,then the most recent response is returned with its body unclosed, along with a nil error.
Fix by returning ErrUseLastResponse from the function:
func RedirectCheck(req *http.Request, via []*http.Request) error {
return http.ErroUseLastResponse
}

Node.js Express - Handle Error Differently Based on Error Type

A few details... I'm using Express 4, Node 0.12.2 and Express-Handlebars as my view engine.
I'm trying to render a partial via AJAX call and would like to handle different errors types differently. The err object passed on the callback invocation doesn't seem to have much useful info to work with, just an error message. Is there something I'm missing here?
// Search (Partial)
router.get('/search-products', function (req, res, next) {
res.render('partials/search/products', {layout: 'ajax'}, function(err, html){
if(err) {
// return res.status(404).send(err);
// return res.status(500).send(err);
}
res.send(html);
});
});
That error object isn't going to have a status code because it's an error object generated by the view engine. If that error is populated you can pretty much assume it's a 500 error because the view engine failed to compile a view for some reason.
For example, if you're using Jade, that error object will be populated if you try to have Jade compile a template that has invalid Jade syntax. The error there is never going to be HTTP related which means it's always just a server-side error and status code 500 should suffice.

User not found on cloud code call? Why?

I want to check if the cloud code request came from an actual user and then return data for that user only.
Here is my code. It passes the !currentUser test most of the time, but fails frequently even though I know there is a user making the request. Any ideas?
CODE:
Parse.Cloud.define("getData", function(request, response) {
var currentUser = request.user;
if(!currentUser) {
response.error("Failure: No user found on getData function");
return;
}
}
ERROR: Failed with: Failure: No user found on getData function
Could this be due to ACLS?
Your logic seems entirely valid, I would suggest just before your response.error() call that you do a console.log(request); so you can look at the log and see more detail.
It could be that your calling code is making a request before the login has completed in the background (race condition), or that requests are being made after a user logs out.

How to handle application errors for json api calls using CakePHP?

I am using CakePHP 2.4.
I want my frontend make api calls to my CakePHP backend using ajax.
Suppose this is to change passwords.
Change password action can throw the following application errors:
old password wrong
new password and confirm new passwords do not match
In my frontend, I have a success callback handler and a error callback handler.
The error callback handler handles all the non 200 request calls such as when I throw NotFoundException or UnAuthorizedAccessException in my action.
The success callback handler handles all the 200 request calls including of course, the above 2 scenarios.
My questions are:
Should I continue to do it this way? Meaning to say, inside all success callback handler, I need to watch out for application success and application error scenarios.
Should I send application errors back with actual HTTP error codes?
if I should do 2, how do I implement this in CakePHP?
Thank you.
Don't use http error codes for system errors like:
old password wrong
new password and confirm new passwords do not match
etc etc...
Now using success handler you can show messages and code flow as:
Create Ajax post or get to submit the form, I am showing you post example
var passwordValue = $('#password').val();
$.post( "/updatePassword", { passwordText: passwordValue })
.done(function(response) {
if(response.status === 'Success'){
// Success msg
// whatever
}else{
// Error msg
// whatever
}
});
json response would like:
{
"status": "Failed/Success",
"message": "old password wrong."
}
Create one function in controller
public function updatePassword() {
$myModel = $this->MyModel->find('first' // YOUR CODE LOGIC);
if($this->request->is('ajax') {
$this->layout=null;
// What else?
echo json_encode($myModel);
exit;
// What else?
}
}
Do something like this, hope it will solve your query!

Resources