How to refresh the current page in Golang after executing a function

76 views Asked by At

I have a small Golang project that uses templates to display tables in a browser, which it retrieves from a remote server that simulates an Economy. The remote server has an API with endpoints to carry out actions for example 'Trade' or 'Produce'.

Effectively, the project is functioning as a front end. I used Go because it had a lower learning curve for me than, say, React or .js based solutions and because it was a way to learn Go by using it for a practical applicatin.

This doesn't seem to be a very common use case (which may mean it's not a good idea) so I haven't been able to find many standard answers to the issues that my project is generating. Maybe there is a community out there that I haven't found yet.

When the remote server has satisfied the request, I want the browser to update whatever table the user is currently looking at, that is, refresh the current page but with modified data. The remote server can update the data, but it doesn't know anything about how this data is being displayed, because I want a complete separation of concerns.

How do I simply refresh this current page? This is something I have been able to do in Django, but can't find the equivalent in Go or gin. For most of the examples I have studied, Gin would generate a GET or POST request which returns the data required for a specific page, related to the request (for example 'display all industries' or 'display one industry'). But I want to display whatever table the user was currently looking at.

I am using gin to handle the table displays but I am not wedded to it.

1

There are 1 answers

0
ancient geek On

I fixed this as follows:

The app maintains a list of logged-in users (which is stored as a map, but anything that yields a User model should do)

Each User is represented by a struct containing a field lastLoggedIn which contains the relative URL of the page that user was visiting, at the time of the request to undertake some action or other (such as updating the simulation)

After the action is complete, its handler calls

ctx.Redirect(http.StatusFound, lastVisitedPage) 

where ctx is the *gin.Context parameter passed into the handler that generates the action

I found the following to be useful sources of information:

https://gin-gonic.com/docs/examples/redirects/

https://stackoverflow.com/questions/68836237/how-to-get-full-server-url-from-any-endpoint-handler-in-gin

Worth nothing that the second reference says

If anyone is familiar with Python's fast API, the Request object has a method url_for(<endpoint_name>) which has the exact same functionality

So maybe other users migrating from Python to Go have experienced similar puzzlement