diff options
| author | Samuel Johnson <[email protected]> | 2025-11-25 20:52:35 -0500 |
|---|---|---|
| committer | Samuel Johnson <[email protected]> | 2025-11-25 20:52:35 -0500 |
| commit | 44d6620b32f31c04663c9e08a1c3954273230ee8 (patch) | |
| tree | a87cf977313ec95f050d7cdbbebd8bdae7c00ab2 | |
| parent | 12602302f28478a9e4ef91e66f68347a4d76f8a6 (diff) | |
Tidy the code
| -rw-r--r-- | cmd/parser/main.go | 12 | ||||
| -rw-r--r-- | cmd/web/handlers/blog.go | 34 | ||||
| -rw-r--r-- | cmd/web/handlers/fs.go | 22 | ||||
| -rw-r--r-- | cmd/web/handlers/login.go | 26 | ||||
| -rw-r--r-- | cmd/web/handlers/routes.go | 18 | ||||
| -rw-r--r-- | cmd/web/main.go | 8 | ||||
| -rw-r--r-- | cmd/web/middleware/auth.go | 66 | ||||
| -rw-r--r-- | cmd/web/types/application.go | 9 | ||||
| -rw-r--r-- | go.mod | 6 | ||||
| -rw-r--r-- | go.sum | 7 | ||||
| -rw-r--r-- | internal/context/environment.go | 6 | ||||
| -rw-r--r-- | internal/dbmigrations.go | 3 | ||||
| -rw-r--r-- | internal/models/post.go | 10 | ||||
| -rw-r--r-- | internal/models/user.go | 6 | ||||
| -rw-r--r-- | static/favicon.ico | bin | 0 -> 258093 bytes |
15 files changed, 121 insertions, 112 deletions
diff --git a/cmd/parser/main.go b/cmd/parser/main.go index 44fca42..0ef8b4d 100644 --- a/cmd/parser/main.go +++ b/cmd/parser/main.go @@ -35,7 +35,7 @@ func mdServe(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusMethodNotAllowed, "Method Not Allowed") return } - + err := r.ParseMultipartForm(4 << 20) if err != nil { writeErr(w, http.StatusUnprocessableEntity, fmt.Sprintf("Failed to retrieve form data: %v", err)) @@ -48,25 +48,25 @@ func mdServe(w http.ResponseWriter, r *http.Request) { userId := r.Form.Get("user_id") shouldCreateShort := len(md) > 255 - + err = mdParser.Convert([]byte(md), &longBuf) if err != nil { writeErr(w, http.StatusUnprocessableEntity, fmt.Sprintf("Failed to compile markdown into html: %v", err)) return } - + var shortMd string if shouldCreateShort { shortMd = md[0:249] err = mdParser.Convert([]byte(shortMd), &shortBuf) - + if err != nil { writeErr(w, http.StatusUnprocessableEntity, fmt.Sprintf("Failed to compile markdown into html: %v", err)) return } } - ctx, cancel := context.WithTimeout(r.Context(), 5 * time.Second) + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() tx, err := db.BeginTx(ctx, nil) @@ -155,7 +155,7 @@ func main() { } srv := &http.Server{ - Addr: fmt.Sprintf(":%d", appPort), + Addr: fmt.Sprintf(":%d", appPort), Handler: router, } diff --git a/cmd/web/handlers/blog.go b/cmd/web/handlers/blog.go index 8d9a811..14a0abe 100644 --- a/cmd/web/handlers/blog.go +++ b/cmd/web/handlers/blog.go @@ -16,14 +16,14 @@ import ( ) type blogContext struct { - err *log.Logger - db *sql.DB + err *log.Logger + db *sql.DB - Post models.Post - Rows []models.Post - Name string - IsAuth bool - Offset int + Post models.Post + Rows []models.Post + Name string + IsAuth bool + Offset int } func (ctx *blogContext) viewPost(w http.ResponseWriter, r *http.Request) { @@ -56,7 +56,7 @@ func (ctx *blogContext) viewPost(w http.ResponseWriter, r *http.Request) { } p.FormattedTime = p.Time.Format(time.ANSIC) - ctx.Post = p + ctx.Post = p files := []string{ "ui/html/base.tmpl.html", @@ -113,7 +113,7 @@ func (ctx *blogContext) post(w http.ResponseWriter, r *http.Request) { if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte("Internal Error")) - return; + return } err = r.ParseMultipartForm(4 << 20) @@ -129,7 +129,7 @@ func (ctx *blogContext) post(w http.ResponseWriter, r *http.Request) { writer := multipart.NewWriter(&buffer) writer.SetBoundary(boundary) writer.WriteField("user_id", strconv.Itoa(int(userId))) - + part, err := writer.CreateFormField("raw") if err != nil { w.WriteHeader(http.StatusInternalServerError) @@ -137,7 +137,7 @@ func (ctx *blogContext) post(w http.ResponseWriter, r *http.Request) { ctx.err.Printf("Could not create form field: %v\n", err) return } - + _, err = part.Write([]byte(r.Form.Get("raw"))) if err != nil { w.WriteHeader(http.StatusInternalServerError) @@ -148,11 +148,11 @@ func (ctx *blogContext) post(w http.ResponseWriter, r *http.Request) { writer.Close() - proxyReq, err := http.NewRequest(r.Method, "http://127.0.0.1:" + os.Getenv("parser_port"), bytes.NewReader(buffer.Bytes())) + proxyReq, err := http.NewRequest(r.Method, "http://127.0.0.1:"+os.Getenv("parser_port"), bytes.NewReader(buffer.Bytes())) proxyReq.Header = make(http.Header) for key, val := range r.Header { if key != "Content-Length" { - proxyReq.Header[key] = val; + proxyReq.Header[key] = val } } @@ -190,10 +190,10 @@ func (ctx *blogContext) index(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) return } - + _, err := r.Cookie("paterissa_session_token") if err == nil { - ctx.IsAuth = true; + ctx.IsAuth = true } ctx.Offset, _ = strconv.Atoi(r.URL.Query().Get("offset")) @@ -230,10 +230,10 @@ func (ctx *blogContext) index(w http.ResponseWriter, r *http.Request) { funcMap := template.FuncMap{ "add": func(a int, b int) int { - return a + b; + return a + b }, "sub": func(a int, b int) int { - return a - b; + return a - b }, } diff --git a/cmd/web/handlers/fs.go b/cmd/web/handlers/fs.go index 96f11d0..1a68e35 100644 --- a/cmd/web/handlers/fs.go +++ b/cmd/web/handlers/fs.go @@ -9,9 +9,9 @@ import ( ) type fsContext struct { - err *log.Logger - path string - contentType string + err *log.Logger + path string + contentType string } func (ctx *fsContext) readdir(w http.ResponseWriter, r *http.Request) { @@ -45,14 +45,14 @@ func (ctx *fsContext) get(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", ctx.contentType) } else { switch filepath.Ext(name) { - case ".css": - w.Header().Set("Content-Type", "text/css") - case ".js": - w.Header().Set("Content-Type", "text/javascript") - case ".svg": - w.Header().Set("Content-Type", "image/svg+xml") - case ".png": - w.Header().Set("Content-Type", "image/png") + case ".css": + w.Header().Set("Content-Type", "text/css") + case ".js": + w.Header().Set("Content-Type", "text/javascript") + case ".svg": + w.Header().Set("Content-Type", "image/svg+xml") + case ".png": + w.Header().Set("Content-Type", "image/png") } } diff --git a/cmd/web/handlers/login.go b/cmd/web/handlers/login.go index f912977..3b1ee92 100644 --- a/cmd/web/handlers/login.go +++ b/cmd/web/handlers/login.go @@ -15,7 +15,7 @@ import ( type loginContext struct { err *log.Logger - db *sql.DB + db *sql.DB } func (ctx *loginContext) index(w http.ResponseWriter, r *http.Request) { @@ -82,7 +82,7 @@ func (ctx *loginContext) login(w http.ResponseWriter, r *http.Request) { ctx.err.Printf("Failed to retrieve user info from DB: %v\n", err) return } - + passOneErr := bcrypt.CompareHashAndPassword([]byte(u.PassOne), []byte(passOne)) passTwoErr := bcrypt.CompareHashAndPassword([]byte(u.PassTwo), []byte(passTwo)) if passOneErr != nil || passTwoErr != nil { @@ -92,13 +92,13 @@ func (ctx *loginContext) login(w http.ResponseWriter, r *http.Request) { } cookie := http.Cookie{ - Name: "paterissa_session_token", - Value: uuid.New().String(), - Expires: time.Now().AddDate(0, 0, 1), - Path: "/", - Domain: os.Getenv("serv"), + Name: "paterissa_session_token", + Value: uuid.New().String(), + Expires: time.Now().AddDate(0, 0, 1), + Path: "/", + Domain: os.Getenv("serv"), HttpOnly: true, - Secure: true, + Secure: true, } commit, err := ctx.db.Prepare("INSERT INTO cookies (content, user_id, expiration) VALUES ($1, $2, $3);") @@ -147,11 +147,11 @@ func (ctx *loginContext) logout(w http.ResponseWriter, r *http.Request) { } cookie = &http.Cookie{ - Name: "paterissa_session_token", - Value: "", - Path: "/", - Domain: os.Getenv("serv"), - MaxAge: -1, + Name: "paterissa_session_token", + Value: "", + Path: "/", + Domain: os.Getenv("serv"), + MaxAge: -1, HttpOnly: true, } diff --git a/cmd/web/handlers/routes.go b/cmd/web/handlers/routes.go index a4c9c09..4b80615 100644 --- a/cmd/web/handlers/routes.go +++ b/cmd/web/handlers/routes.go @@ -11,25 +11,25 @@ import ( func RegisterEndpoints(app types.Application, db *sql.DB) *http.ServeMux { auth := middleware.AuthMiddleware{ Err: app.Err, - Db: db, + Db: db, } blog := blogContext{ - err: app.Err, - db: db, + err: app.Err, + db: db, Name: app.Env.Webmaster, } login := loginContext{ err: app.Err, - db: db, + db: db, } audio := fsContext{ - err: app.Err, - path: app.AudioDir, + err: app.Err, + path: app.AudioDir, contentType: "audio/mpeg", } static := fsContext{ - err: app.Err, + err: app.Err, path: "static", } @@ -46,5 +46,9 @@ func RegisterEndpoints(app types.Application, db *sql.DB) *http.ServeMux { blogRouter.HandleFunc("/static/get", static.get) + blogRouter.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) { + http.ServeFile(w, r, "/static/favicon.ico") + }) + return blogRouter } diff --git a/cmd/web/main.go b/cmd/web/main.go index 0b35ff2..00286b8 100644 --- a/cmd/web/main.go +++ b/cmd/web/main.go @@ -20,8 +20,8 @@ import ( func main() { var app types.Application - app.Err = log.New(os.Stderr, "ERROR\t", log.Ldate | log.Ltime) - app.Info = log.New(os.Stdout, "INFO\t", log.Ldate | log.Ltime) + app.Err = log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime) + app.Info = log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime) err := godotenv.Load() if err != nil { @@ -62,9 +62,9 @@ func main() { router := handlers.RegisterEndpoints(app, db) srv := &http.Server{ - Addr: fmt.Sprintf(":%d", app.Env.AppPort), + Addr: fmt.Sprintf(":%d", app.Env.AppPort), ErrorLog: app.Err, - Handler: router, + Handler: router, } err = srv.ListenAndServe() diff --git a/cmd/web/middleware/auth.go b/cmd/web/middleware/auth.go index 255f40f..e396e86 100644 --- a/cmd/web/middleware/auth.go +++ b/cmd/web/middleware/auth.go @@ -10,12 +10,12 @@ import ( type AuthMiddleware struct { Err *log.Logger - Db *sql.DB + Db *sql.DB } func (auth *AuthMiddleware) CheckAndInvalidate(next http.HandlerFunc) http.HandlerFunc { return http.HandlerFunc( - func (w http.ResponseWriter, r *http.Request) { + func(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie("paterissa_session_token") if err != nil { next.ServeHTTP(w, r) @@ -25,11 +25,11 @@ func (auth *AuthMiddleware) CheckAndInvalidate(next http.HandlerFunc) http.Handl stmt, err := auth.Db.Prepare("SELECT * FROM cookies WHERE content = $1;") if err != nil { cookie = &http.Cookie{ - Name: "paterissa_session_token", - Value: "", - Path: "/", - Domain: os.Getenv("serv"), - MaxAge: -1, + Name: "paterissa_session_token", + Value: "", + Path: "/", + Domain: os.Getenv("serv"), + MaxAge: -1, HttpOnly: true, } http.SetCookie(w, cookie) @@ -47,11 +47,11 @@ func (auth *AuthMiddleware) CheckAndInvalidate(next http.HandlerFunc) http.Handl err = row.Scan(&id, &content, &userId, &expiration) if err != nil { cookie = &http.Cookie{ - Name: "paterissa_session_token", - Value: "", - Path: "/", - Domain: os.Getenv("serv"), - MaxAge: -1, + Name: "paterissa_session_token", + Value: "", + Path: "/", + Domain: os.Getenv("serv"), + MaxAge: -1, HttpOnly: true, } http.SetCookie(w, cookie) @@ -61,11 +61,11 @@ func (auth *AuthMiddleware) CheckAndInvalidate(next http.HandlerFunc) http.Handl if time.Now().After(expiration) { cookie = &http.Cookie{ - Name: "paterissa_session_token", - Value: "", - Path: "/", - Domain: os.Getenv("serv"), - MaxAge: -1, + Name: "paterissa_session_token", + Value: "", + Path: "/", + Domain: os.Getenv("serv"), + MaxAge: -1, HttpOnly: true, } http.SetCookie(w, cookie) @@ -80,7 +80,7 @@ func (auth *AuthMiddleware) CheckAndInvalidate(next http.HandlerFunc) http.Handl func (auth *AuthMiddleware) Resolve(next http.HandlerFunc) http.HandlerFunc { return http.HandlerFunc( - func (w http.ResponseWriter, r *http.Request) { + func(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie("paterissa_session_token") if err != nil { w.WriteHeader(http.StatusUnauthorized) @@ -91,11 +91,11 @@ func (auth *AuthMiddleware) Resolve(next http.HandlerFunc) http.HandlerFunc { stmt, err := auth.Db.Prepare("SELECT * FROM cookies WHERE content = $1;") if err != nil { cookie = &http.Cookie{ - Name: "paterissa_session_token", - Value: "", - Path: "/", - Domain: os.Getenv("serv"), - MaxAge: -1, + Name: "paterissa_session_token", + Value: "", + Path: "/", + Domain: os.Getenv("serv"), + MaxAge: -1, HttpOnly: true, } http.SetCookie(w, cookie) @@ -116,11 +116,11 @@ func (auth *AuthMiddleware) Resolve(next http.HandlerFunc) http.HandlerFunc { err = row.Scan(&id, &content, &userId, &expiration) if err != nil { cookie = &http.Cookie{ - Name: "paterissa_session_token", - Value: "", - Path: "/", - Domain: os.Getenv("serv"), - MaxAge: -1, + Name: "paterissa_session_token", + Value: "", + Path: "/", + Domain: os.Getenv("serv"), + MaxAge: -1, HttpOnly: true, } http.SetCookie(w, cookie) @@ -133,11 +133,11 @@ func (auth *AuthMiddleware) Resolve(next http.HandlerFunc) http.HandlerFunc { if time.Now().After(expiration) { cookie = &http.Cookie{ - Name: "paterissa_session_token", - Value: "", - Path: "/", - Domain: os.Getenv("serv"), - MaxAge: -1, + Name: "paterissa_session_token", + Value: "", + Path: "/", + Domain: os.Getenv("serv"), + MaxAge: -1, HttpOnly: true, } http.SetCookie(w, cookie) diff --git a/cmd/web/types/application.go b/cmd/web/types/application.go index 8bc6a73..8ded626 100644 --- a/cmd/web/types/application.go +++ b/cmd/web/types/application.go @@ -7,11 +7,10 @@ import ( ) type Application struct { - Err *log.Logger - Info *log.Logger + Err *log.Logger + Info *log.Logger - AudioDir string + AudioDir string - Env context.Environment + Env context.Environment } - @@ -3,17 +3,17 @@ module paterissa.net/mblog go 1.23.5 require ( + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.7.6 github.com/joho/godotenv v1.5.1 github.com/yuin/goldmark v1.7.11 + golang.org/x/crypto v0.37.0 ) require ( - github.com/google/uuid v1.6.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/jackc/pgx/v5 v5.7.6 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect - golang.org/x/crypto v0.37.0 // indirect golang.org/x/sync v0.13.0 // indirect golang.org/x/text v0.24.0 // indirect ) @@ -1,4 +1,6 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= @@ -11,10 +13,13 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/yuin/goldmark v1.7.11 h1:ZCxLyDMtz0nT2HFfsYG8WZ47Trip2+JyLysKcMYE5bo= github.com/yuin/goldmark v1.7.11/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= @@ -25,3 +30,5 @@ golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/context/environment.go b/internal/context/environment.go index 35cb9d8..3e680cf 100644 --- a/internal/context/environment.go +++ b/internal/context/environment.go @@ -1,9 +1,9 @@ package context type DbCredentials struct { - Name string - Host string - Port uint64 + Name string + Host string + Port uint64 Username string Password string } diff --git a/internal/dbmigrations.go b/internal/dbmigrations.go index d5f4836..50badc0 100644 --- a/internal/dbmigrations.go +++ b/internal/dbmigrations.go @@ -8,7 +8,7 @@ import ( "golang.org/x/crypto/bcrypt" ) -func Migrate (db *sql.DB, webmaster string, passOne string, passTwo string) { +func Migrate(db *sql.DB, webmaster string, passOne string, passTwo string) { _, table_check := db.Query("SELECT * FROM logins;") if table_check != nil { _, err := db.Exec("CREATE TABLE logins (id SERIAL PRIMARY KEY, name VARCHAR(50) NOT NULL, time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, pass_one TEXT NOT NULL, pass_two TEXT NOT NULL);") @@ -40,7 +40,6 @@ func Migrate (db *sql.DB, webmaster string, passOne string, passTwo string) { } } - _, table_check = db.Query("SELECT * FROM cookies;") if table_check != nil { _, err := db.Exec("CREATE TABLE cookies (id SERIAL PRIMARY KEY, content VARCHAR(255) NOT NULL, user_id INTEGER REFERENCES logins(id), expiration TIMESTAMP);") diff --git a/internal/models/post.go b/internal/models/post.go index d7f1aaa..95dde58 100644 --- a/internal/models/post.go +++ b/internal/models/post.go @@ -6,10 +6,10 @@ import ( ) type Post struct { - Id int - Name string - Time time.Time + Id int + Name string + Time time.Time FormattedTime string - Brief template.HTML - Content template.HTML + Brief template.HTML + Content template.HTML } diff --git a/internal/models/user.go b/internal/models/user.go index 8753810..e75ea80 100644 --- a/internal/models/user.go +++ b/internal/models/user.go @@ -1,9 +1,9 @@ package models type User struct { - Id int - Name string - Time string + Id int + Name string + Time string PassOne string PassTwo string } diff --git a/static/favicon.ico b/static/favicon.ico Binary files differnew file mode 100644 index 0000000..17342e5 --- /dev/null +++ b/static/favicon.ico |
