From 815c362badbb142d1b18bd6435457dbb21a23c7f Mon Sep 17 00:00:00 2001 From: juzeon Date: Sat, 27 Jan 2024 17:25:43 +0800 Subject: [PATCH] add ipc server for browser extension --- ipc.go | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ main.go | 2 ++ 2 files changed, 55 insertions(+) create mode 100644 ipc.go diff --git a/ipc.go b/ipc.go new file mode 100644 index 0000000..e3b823d --- /dev/null +++ b/ipc.go @@ -0,0 +1,53 @@ +package main + +import ( + "encoding/json" + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + "log/slog" + "net/http" + "os" + "sydneyqt/util" +) + +type IPCServer struct { + mux *chi.Mux + settings *Settings +} + +func NewIPCServer(settings *Settings) *IPCServer { + mux := chi.NewRouter() + server := &IPCServer{ + mux: mux, + settings: settings, + } + server.registerRouters(mux) + return server +} +func (o *IPCServer) registerRouters(mux *chi.Mux) { + mux.Use(middleware.Logger) + mux.Use(middleware.Recoverer) + mux.Post("/cookies", func(writer http.ResponseWriter, request *http.Request) { + var cookies []util.FileCookie + err := json.NewDecoder(request.Body).Decode(&cookies) + if err != nil { + writer.WriteHeader(400) + slog.Error("Could not decode request", "err", err) + return + } + v, _ := json.MarshalIndent(&cookies, "", " ") + err = os.WriteFile("cookies.json", v, 0644) + if err != nil { + writer.WriteHeader(500) + slog.Error("Could write cookies.json", "err", err) + return + } + writer.WriteHeader(200) + }) +} +func (o *IPCServer) Serve() { + err := http.ListenAndServe(":61989", o.mux) + if err != nil { + util.GracefulPanic(err) + } +} diff --git a/main.go b/main.go index 9575421..d11c655 100644 --- a/main.go +++ b/main.go @@ -13,6 +13,8 @@ var assets embed.FS func main() { // Create an instance of the app structure settings := NewSettings() + ipcServer := NewIPCServer(settings) + go ipcServer.Serve() app := NewApp(settings) // Create application with options