Skip to content

Instantly share code, notes, and snippets.

@satishbabariya
Created December 7, 2021 11:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save satishbabariya/2bbb72befb3ff20b1ae1f505bee8d6fd to your computer and use it in GitHub Desktop.
Save satishbabariya/2bbb72befb3ff20b1ae1f505bee8d6fd to your computer and use it in GitHub Desktop.
supabase + gorush notification middleware service
package main
import (
"fmt"
"net/http"
"os"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
"github.com/appleboy/gorush/rpc/proto"
"google.golang.org/grpc"
)
type Config struct {
port int
debug bool
gorushAddress string
}
type Server struct {
client proto.GorushClient
}
func main() {
config := &Config{}
app := &cli.App{
Name: "notifications",
Usage: "a general push notification server for ios and android",
Flags: []cli.Flag{
&cli.IntFlag{
Name: "port",
Value: 1203,
Usage: "the port on which the server will listen",
Destination: &config.port,
EnvVars: []string{"PORT"},
},
&cli.BoolFlag{
Name: "debug",
Usage: "enable debug mode",
Value: false,
Destination: &config.debug,
EnvVars: []string{"DEBUG"},
},
&cli.StringFlag{
Name: "gorush-address",
Value: "localhost:3000",
Usage: "the address of gorush server",
Destination: &config.gorushAddress,
EnvVars: []string{"GORUSH_ADDRESS"},
},
},
Action: func(ctx *cli.Context) error {
conn, err := grpc.Dial(config.gorushAddress, grpc.WithInsecure())
if err != nil {
return err
}
defer conn.Close()
client := proto.NewGorushClient(conn)
srv := &Server{
client: client,
}
port := fmt.Sprintf(":%d", config.port)
if config.debug {
logrus.SetLevel(logrus.DebugLevel)
}
e := echo.New()
e.HideBanner = true
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Routes
e.POST("/notification/send", srv.send)
e.Logger.Fatal(e.Start(port))
return nil
},
}
err := app.Run(os.Args)
if err != nil {
logrus.Fatal(err)
}
}
func (srv *Server) send(c echo.Context) error {
type Record struct {
Payload *proto.NotificationRequest `json:"payload"`
}
type RequestBody struct {
Record *Record `json:"record"`
}
body := RequestBody{}
if err := c.Bind(&body); err != nil {
return c.JSON(http.StatusBadRequest, err)
}
if body.Record == nil {
return c.JSON(http.StatusBadRequest, "record is required")
}
if body.Record.Payload == nil {
return c.JSON(http.StatusBadRequest, "payload is required")
}
logrus.Debugln("request body:", body)
resp, err := srv.client.Send(c.Request().Context(), body.Record.Payload)
if err != nil {
logrus.Errorln("failed to send notification:", err)
return c.JSON(http.StatusInternalServerError, err)
}
return c.JSON(http.StatusOK, resp)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment