How to use Gin-gonic middleware with Google App Engine? - google-app-engine

I'm using Gin-Gonic on a Google App Engine platform for my website.
Everything works fine but I'm starting to need to use some middleware.
When I try to use :
router.Use(MyMiddleware())
The middleware returned by MyMiddleware() doesn't seem to be run.
So my questions are :
Is it possible to use gin-gonic middlewares when working with GAE ?
If so, how can I achieve it ?
Thank you !
Here are my sources :
main.go :
func init() {
router := routes.Router()
// Set the config to the context
router.Use(SetConfiguration())
http.Handle("/", router)
}
func SetConfiguration() gin.HandlerFunc {
configuration := config.GetConfiguration()
return func(c *gin.Context) {
c.Set("config", configuration)
c.Next()
}
}
PS : routes.Router() simply set a router with gin.New() and add some routes.

The middleware route should be the first to be added before the other routes. See this file from a project of mine where I use CORS Middleware and Auth Middleware
https://github.com/wilsontamarozzi/panda-api/blob/master/routers/router.go

Related

locally host firebase backend with react frontend together, for debugging

I am building a react website with firebase functions backend.
I'm using firebase serve to locally host the node.js backend that I connect to my react code through express API endpoints, and I am using react-scripts start to test my react frontend app.
all my get requests in my react app use /some endpoint to communicate with my firebase localserver. But they are running on different ports. firebase serves it on localhost:5000 while react live server hosts it at localhost:3000.
I tried many things and couldn't get any useful way to make this work. I at last added my react project as a subfolder in my firebase project and made the hosting public path at firebase.json to my react build directory. It works now but I always have to run npm run build on my react app on every change, to make it compile my app into the build directory, which is painfully slow.
What is the proper way to do this? debug react app and firebase backend together.
I finally enabled cross-origin-requests on my server using cors module
Serverside code
const cors = require("cors");
app.get("/test", (req, res) => {
return cors()(req, res, async () => {
res.send("working...");
});
});
Serverside code
And then adding a simple config file in the react side, to switch between debugging and deployed testing really helped.
config.js
var domain = "";
// domain = "http://localhost:5000";
export {domain}
then whenever I use apis in react, I simply comment/uncomment the second line to switch between local and deployed testing.
Then whenever I use APIs, I append `domain` before every url in all references, eg fetch requests
import { domain } from "config.js";
fetch(domain + "/int-search", ...
Then it worked fine running both the firebase backend and the react application on localhost, using firebase serve and npm start for my react app.

Firebase - How to create proxy for web app to prevent CORS

I have a React app that pulling data via Rest API from a different domain.
In my development env in order to work around this, I am using http-proxy-middleware.
module.exports = function (app) {
app.use(
createProxyMiddleware("/shabbat", {
target: "https://www.hebcal.com",
changeOrigin: true
})
)
}
Since I am using Firebase to host my web app I need to handle this via Firebase but can't figure it our how to properly configure.
I would appreciate it if someone can share a working example.
Thank you
i also got this error, i changed to use another https://xxx api to test,then worked well, so i guess this issue is due to firebase's settings, but i haven't found the solution

Redirect from http to https on localhost with create-react-app to test with Lighthouse

I have configured create-react-app to use https in my local development environment. I would now like to convert my React application to a progressive web app and I plan to use Lighthouse to check my status. I am running Lighthouse as a Chrome plugin, but I am having trouble with the part when it is checking if my HTTP requests are redirected to HTTPS. They are not.
I have been crawling through my node_modules and I have taken a look at webpack-dev-server that is bundled with create-react-app. I have tried to make some changes, but the best I have managed so far is that I have gotten "Too many redirects".
TL;DR: How can I configure create-react-app to redirect all requests from http to https on my local dev environment?
Here's the code from my create-react-app if you are having trouble with just the redirect part. I'm doing it manually since Heroku doesn't automatically handle it. But this actually needs to be handled on the server because it makes the app visibly load twice if it has to redirect to http. But for now, I'm redirecting in the constructor of my App component.
constructor(props, context) {
const url = window.location.origin
if (!url.includes('localhost') && !url.includes('https')) {
window.location = `https:${url.split(':'))[1]}`
}
}
For your purposes, you'd just need to take out the localhost part and make the new url a little differently (because of the port).
I'm using ramda here, but lodash also has a tail function you can use.
import { tail } from 'ramda
...
constructor(props, context) {
const url = window.location.origin
if (!url.includes('https')) {
window.location = `https:${tail(url.split(':')).join(':')}`
}
}
#Fmacs, for redirection of HTTP traffic to HTTPS, instead of using local dev-server, deploy your app on any environment like Heroku or Firebase. Firebase is very simple. I see that you also have other issues running the create-react-app that you created. I have explained how to do this in simple steps in a blog post with sample code in GitHub. Please refer to: http://softwaredevelopercentral.blogspot.com/2019/10/react-pwa-tutorial.html

Setting up an App Engine Context in Go

I post JSON to an app I registered at Google App Engine but I am baffled by the authentication process in my Go code to get it working in appengine:
func init() {
http.HandleFunc("/post", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
app := appengine.NewContext(r)
client := &http.Client{
Transport: &oauth2.Transport{
Source: google.AppEngineTokenSource(app, "https://www.googleapis.com/auth/bigquery"),
Base: &urlfetch.Transport{
Context: app,
},
},
}
log.Print(client)
}
In following the docs, I have reduced my problem to the code above which consistently gives me the following error:
2015/01/28 09:05:32 appengine: NewContext passed an unknown http.Request
I'd love some pointers as to how I can provide appengine with a "known" http.Request because ultimately I am trying to get to the storage api which also requires a valid context.
Does removing and re go getting google.golang.org/appengine from your GOPATH fixes the issue ?
Edit: Also, a colleague of mine said that after rebooting all went well.

Access remote service using GWTP Rest Dispatch

I want to separate packages for UI and backend development of my GWTP app.
Currently my UI access the backend using Rest dispatch configured like this:
bindConstant().annotatedWith(RestApplicationPath.class).to("/MyProject/api");
I want to access remote service using localhost UI (running GWT app using eclipse plugin). I changed the above line to:
bindConstant().annotatedWith(RestApplicationPath.class).to("http://my-app.appspot.com/MyProject/api");
Using this, call successfully reaches server ( I can see this in appengine logs) but UI always gets back status code 0.
What is wrong with above setup? Do I have to do something else to access remote service using GWT ui ?
If you want to have a solution that works both on localhost/App Engine, you'd want to use something like this:
import com.google.gwt.core.client.GWT;
import com.google.gwt.inject.client.AbstractGinModule;
import com.google.inject.Provides;
import com.gwtplatform.dispatch.rest.client.RestApplicationPath;
import com.gwtplatform.dispatch.rest.client.gin.RestDispatchAsyncModule;
public class ServiceModule extends AbstractGinModule {
#Override
protected void configure() {
install(new RestDispatchAsyncModule.Builder().build());
}
#Provides
#RestApplicationPath
String getApplicationPath() {
String baseUrl = GWT.getHostPageBaseURL();
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
}
return baseUrl + "/MyProject/api";
}
}
The string returned by getApplicationPath will be bound to #RestApplicationPath and used seamlessly by GWTP's RestDispatch.
In your case, the string will resolve to http://localhost:8080/MyProject/api or "http://my-app.appspot.com/MyProject/api" depending on the app running locally or on App Engine.

Resources