From 662e3d5547b8873a11df013e2d8ce35f0b175dfa Mon Sep 17 00:00:00 2001 From: Devan Date: Sun, 21 Jan 2024 21:03:11 -0600 Subject: [PATCH 01/12] feat: refactor to use interfaces --- .idea/.gitignore | 8 +++++ .idea/modules.xml | 8 +++++ .idea/sublinks-federation.iml | 9 +++++ .idea/vcs.xml | 6 ++++ cmd/federation.go | 15 +++++--- internal/http/{routes => }/activity.go | 20 +++++------ internal/http/{routes => }/apub.go | 14 ++++---- internal/http/middleware.go | 33 +++++++++++++++++ internal/http/{routes => }/post.go | 14 ++++---- internal/http/routes/routes.go | 48 ------------------------- internal/http/server.go | 35 ++++++++++++++---- internal/http/{routes => }/user.go | 16 ++++----- internal/log/log.go | 50 ++++++++++++++++++-------- 13 files changed, 166 insertions(+), 110 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 .idea/modules.xml create mode 100644 .idea/sublinks-federation.iml create mode 100644 .idea/vcs.xml rename internal/http/{routes => }/activity.go (70%) rename internal/http/{routes => }/apub.go (67%) create mode 100644 internal/http/middleware.go rename internal/http/{routes => }/post.go (69%) delete mode 100644 internal/http/routes/routes.go rename internal/http/{routes => }/user.go (63%) diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..bd26bfb --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/sublinks-federation.iml b/.idea/sublinks-federation.iml new file mode 100644 index 0000000..5e764c4 --- /dev/null +++ b/.idea/sublinks-federation.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/cmd/federation.go b/cmd/federation.go index 46b924c..20d9b63 100644 --- a/cmd/federation.go +++ b/cmd/federation.go @@ -11,17 +11,24 @@ import ( ) func main() { + // bootstrap logger + logger := log.NewLogger() + // Load connection string from .env file err := godotenv.Load() if err != nil { - log.Warn(fmt.Sprintf("failed to load env, %v", err)) + logger.Warn(fmt.Sprintf("failed to load env, %v", err)) } + conn, err := db.Connect() if err != nil { - log.Fatal("failed connecting to db", err) + logger.Fatal("failed connecting to db", err) } - defer conn.Close() db.RunMigrations(conn) - http.RunServer() + + defer conn.Close() + s := http.NewServer(logger) + s.RunServer() + os.Exit(0) } diff --git a/internal/http/routes/activity.go b/internal/http/activity.go similarity index 70% rename from internal/http/routes/activity.go rename to internal/http/activity.go index 4edc242..c73880e 100644 --- a/internal/http/routes/activity.go +++ b/internal/http/activity.go @@ -1,14 +1,12 @@ -package routes +package http import ( "context" "encoding/json" + "fmt" "net/http" "sublinks/sublinks-federation/internal/activitypub" "sublinks/sublinks-federation/internal/lemmy" - "sublinks/sublinks-federation/internal/log" - - "fmt" "golang.org/x/text/cases" "golang.org/x/text/language" @@ -16,18 +14,18 @@ import ( "github.com/gorilla/mux" ) -func SetupActivityRoutes(r *mux.Router) { - r.HandleFunc("/activities/{action}/{id}", getActivityHandler).Methods("GET") +func (s Server) SetupActivityRoutes() { + s.HandleFunc("/activities/{action}/{id}", s.getActivityHandler).Methods("GET") } -func getActivityHandler(w http.ResponseWriter, r *http.Request) { +func (s Server) getActivityHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) var content []byte switch vars["action"] { case "create": - obj, err := GetPostActivityObject(vars["id"]) + obj, err := s.GetPostActivityObject(vars["id"]) if err != nil { - log.Error("Error reading object", err) + s.Error("Error reading object", err) w.WriteHeader(http.StatusInternalServerError) return } @@ -54,12 +52,12 @@ func getActivityHandler(w http.ResponseWriter, r *http.Request) { w.Write(content) } -func GetPostActivityObject(id string) (*activitypub.Post, error) { +func (s Server) GetPostActivityObject(id string) (*activitypub.Post, error) { ctx := context.Background() c := lemmy.GetLemmyClient(ctx) post, err := c.GetPost(ctx, id) if err != nil { - log.Error("Error reading post", err) + s.Error("Error reading post", err) return nil, err } return activitypub.ConvertPostToApub(post), nil diff --git a/internal/http/routes/apub.go b/internal/http/apub.go similarity index 67% rename from internal/http/routes/apub.go rename to internal/http/apub.go index b1d3016..f1398b0 100644 --- a/internal/http/routes/apub.go +++ b/internal/http/apub.go @@ -1,16 +1,14 @@ -package routes +package http import ( "net/http" - - "github.com/gorilla/mux" ) -func SetupApubRoutes(r *mux.Router) { - r.HandleFunc("/users/{user}/inbox", getInboxHandler).Methods("GET") - r.HandleFunc("/users/{user}/inbox", postInboxHandler).Methods("POST") - r.HandleFunc("/users/{user}/outbox", getOutboxHandler).Methods("GET") - r.HandleFunc("/users/{user}/outbox", postOutboxHandler).Methods("POST") +func (s Server) SetupApubRoutes() { + s.HandleFunc("/users/{user}/inbox", getInboxHandler).Methods("GET") + s.HandleFunc("/users/{user}/inbox", postInboxHandler).Methods("POST") + s.HandleFunc("/users/{user}/outbox", getOutboxHandler).Methods("GET") + s.HandleFunc("/users/{user}/outbox", postOutboxHandler).Methods("POST") } func getInboxHandler(w http.ResponseWriter, r *http.Request) { diff --git a/internal/http/middleware.go b/internal/http/middleware.go new file mode 100644 index 0000000..c54ea78 --- /dev/null +++ b/internal/http/middleware.go @@ -0,0 +1,33 @@ +package http + +import ( + "encoding/json" + "net/http" +) + +func (s Server) logMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.Logger.Request("", r) + next.ServeHTTP(w, r) + }) +} + +type RequestError struct { + Msg string `json:"message"` +} + +func (s Server) notFound(w http.ResponseWriter, r *http.Request) { + s.Logger.Request("404 Not Found", r) + w.WriteHeader(http.StatusNotFound) + w.Header().Add("content-type", "application/activity+json") + content, _ := json.Marshal(RequestError{Msg: "not found"}) + w.Write(content) +} + +func (s Server) notAllowedMethod(w http.ResponseWriter, r *http.Request) { + s.Logger.Request("405 Method Not Allowed", r) + w.WriteHeader(http.StatusNotFound) + w.Header().Add("content-type", "application/activity+json") + content, _ := json.Marshal(RequestError{Msg: "method not allowed"}) + w.Write(content) +} diff --git a/internal/http/routes/post.go b/internal/http/post.go similarity index 69% rename from internal/http/routes/post.go rename to internal/http/post.go index 635cc25..d1ccbc6 100644 --- a/internal/http/routes/post.go +++ b/internal/http/post.go @@ -1,27 +1,25 @@ -package routes +package http import ( "context" "encoding/json" + "github.com/gorilla/mux" "net/http" "sublinks/sublinks-federation/internal/activitypub" "sublinks/sublinks-federation/internal/lemmy" - "sublinks/sublinks-federation/internal/log" - - "github.com/gorilla/mux" ) -func SetupPostRoutes(r *mux.Router) { - r.HandleFunc("/post/{postId}", getPostHandler).Methods("GET") +func (s Server) SetupPostRoutes() { + s.HandleFunc("/post/{postId}", s.getPostHandler).Methods("GET") } -func getPostHandler(w http.ResponseWriter, r *http.Request) { +func (s Server) getPostHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) ctx := context.Background() c := lemmy.GetLemmyClient(ctx) post, err := c.GetPost(ctx, vars["postId"]) if err != nil { - log.Error("Error reading post", err) + s.Error("Error reading post", err) return } postLd := activitypub.ConvertPostToApub(post) diff --git a/internal/http/routes/routes.go b/internal/http/routes/routes.go deleted file mode 100644 index a82c5e1..0000000 --- a/internal/http/routes/routes.go +++ /dev/null @@ -1,48 +0,0 @@ -package routes - -import ( - "encoding/json" - "net/http" - "sublinks/sublinks-federation/internal/log" - - "github.com/gorilla/mux" -) - -func SetupRoutes() *mux.Router { - r := mux.NewRouter() - SetupUserRoutes(r) - SetupPostRoutes(r) - SetupApubRoutes(r) - SetupActivityRoutes(r) - r.NotFoundHandler = http.HandlerFunc(notFound) - r.MethodNotAllowedHandler = http.HandlerFunc(notAllowedMethod) - r.Use(logMiddleware) - return r -} - -func logMiddleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - log.Request("", r) - next.ServeHTTP(w, r) - }) -} - -type RequestError struct { - Msg string `json:"message"` -} - -func notFound(w http.ResponseWriter, r *http.Request) { - log.Request("404 Not Found", r) - w.WriteHeader(http.StatusNotFound) - w.Header().Add("content-type", "application/activity+json") - content, _ := json.Marshal(RequestError{Msg: "not found"}) - w.Write(content) -} - -func notAllowedMethod(w http.ResponseWriter, r *http.Request) { - log.Request("405 Method Not Allowed", r) - w.WriteHeader(http.StatusNotFound) - w.Header().Add("content-type", "application/activity+json") - content, _ := json.Marshal(RequestError{Msg: "method not allowed"}) - w.Write(content) -} diff --git a/internal/http/server.go b/internal/http/server.go index 2e76ce5..49f9486 100644 --- a/internal/http/server.go +++ b/internal/http/server.go @@ -3,20 +3,40 @@ package http import ( "context" "flag" + "github.com/gorilla/mux" "net/http" "os" "os/signal" - "sublinks/sublinks-federation/internal/http/routes" "sublinks/sublinks-federation/internal/log" "time" ) -func RunServer() { +type Server struct { + *mux.Router + log.Logger +} + +func NewServer(logger log.Logger) *Server { + r := mux.NewRouter() + + return &Server{ + Router: r, + Logger: logger, + } +} + +func (s Server) RunServer() { var wait time.Duration flag.DurationVar(&wait, "graceful-timeout", time.Second*15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m") flag.Parse() - r := routes.SetupRoutes() + s.SetupUserRoutes() + s.SetupPostRoutes() + s.SetupApubRoutes() + s.SetupActivityRoutes() + s.NotFoundHandler = http.HandlerFunc(s.notFound) + s.MethodNotAllowedHandler = http.HandlerFunc(s.notAllowedMethod) + s.Use(s.logMiddleware) srv := &http.Server{ Addr: "0.0.0.0:8080", @@ -24,14 +44,15 @@ func RunServer() { WriteTimeout: time.Second * 15, ReadTimeout: time.Second * 15, IdleTimeout: time.Second * 60, - Handler: r, // Pass our instance of gorilla/mux in. + // pass embed of Server for *mux + Handler: s, } // Run our server in a goroutine so that it doesn't block. go func() { - log.Info("Starting server") + s.Info("Starting server") if err := srv.ListenAndServe(); err != nil { - log.Error("Error starting server", err) + s.Error("Error starting server", err) } }() @@ -52,5 +73,5 @@ func RunServer() { // Optionally, you could run srv.Shutdown in a goroutine and block on // <-ctx.Done() if your application should wait for other services // to finalize based on context cancellation. - log.Info("shutting down") + s.Info("shutting down") } diff --git a/internal/http/routes/user.go b/internal/http/user.go similarity index 63% rename from internal/http/routes/user.go rename to internal/http/user.go index 10abdda..3f3ae49 100644 --- a/internal/http/routes/user.go +++ b/internal/http/user.go @@ -1,29 +1,27 @@ -package routes +package http import ( "context" "encoding/json" "fmt" + "github.com/gorilla/mux" "net/http" "sublinks/sublinks-federation/internal/activitypub" "sublinks/sublinks-federation/internal/lemmy" - "sublinks/sublinks-federation/internal/log" - - "github.com/gorilla/mux" ) -func SetupUserRoutes(r *mux.Router) { - r.HandleFunc("/u/{user}", getUserInfoHandler).Methods("GET") +func (s Server) SetupUserRoutes() { + s.HandleFunc("/u/{user}", s.getUserInfoHandler).Methods("GET") } -func getUserInfoHandler(w http.ResponseWriter, r *http.Request) { +func (s Server) getUserInfoHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) ctx := context.Background() c := lemmy.GetLemmyClient(ctx) - log.Info(fmt.Sprintf("Looking up user %s", vars["user"])) + s.Info(fmt.Sprintf("Looking up user %s", vars["user"])) user, err := c.GetUser(ctx, vars["user"]) if err != nil { - log.Error("Error reading user", err) + s.Error("Error reading user", err) return } diff --git a/internal/log/log.go b/internal/log/log.go index ea5fc61..e516c39 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -2,48 +2,68 @@ package log import ( "encoding/json" + "github.com/rs/zerolog" "io" "net/http" "github.com/rs/zerolog/log" ) -func init() { +type Logger interface { + Info(msg string) + Debug(msg string) + Error(msg string, err error) + Fatal(msg string, err error) + Warn(msg string) + Request(msg string, r *http.Request) +} + +type Log struct { + *zerolog.Logger +} + +func NewLogger() *Log { log.Debug().Msg("Logger started") + return &Log{} } -func Info(msg string) { - log.Info().Msg(msg) +func (l Log) Info(msg string) { + l.Logger.Info().Msg(msg) } -func Debug(msg string) { - log.Debug().Msg(msg) +func (l Log) Debug(msg string) { + l.Logger.Debug().Msg(msg) } -func Error(msg string, err error) { - log.Error().Err(err).Msg(msg) +func (l Log) Error(msg string, err error) { + l.Logger.Error().Err(err).Msg(msg) } -func Fatal(msg string, err error) { - log.Fatal().Err(err).Msg(msg) +func (l Log) Fatal(msg string, err error) { + l.Logger.Fatal().Err(err).Msg(msg) } -func Warn(msg string) { - log.Warn().Msg(msg) +func (l Log) Warn(msg string) { + l.Logger.Warn().Msg(msg) } -func Request(msg string, r *http.Request) { - defer r.Body.Close() +func (l Log) Request(msg string, r *http.Request) { + defer func(Body io.ReadCloser) { + err := Body.Close() + if err != nil { + panic("error closing http io reader") + } + }(r.Body) var body interface{} rawbody, err := io.ReadAll(r.Body) if err != nil { - Error("Error reading request body", err) + l.Error("Error reading request body", err) body = nil } if r.ContentLength > 0 && r.Header.Get("Content-Type") == "application/json" { err = json.Unmarshal(rawbody, &body) if err != nil { - Error("Error parsing request body into json", err) + l.Error("Error parsing request body into json", err) body = nil } } else { From 9353f43fb0280ab3d67ccfee162cc782ab1ffe20 Mon Sep 17 00:00:00 2001 From: Devan Date: Mon, 22 Jan 2024 07:37:50 -0600 Subject: [PATCH 02/12] feat: update logger --- internal/db/migrate.go | 11 ++++++----- internal/log/log.go | 15 ++++++--------- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/internal/db/migrate.go b/internal/db/migrate.go index 2c3ad75..342628f 100644 --- a/internal/db/migrate.go +++ b/internal/db/migrate.go @@ -17,18 +17,19 @@ import ( var migrations embed.FS func RunMigrations(db *sql.DB) { - log.Debug("Running migrations...") + logger := log.NewLogger() + logger.Debug("Running migrations...") driver, err := mysql.WithInstance(db, &mysql.Config{}) if err != nil { - log.Fatal("Error getting MySQL driver", err) + logger.Fatal("Error getting MySQL driver", err) } source, _ := iofs.New(migrations, "migrations") m, err := migrate.NewWithInstance("iofs", source, "mysql", driver) if err != nil { - log.Fatal("Error connecting to database", err) + logger.Fatal("Error connecting to database", err) } if err := m.Up(); err != nil && fmt.Sprintf("%s", err) != "no change" { - log.Fatal("Error running migrations", err) + logger.Fatal("Error running migrations", err) } - log.Debug("Done!") + logger.Debug("Done!") } diff --git a/internal/log/log.go b/internal/log/log.go index e516c39..bb24999 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -2,7 +2,6 @@ package log import ( "encoding/json" - "github.com/rs/zerolog" "io" "net/http" @@ -18,9 +17,7 @@ type Logger interface { Request(msg string, r *http.Request) } -type Log struct { - *zerolog.Logger -} +type Log struct{} func NewLogger() *Log { log.Debug().Msg("Logger started") @@ -28,23 +25,23 @@ func NewLogger() *Log { } func (l Log) Info(msg string) { - l.Logger.Info().Msg(msg) + log.Info().Msg(msg) } func (l Log) Debug(msg string) { - l.Logger.Debug().Msg(msg) + log.Debug().Msg(msg) } func (l Log) Error(msg string, err error) { - l.Logger.Error().Err(err).Msg(msg) + log.Error().Err(err).Msg(msg) } func (l Log) Fatal(msg string, err error) { - l.Logger.Fatal().Err(err).Msg(msg) + log.Fatal().Err(err).Msg(msg) } func (l Log) Warn(msg string) { - l.Logger.Warn().Msg(msg) + log.Warn().Msg(msg) } func (l Log) Request(msg string, r *http.Request) { From 9d52b3f251ab4db8677c633ee6de75a119c5c654 Mon Sep 17 00:00:00 2001 From: Devan Date: Mon, 22 Jan 2024 07:41:26 -0600 Subject: [PATCH 03/12] rm .idea --- .idea/.gitignore | 8 -------- .idea/modules.xml | 8 -------- .idea/sublinks-federation.iml | 9 --------- .idea/vcs.xml | 6 ------ 4 files changed, 31 deletions(-) delete mode 100644 .idea/.gitignore delete mode 100644 .idea/modules.xml delete mode 100644 .idea/sublinks-federation.iml delete mode 100644 .idea/vcs.xml diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 13566b8..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index bd26bfb..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/sublinks-federation.iml b/.idea/sublinks-federation.iml deleted file mode 100644 index 5e764c4..0000000 --- a/.idea/sublinks-federation.iml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 35eb1dd..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file From 5b2259a0a01786a24884ead6bdd61624b030df41 Mon Sep 17 00:00:00 2001 From: Devan Date: Mon, 22 Jan 2024 10:08:17 -0600 Subject: [PATCH 04/12] touch --- .gitignore | 3 +++ internal/http/middleware.go | 8 ++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 7209c54..ae0914e 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,6 @@ # Go workspace file go.work + +# jetbrains editor +.idea \ No newline at end of file diff --git a/internal/http/middleware.go b/internal/http/middleware.go index c54ea78..386deb9 100644 --- a/internal/http/middleware.go +++ b/internal/http/middleware.go @@ -5,6 +5,10 @@ import ( "net/http" ) +type RequestError struct { + Msg string `json:"message"` +} + func (s Server) logMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s.Logger.Request("", r) @@ -12,10 +16,6 @@ func (s Server) logMiddleware(next http.Handler) http.Handler { }) } -type RequestError struct { - Msg string `json:"message"` -} - func (s Server) notFound(w http.ResponseWriter, r *http.Request) { s.Logger.Request("404 Not Found", r) w.WriteHeader(http.StatusNotFound) From 64bee7bd67ab129db62b671bf9b970daaba0f62e Mon Sep 17 00:00:00 2001 From: Devan Date: Tue, 23 Jan 2024 06:41:14 -0600 Subject: [PATCH 05/12] update logger and server --- cmd/federation.go | 2 +- internal/http/activity.go | 6 +++--- internal/http/apub.go | 16 ++++++++-------- internal/http/post.go | 4 ++-- internal/http/server.go | 6 +++--- internal/http/user.go | 6 +++--- internal/log/log.go | 37 ++++++++++++++++++++----------------- 7 files changed, 40 insertions(+), 37 deletions(-) diff --git a/cmd/federation.go b/cmd/federation.go index 20d9b63..b6f511c 100644 --- a/cmd/federation.go +++ b/cmd/federation.go @@ -21,12 +21,12 @@ func main() { } conn, err := db.Connect() + defer conn.Close() if err != nil { logger.Fatal("failed connecting to db", err) } db.RunMigrations(conn) - defer conn.Close() s := http.NewServer(logger) s.RunServer() diff --git a/internal/http/activity.go b/internal/http/activity.go index c73880e..7b2f2eb 100644 --- a/internal/http/activity.go +++ b/internal/http/activity.go @@ -15,7 +15,7 @@ import ( ) func (s Server) SetupActivityRoutes() { - s.HandleFunc("/activities/{action}/{id}", s.getActivityHandler).Methods("GET") + s.Router.HandleFunc("/activities/{action}/{id}", s.getActivityHandler).Methods("GET") } func (s Server) getActivityHandler(w http.ResponseWriter, r *http.Request) { @@ -25,7 +25,7 @@ func (s Server) getActivityHandler(w http.ResponseWriter, r *http.Request) { case "create": obj, err := s.GetPostActivityObject(vars["id"]) if err != nil { - s.Error("Error reading object", err) + s.Logger.Error("Error reading object", err) w.WriteHeader(http.StatusInternalServerError) return } @@ -57,7 +57,7 @@ func (s Server) GetPostActivityObject(id string) (*activitypub.Post, error) { c := lemmy.GetLemmyClient(ctx) post, err := c.GetPost(ctx, id) if err != nil { - s.Error("Error reading post", err) + s.Logger.Error("Error reading post", err) return nil, err } return activitypub.ConvertPostToApub(post), nil diff --git a/internal/http/apub.go b/internal/http/apub.go index f1398b0..e1ec881 100644 --- a/internal/http/apub.go +++ b/internal/http/apub.go @@ -5,28 +5,28 @@ import ( ) func (s Server) SetupApubRoutes() { - s.HandleFunc("/users/{user}/inbox", getInboxHandler).Methods("GET") - s.HandleFunc("/users/{user}/inbox", postInboxHandler).Methods("POST") - s.HandleFunc("/users/{user}/outbox", getOutboxHandler).Methods("GET") - s.HandleFunc("/users/{user}/outbox", postOutboxHandler).Methods("POST") + s.Router.HandleFunc("/users/{user}/inbox", s.getInboxHandler).Methods("GET") + s.Router.HandleFunc("/users/{user}/inbox", s.postInboxHandler).Methods("POST") + s.Router.HandleFunc("/users/{user}/outbox", s.getOutboxHandler).Methods("GET") + s.Router.HandleFunc("/users/{user}/outbox", s.postOutboxHandler).Methods("POST") } -func getInboxHandler(w http.ResponseWriter, r *http.Request) { +func (s Server) getInboxHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/activity+json") } -func postInboxHandler(w http.ResponseWriter, r *http.Request) { +func (s Server) postInboxHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/activity+json") } -func getOutboxHandler(w http.ResponseWriter, r *http.Request) { +func (s Server) getOutboxHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/activity+json") } -func postOutboxHandler(w http.ResponseWriter, r *http.Request) { +func (s Server) postOutboxHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/activity+json") } diff --git a/internal/http/post.go b/internal/http/post.go index d1ccbc6..8c33cb7 100644 --- a/internal/http/post.go +++ b/internal/http/post.go @@ -10,7 +10,7 @@ import ( ) func (s Server) SetupPostRoutes() { - s.HandleFunc("/post/{postId}", s.getPostHandler).Methods("GET") + s.Router.HandleFunc("/post/{postId}", s.getPostHandler).Methods("GET") } func (s Server) getPostHandler(w http.ResponseWriter, r *http.Request) { @@ -19,7 +19,7 @@ func (s Server) getPostHandler(w http.ResponseWriter, r *http.Request) { c := lemmy.GetLemmyClient(ctx) post, err := c.GetPost(ctx, vars["postId"]) if err != nil { - s.Error("Error reading post", err) + s.Logger.Error("Error reading post", err) return } postLd := activitypub.ConvertPostToApub(post) diff --git a/internal/http/server.go b/internal/http/server.go index 49f9486..a0b9051 100644 --- a/internal/http/server.go +++ b/internal/http/server.go @@ -50,9 +50,9 @@ func (s Server) RunServer() { // Run our server in a goroutine so that it doesn't block. go func() { - s.Info("Starting server") + s.Logger.Info("Starting server") if err := srv.ListenAndServe(); err != nil { - s.Error("Error starting server", err) + s.Logger.Error("Error starting server", err) } }() @@ -73,5 +73,5 @@ func (s Server) RunServer() { // Optionally, you could run srv.Shutdown in a goroutine and block on // <-ctx.Done() if your application should wait for other services // to finalize based on context cancellation. - s.Info("shutting down") + s.Logger.Info("shutting down") } diff --git a/internal/http/user.go b/internal/http/user.go index 3f3ae49..92358d8 100644 --- a/internal/http/user.go +++ b/internal/http/user.go @@ -11,17 +11,17 @@ import ( ) func (s Server) SetupUserRoutes() { - s.HandleFunc("/u/{user}", s.getUserInfoHandler).Methods("GET") + s.Router.HandleFunc("/u/{user}", s.getUserInfoHandler).Methods("GET") } func (s Server) getUserInfoHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) ctx := context.Background() c := lemmy.GetLemmyClient(ctx) - s.Info(fmt.Sprintf("Looking up user %s", vars["user"])) + s.Logger.Info(fmt.Sprintf("Looking up user %s", vars["user"])) user, err := c.GetUser(ctx, vars["user"]) if err != nil { - s.Error("Error reading user", err) + s.Logger.Error("Error reading user", err) return } diff --git a/internal/log/log.go b/internal/log/log.go index bb24999..1bc9085 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -2,10 +2,10 @@ package log import ( "encoding/json" + "github.com/rs/zerolog" "io" "net/http" - - "github.com/rs/zerolog/log" + "os" ) type Logger interface { @@ -17,34 +17,37 @@ type Logger interface { Request(msg string, r *http.Request) } -type Log struct{} +type Log struct { + *zerolog.Logger +} func NewLogger() *Log { - log.Debug().Msg("Logger started") - return &Log{} + logger := zerolog.New(os.Stdout) + logger.Debug().Msg("Logger started") + return &Log{&logger} } -func (l Log) Info(msg string) { - log.Info().Msg(msg) +func (l *Log) Info(msg string) { + l.Logger.Info().Msg(msg) } -func (l Log) Debug(msg string) { - log.Debug().Msg(msg) +func (l *Log) Debug(msg string) { + l.Logger.Debug().Msg(msg) } -func (l Log) Error(msg string, err error) { - log.Error().Err(err).Msg(msg) +func (l *Log) Error(msg string, err error) { + l.Logger.Error().Err(err).Msg(msg) } -func (l Log) Fatal(msg string, err error) { - log.Fatal().Err(err).Msg(msg) +func (l *Log) Fatal(msg string, err error) { + l.Logger.Fatal().Err(err).Msg(msg) } -func (l Log) Warn(msg string) { - log.Warn().Msg(msg) +func (l *Log) Warn(msg string) { + l.Logger.Warn().Msg(msg) } -func (l Log) Request(msg string, r *http.Request) { +func (l *Log) Request(msg string, r *http.Request) { defer func(Body io.ReadCloser) { err := Body.Close() if err != nil { @@ -66,7 +69,7 @@ func (l Log) Request(msg string, r *http.Request) { } else { body = rawbody } - log.Debug(). + l.Logger.Debug(). Str("method", r.Method). Str("url", r.URL.String()). Str("user-agent", r.UserAgent()). From 9978aff490c1bfd7ef3a5ba14d282cb3842e2f3d Mon Sep 17 00:00:00 2001 From: Devan Date: Tue, 23 Jan 2024 06:45:07 -0600 Subject: [PATCH 06/12] update logger and server --- internal/log/log.go | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/internal/log/log.go b/internal/log/log.go index 1bc9085..d01ae58 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -27,27 +27,27 @@ func NewLogger() *Log { return &Log{&logger} } -func (l *Log) Info(msg string) { - l.Logger.Info().Msg(msg) +func (logger *Log) Info(msg string) { + logger.Logger.Info().Msg(msg) } -func (l *Log) Debug(msg string) { - l.Logger.Debug().Msg(msg) +func (logger *Log) Debug(msg string) { + logger.Logger.Debug().Msg(msg) } -func (l *Log) Error(msg string, err error) { - l.Logger.Error().Err(err).Msg(msg) +func (logger *Log) Error(msg string, err error) { + logger.Logger.Error().Err(err).Msg(msg) } -func (l *Log) Fatal(msg string, err error) { - l.Logger.Fatal().Err(err).Msg(msg) +func (logger *Log) Fatal(msg string, err error) { + logger.Logger.Fatal().Err(err).Msg(msg) } -func (l *Log) Warn(msg string) { - l.Logger.Warn().Msg(msg) +func (logger *Log) Warn(msg string) { + logger.Logger.Warn().Msg(msg) } -func (l *Log) Request(msg string, r *http.Request) { +func (logger *Log) Request(msg string, r *http.Request) { defer func(Body io.ReadCloser) { err := Body.Close() if err != nil { @@ -57,19 +57,19 @@ func (l *Log) Request(msg string, r *http.Request) { var body interface{} rawbody, err := io.ReadAll(r.Body) if err != nil { - l.Error("Error reading request body", err) + logger.Error("Error reading request body", err) body = nil } if r.ContentLength > 0 && r.Header.Get("Content-Type") == "application/json" { err = json.Unmarshal(rawbody, &body) if err != nil { - l.Error("Error parsing request body into json", err) + logger.Error("Error parsing request body into json", err) body = nil } } else { body = rawbody } - l.Logger.Debug(). + logger.Logger.Debug(). Str("method", r.Method). Str("url", r.URL.String()). Str("user-agent", r.UserAgent()). From 8f85d1d25c5e3620cabe51a174a155b5e275d65b Mon Sep 17 00:00:00 2001 From: Devan Date: Wed, 24 Jan 2024 10:49:32 -0600 Subject: [PATCH 07/12] feat: update variable naming --- internal/http/activity.go | 16 ++++++++-------- internal/http/apub.go | 18 +++++++++--------- internal/http/middleware.go | 12 ++++++------ internal/http/post.go | 8 ++++---- internal/http/server.go | 24 ++++++++++++------------ internal/http/user.go | 10 +++++----- 6 files changed, 44 insertions(+), 44 deletions(-) diff --git a/internal/http/activity.go b/internal/http/activity.go index 7b2f2eb..c047bdf 100644 --- a/internal/http/activity.go +++ b/internal/http/activity.go @@ -14,18 +14,18 @@ import ( "github.com/gorilla/mux" ) -func (s Server) SetupActivityRoutes() { - s.Router.HandleFunc("/activities/{action}/{id}", s.getActivityHandler).Methods("GET") +func (server Server) SetupActivityRoutes() { + server.Router.HandleFunc("/activities/{action}/{id}", server.getActivityHandler).Methods("GET") } -func (s Server) getActivityHandler(w http.ResponseWriter, r *http.Request) { +func (server Server) getActivityHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) var content []byte switch vars["action"] { case "create": - obj, err := s.GetPostActivityObject(vars["id"]) + obj, err := server.GetPostActivityObject(vars["id"]) if err != nil { - s.Logger.Error("Error reading object", err) + server.Logger.Error("Error reading object", err) w.WriteHeader(http.StatusInternalServerError) return } @@ -42,7 +42,7 @@ func (s Server) getActivityHandler(w http.ResponseWriter, r *http.Request) { break default: - error.Error(fmt.Errorf("action %s not found", vars["action"])) + error.Error(fmt.Errorf("action %server not found", vars["action"])) w.WriteHeader(http.StatusNotFound) return } @@ -52,12 +52,12 @@ func (s Server) getActivityHandler(w http.ResponseWriter, r *http.Request) { w.Write(content) } -func (s Server) GetPostActivityObject(id string) (*activitypub.Post, error) { +func (server Server) GetPostActivityObject(id string) (*activitypub.Post, error) { ctx := context.Background() c := lemmy.GetLemmyClient(ctx) post, err := c.GetPost(ctx, id) if err != nil { - s.Logger.Error("Error reading post", err) + server.Logger.Error("Error reading post", err) return nil, err } return activitypub.ConvertPostToApub(post), nil diff --git a/internal/http/apub.go b/internal/http/apub.go index e1ec881..83ab759 100644 --- a/internal/http/apub.go +++ b/internal/http/apub.go @@ -4,29 +4,29 @@ import ( "net/http" ) -func (s Server) SetupApubRoutes() { - s.Router.HandleFunc("/users/{user}/inbox", s.getInboxHandler).Methods("GET") - s.Router.HandleFunc("/users/{user}/inbox", s.postInboxHandler).Methods("POST") - s.Router.HandleFunc("/users/{user}/outbox", s.getOutboxHandler).Methods("GET") - s.Router.HandleFunc("/users/{user}/outbox", s.postOutboxHandler).Methods("POST") +func (server Server) SetupApubRoutes() { + server.Router.HandleFunc("/users/{user}/inbox", server.getInboxHandler).Methods("GET") + server.Router.HandleFunc("/users/{user}/inbox", server.postInboxHandler).Methods("POST") + server.Router.HandleFunc("/users/{user}/outbox", server.getOutboxHandler).Methods("GET") + server.Router.HandleFunc("/users/{user}/outbox", server.postOutboxHandler).Methods("POST") } -func (s Server) getInboxHandler(w http.ResponseWriter, r *http.Request) { +func (server Server) getInboxHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/activity+json") } -func (s Server) postInboxHandler(w http.ResponseWriter, r *http.Request) { +func (server Server) postInboxHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/activity+json") } -func (s Server) getOutboxHandler(w http.ResponseWriter, r *http.Request) { +func (server Server) getOutboxHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/activity+json") } -func (s Server) postOutboxHandler(w http.ResponseWriter, r *http.Request) { +func (server Server) postOutboxHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/activity+json") } diff --git a/internal/http/middleware.go b/internal/http/middleware.go index 386deb9..27aa1a7 100644 --- a/internal/http/middleware.go +++ b/internal/http/middleware.go @@ -9,23 +9,23 @@ type RequestError struct { Msg string `json:"message"` } -func (s Server) logMiddleware(next http.Handler) http.Handler { +func (server Server) logMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - s.Logger.Request("", r) + server.Logger.Request("", r) next.ServeHTTP(w, r) }) } -func (s Server) notFound(w http.ResponseWriter, r *http.Request) { - s.Logger.Request("404 Not Found", r) +func (server Server) notFound(w http.ResponseWriter, r *http.Request) { + server.Logger.Request("404 Not Found", r) w.WriteHeader(http.StatusNotFound) w.Header().Add("content-type", "application/activity+json") content, _ := json.Marshal(RequestError{Msg: "not found"}) w.Write(content) } -func (s Server) notAllowedMethod(w http.ResponseWriter, r *http.Request) { - s.Logger.Request("405 Method Not Allowed", r) +func (server Server) notAllowedMethod(w http.ResponseWriter, r *http.Request) { + server.Logger.Request("405 Method Not Allowed", r) w.WriteHeader(http.StatusNotFound) w.Header().Add("content-type", "application/activity+json") content, _ := json.Marshal(RequestError{Msg: "method not allowed"}) diff --git a/internal/http/post.go b/internal/http/post.go index 8c33cb7..bb6486f 100644 --- a/internal/http/post.go +++ b/internal/http/post.go @@ -9,17 +9,17 @@ import ( "sublinks/sublinks-federation/internal/lemmy" ) -func (s Server) SetupPostRoutes() { - s.Router.HandleFunc("/post/{postId}", s.getPostHandler).Methods("GET") +func (server Server) SetupPostRoutes() { + server.Router.HandleFunc("/post/{postId}", server.getPostHandler).Methods("GET") } -func (s Server) getPostHandler(w http.ResponseWriter, r *http.Request) { +func (server Server) getPostHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) ctx := context.Background() c := lemmy.GetLemmyClient(ctx) post, err := c.GetPost(ctx, vars["postId"]) if err != nil { - s.Logger.Error("Error reading post", err) + server.Logger.Error("Error reading post", err) return } postLd := activitypub.ConvertPostToApub(post) diff --git a/internal/http/server.go b/internal/http/server.go index a0b9051..1410fb8 100644 --- a/internal/http/server.go +++ b/internal/http/server.go @@ -25,18 +25,18 @@ func NewServer(logger log.Logger) *Server { } } -func (s Server) RunServer() { +func (server Server) RunServer() { var wait time.Duration flag.DurationVar(&wait, "graceful-timeout", time.Second*15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m") flag.Parse() - s.SetupUserRoutes() - s.SetupPostRoutes() - s.SetupApubRoutes() - s.SetupActivityRoutes() - s.NotFoundHandler = http.HandlerFunc(s.notFound) - s.MethodNotAllowedHandler = http.HandlerFunc(s.notAllowedMethod) - s.Use(s.logMiddleware) + server.SetupUserRoutes() + server.SetupPostRoutes() + server.SetupApubRoutes() + server.SetupActivityRoutes() + server.NotFoundHandler = http.HandlerFunc(server.notFound) + server.MethodNotAllowedHandler = http.HandlerFunc(server.notAllowedMethod) + server.Use(server.logMiddleware) srv := &http.Server{ Addr: "0.0.0.0:8080", @@ -45,14 +45,14 @@ func (s Server) RunServer() { ReadTimeout: time.Second * 15, IdleTimeout: time.Second * 60, // pass embed of Server for *mux - Handler: s, + Handler: server, } // Run our server in a goroutine so that it doesn't block. go func() { - s.Logger.Info("Starting server") + server.Logger.Info("Starting server") if err := srv.ListenAndServe(); err != nil { - s.Logger.Error("Error starting server", err) + server.Logger.Error("Error starting server", err) } }() @@ -73,5 +73,5 @@ func (s Server) RunServer() { // Optionally, you could run srv.Shutdown in a goroutine and block on // <-ctx.Done() if your application should wait for other services // to finalize based on context cancellation. - s.Logger.Info("shutting down") + server.Logger.Info("shutting down") } diff --git a/internal/http/user.go b/internal/http/user.go index 92358d8..4b87a35 100644 --- a/internal/http/user.go +++ b/internal/http/user.go @@ -10,18 +10,18 @@ import ( "sublinks/sublinks-federation/internal/lemmy" ) -func (s Server) SetupUserRoutes() { - s.Router.HandleFunc("/u/{user}", s.getUserInfoHandler).Methods("GET") +func (server Server) SetupUserRoutes() { + server.Router.HandleFunc("/u/{user}", server.getUserInfoHandler).Methods("GET") } -func (s Server) getUserInfoHandler(w http.ResponseWriter, r *http.Request) { +func (server Server) getUserInfoHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) ctx := context.Background() c := lemmy.GetLemmyClient(ctx) - s.Logger.Info(fmt.Sprintf("Looking up user %s", vars["user"])) + server.Logger.Info(fmt.Sprintf("Looking up user %server", vars["user"])) user, err := c.GetUser(ctx, vars["user"]) if err != nil { - s.Logger.Error("Error reading user", err) + server.Logger.Error("Error reading user", err) return } From 81feda27027043d1dfd202f1090206affa946bf9 Mon Sep 17 00:00:00 2001 From: Devan Date: Wed, 24 Jan 2024 10:52:01 -0600 Subject: [PATCH 08/12] update --- cmd/federation.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/federation.go b/cmd/federation.go index b6f511c..7aa8d21 100644 --- a/cmd/federation.go +++ b/cmd/federation.go @@ -21,11 +21,11 @@ func main() { } conn, err := db.Connect() - defer conn.Close() if err != nil { logger.Fatal("failed connecting to db", err) } db.RunMigrations(conn) + defer conn.Close() s := http.NewServer(logger) s.RunServer() From 74d44fce09fd0b502dd319ab963a488081ff99c0 Mon Sep 17 00:00:00 2001 From: Devan Date: Wed, 24 Jan 2024 11:34:18 -0600 Subject: [PATCH 09/12] pointer receiver --- internal/http/activity.go | 6 +++--- internal/http/apub.go | 10 +++++----- internal/http/middleware.go | 6 +++--- internal/http/post.go | 4 ++-- internal/http/server.go | 2 +- internal/http/user.go | 4 ++-- 6 files changed, 16 insertions(+), 16 deletions(-) diff --git a/internal/http/activity.go b/internal/http/activity.go index c047bdf..15e2697 100644 --- a/internal/http/activity.go +++ b/internal/http/activity.go @@ -14,11 +14,11 @@ import ( "github.com/gorilla/mux" ) -func (server Server) SetupActivityRoutes() { +func (server *Server) SetupActivityRoutes() { server.Router.HandleFunc("/activities/{action}/{id}", server.getActivityHandler).Methods("GET") } -func (server Server) getActivityHandler(w http.ResponseWriter, r *http.Request) { +func (server *Server) getActivityHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) var content []byte switch vars["action"] { @@ -52,7 +52,7 @@ func (server Server) getActivityHandler(w http.ResponseWriter, r *http.Request) w.Write(content) } -func (server Server) GetPostActivityObject(id string) (*activitypub.Post, error) { +func (server *Server) GetPostActivityObject(id string) (*activitypub.Post, error) { ctx := context.Background() c := lemmy.GetLemmyClient(ctx) post, err := c.GetPost(ctx, id) diff --git a/internal/http/apub.go b/internal/http/apub.go index 83ab759..0f34218 100644 --- a/internal/http/apub.go +++ b/internal/http/apub.go @@ -4,29 +4,29 @@ import ( "net/http" ) -func (server Server) SetupApubRoutes() { +func (server *Server) SetupApubRoutes() { server.Router.HandleFunc("/users/{user}/inbox", server.getInboxHandler).Methods("GET") server.Router.HandleFunc("/users/{user}/inbox", server.postInboxHandler).Methods("POST") server.Router.HandleFunc("/users/{user}/outbox", server.getOutboxHandler).Methods("GET") server.Router.HandleFunc("/users/{user}/outbox", server.postOutboxHandler).Methods("POST") } -func (server Server) getInboxHandler(w http.ResponseWriter, r *http.Request) { +func (server *Server) getInboxHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/activity+json") } -func (server Server) postInboxHandler(w http.ResponseWriter, r *http.Request) { +func (server *Server) postInboxHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/activity+json") } -func (server Server) getOutboxHandler(w http.ResponseWriter, r *http.Request) { +func (server *Server) getOutboxHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/activity+json") } -func (server Server) postOutboxHandler(w http.ResponseWriter, r *http.Request) { +func (server *Server) postOutboxHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/activity+json") } diff --git a/internal/http/middleware.go b/internal/http/middleware.go index 27aa1a7..9bb8e53 100644 --- a/internal/http/middleware.go +++ b/internal/http/middleware.go @@ -9,14 +9,14 @@ type RequestError struct { Msg string `json:"message"` } -func (server Server) logMiddleware(next http.Handler) http.Handler { +func (server *Server) logMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { server.Logger.Request("", r) next.ServeHTTP(w, r) }) } -func (server Server) notFound(w http.ResponseWriter, r *http.Request) { +func (server *Server) notFound(w http.ResponseWriter, r *http.Request) { server.Logger.Request("404 Not Found", r) w.WriteHeader(http.StatusNotFound) w.Header().Add("content-type", "application/activity+json") @@ -24,7 +24,7 @@ func (server Server) notFound(w http.ResponseWriter, r *http.Request) { w.Write(content) } -func (server Server) notAllowedMethod(w http.ResponseWriter, r *http.Request) { +func (server *Server) notAllowedMethod(w http.ResponseWriter, r *http.Request) { server.Logger.Request("405 Method Not Allowed", r) w.WriteHeader(http.StatusNotFound) w.Header().Add("content-type", "application/activity+json") diff --git a/internal/http/post.go b/internal/http/post.go index bb6486f..859b871 100644 --- a/internal/http/post.go +++ b/internal/http/post.go @@ -9,11 +9,11 @@ import ( "sublinks/sublinks-federation/internal/lemmy" ) -func (server Server) SetupPostRoutes() { +func (server *Server) SetupPostRoutes() { server.Router.HandleFunc("/post/{postId}", server.getPostHandler).Methods("GET") } -func (server Server) getPostHandler(w http.ResponseWriter, r *http.Request) { +func (server *Server) getPostHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) ctx := context.Background() c := lemmy.GetLemmyClient(ctx) diff --git a/internal/http/server.go b/internal/http/server.go index 1410fb8..086239d 100644 --- a/internal/http/server.go +++ b/internal/http/server.go @@ -25,7 +25,7 @@ func NewServer(logger log.Logger) *Server { } } -func (server Server) RunServer() { +func (server *Server) RunServer() { var wait time.Duration flag.DurationVar(&wait, "graceful-timeout", time.Second*15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m") flag.Parse() diff --git a/internal/http/user.go b/internal/http/user.go index 4b87a35..85e2f82 100644 --- a/internal/http/user.go +++ b/internal/http/user.go @@ -10,11 +10,11 @@ import ( "sublinks/sublinks-federation/internal/lemmy" ) -func (server Server) SetupUserRoutes() { +func (server *Server) SetupUserRoutes() { server.Router.HandleFunc("/u/{user}", server.getUserInfoHandler).Methods("GET") } -func (server Server) getUserInfoHandler(w http.ResponseWriter, r *http.Request) { +func (server *Server) getUserInfoHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) ctx := context.Background() c := lemmy.GetLemmyClient(ctx) From dd67be0e7a43ec1b5ffb0a38247bfcd32793af20 Mon Sep 17 00:00:00 2001 From: Devan Date: Wed, 24 Jan 2024 12:06:50 -0600 Subject: [PATCH 10/12] make loggers named --- cmd/federation.go | 2 +- internal/db/migrate.go | 2 +- internal/log/log.go | 5 +++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/cmd/federation.go b/cmd/federation.go index 7aa8d21..f06582e 100644 --- a/cmd/federation.go +++ b/cmd/federation.go @@ -12,7 +12,7 @@ import ( func main() { // bootstrap logger - logger := log.NewLogger() + logger := log.NewLogger("main") // Load connection string from .env file err := godotenv.Load() diff --git a/internal/db/migrate.go b/internal/db/migrate.go index 342628f..dd628f1 100644 --- a/internal/db/migrate.go +++ b/internal/db/migrate.go @@ -17,7 +17,7 @@ import ( var migrations embed.FS func RunMigrations(db *sql.DB) { - logger := log.NewLogger() + logger := log.NewLogger("db migrations") logger.Debug("Running migrations...") driver, err := mysql.WithInstance(db, &mysql.Config{}) if err != nil { diff --git a/internal/log/log.go b/internal/log/log.go index d01ae58..1aed252 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -2,6 +2,7 @@ package log import ( "encoding/json" + "fmt" "github.com/rs/zerolog" "io" "net/http" @@ -21,9 +22,9 @@ type Log struct { *zerolog.Logger } -func NewLogger() *Log { +func NewLogger(name string) *Log { logger := zerolog.New(os.Stdout) - logger.Debug().Msg("Logger started") + logger.Debug().Msg(fmt.Sprintf("%s logger started", name)) return &Log{&logger} } From 5eeaf9b6071e2fdc046b5c2cf6c4cb9e5f9cceda Mon Sep 17 00:00:00 2001 From: Devan Date: Wed, 24 Jan 2024 13:29:12 -0600 Subject: [PATCH 11/12] changes per joe --- cmd/federation.go | 2 +- internal/http/user.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/federation.go b/cmd/federation.go index f06582e..1911d15 100644 --- a/cmd/federation.go +++ b/cmd/federation.go @@ -24,8 +24,8 @@ func main() { if err != nil { logger.Fatal("failed connecting to db", err) } - db.RunMigrations(conn) defer conn.Close() + db.RunMigrations(conn) s := http.NewServer(logger) s.RunServer() diff --git a/internal/http/user.go b/internal/http/user.go index 85e2f82..5224bc1 100644 --- a/internal/http/user.go +++ b/internal/http/user.go @@ -18,7 +18,7 @@ func (server *Server) getUserInfoHandler(w http.ResponseWriter, r *http.Request) vars := mux.Vars(r) ctx := context.Background() c := lemmy.GetLemmyClient(ctx) - server.Logger.Info(fmt.Sprintf("Looking up user %server", vars["user"])) + server.Logger.Info(fmt.Sprintf("Looking up user %s", vars["user"])) user, err := c.GetUser(ctx, vars["user"]) if err != nil { server.Logger.Error("Error reading user", err) From 76daff0c4496645c96b5f3d3b5509103ea9118ed Mon Sep 17 00:00:00 2001 From: Devan Date: Wed, 24 Jan 2024 13:37:12 -0600 Subject: [PATCH 12/12] changes per joe --- internal/http/activity.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/http/activity.go b/internal/http/activity.go index 15e2697..996db35 100644 --- a/internal/http/activity.go +++ b/internal/http/activity.go @@ -42,7 +42,7 @@ func (server *Server) getActivityHandler(w http.ResponseWriter, r *http.Request) break default: - error.Error(fmt.Errorf("action %server not found", vars["action"])) + error.Error(fmt.Errorf("action %s not found", vars["action"])) w.WriteHeader(http.StatusNotFound) return }