Converted to JSON slog

This commit is contained in:
Magnus Åhall 2023-12-28 09:09:56 +01:00
parent 251186389d
commit abbd320b93
4 changed files with 40 additions and 41 deletions

View File

@ -6,7 +6,7 @@ import (
// Standard // Standard
"errors" "errors"
"io/ioutil" "os"
) )
@ -37,7 +37,7 @@ type Config struct {
func ConfigRead(filename string) (config Config, err error) { func ConfigRead(filename string) (config Config, err error) {
var rawConfigData []byte var rawConfigData []byte
rawConfigData, err = ioutil.ReadFile(filename) rawConfigData, err = os.ReadFile(filename)
if err != nil { return } if err != nil { return }
err = yaml.Unmarshal(rawConfigData, &config) err = yaml.Unmarshal(rawConfigData, &config)

View File

@ -6,7 +6,6 @@ import (
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
// Standard // Standard
"log"
"net/http" "net/http"
) )
@ -72,7 +71,7 @@ func (cm *ConnectionManager) NewConnection(w http.ResponseWriter, r *http.Reques
cm.connections[wsConn.UUID] = &wsConn cm.connections[wsConn.UUID] = &wsConn
// Successfully upgraded to a websocket connection. // Successfully upgraded to a websocket connection.
log.Printf("[%s] Connection from %s", wsConn.UUID, r.RemoteAddr) logger.Info("websocket", "uuid", wsConn.UUID, "remote_addr", r.RemoteAddr)
go cm.ReadLoop(&wsConn) go cm.ReadLoop(&wsConn)
@ -82,9 +81,7 @@ func (cm *ConnectionManager) NewConnection(w http.ResponseWriter, r *http.Reques
// Prune closes an deletes connections. If this happened to be non-fatal, the // Prune closes an deletes connections. If this happened to be non-fatal, the
// user will just have to reconnect. // user will just have to reconnect.
func (cm *ConnectionManager) Prune(wsConn *WsConnection, err error) {// {{{ func (cm *ConnectionManager) Prune(wsConn *WsConnection, err error) {// {{{
if false { logger.Info("websocket", "op", "prune", "uuid", wsConn.UUID)
log.Printf("[%s] pruning connection [%s]\n", wsConn.UUID, err)
}
wsConn.Conn.Close() wsConn.Conn.Close()
wsConn.Pruned = true wsConn.Pruned = true
delete(cm.connections, wsConn.UUID) delete(cm.connections, wsConn.UUID)
@ -98,8 +95,7 @@ func (cm *ConnectionManager) ReadLoop(wsConn *WsConnection) {// {{{
break break
} }
log.Printf("%s\n", data) logger.Debug("websocket", "op", "read", "data", data)
//cm.Send(wsConn, response) //cm.Send(wsConn, response)
} }
}// }}} }// }}}

13
db.go
View File

@ -9,7 +9,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io/fs" "io/fs"
"log"
"regexp" "regexp"
"strconv" "strconv"
) )
@ -29,11 +28,7 @@ func dbInit() (err error) { // {{{
config.Database.Name, config.Database.Name,
) )
log.Printf( logger.Info("db", "op", "connect", "host", config.Database.Host, "port", config.Database.Port)
"\x1b[32mNotes\x1b[0m Connecting to database %s:%d\n",
config.Database.Host,
config.Database.Port,
)
if db, err = sqlx.Connect("postgres", dbConn); err != nil { if db, err = sqlx.Connect("postgres", dbConn); err != nil {
return return
@ -66,7 +61,7 @@ func dbVerifyInternals() (err error) { // {{{
} }
if !exists { if !exists {
log.Printf("\x1b[32mNotes\x1b[0m Creating _internal.db\n") logger.Info("db", "op", "create_db", "db", "_internal.db")
if _, err = db.Exec(` if _, err = db.Exec(`
CREATE SCHEMA "_internal"; CREATE SCHEMA "_internal";
@ -114,7 +109,7 @@ func dbUpdate() (err error) { // {{{
} }
sqlSchemaVersion := sqlSchema() sqlSchemaVersion := sqlSchema()
for i := (schema + 1); i <= sqlSchemaVersion; i++ { for i := (schema + 1); i <= sqlSchemaVersion; i++ {
log.Printf("\x1b[32mNotes\x1b[0m Upgrading SQL schema to revision %d...", i) logger.Info("db", "op", "upgrade_schema", "schema", i)
sql, _ := embedded.ReadFile( sql, _ := embedded.ReadFile(
fmt.Sprintf("sql/%04d.sql", i), fmt.Sprintf("sql/%04d.sql", i),
) )
@ -126,7 +121,7 @@ func dbUpdate() (err error) { // {{{
if err != nil { if err != nil {
return return
} }
log.Printf("\x1b[32mNotes\x1b[0m OK: %d", i) logger.Info("db", "op", "upgrade_schema", "schema", i, "result", "ok")
} }
return return

54
main.go
View File

@ -9,7 +9,7 @@ import (
"fmt" "fmt"
"html/template" "html/template"
"io" "io"
"log" "log/slog"
"net/http" "net/http"
"os" "os"
"path" "path"
@ -30,6 +30,7 @@ var (
connectionManager ConnectionManager connectionManager ConnectionManager
static http.Handler static http.Handler
config Config config Config
logger *slog.Logger
VERSION string VERSION string
//go:embed version sql/* //go:embed version sql/*
@ -40,6 +41,9 @@ func init() { // {{{
version, _ := embedded.ReadFile("version") version, _ := embedded.ReadFile("version")
VERSION = strings.TrimSpace(string(version)) VERSION = strings.TrimSpace(string(version))
opt := slog.HandlerOptions{}
logger = slog.New(slog.NewJSONHandler(os.Stdout, &opt))
configFilename := os.Getenv("HOME") + "/.config/notes.yaml" configFilename := os.Getenv("HOME") + "/.config/notes.yaml"
flag.IntVar(&flagPort, "port", 1371, "TCP port to listen on") flag.IntVar(&flagPort, "port", 1371, "TCP port to listen on")
flag.BoolVar(&flagVersion, "version", false, "Shows Notes version and exists") flag.BoolVar(&flagVersion, "version", false, "Shows Notes version and exists")
@ -55,23 +59,23 @@ func main() { // {{{
os.Exit(0) os.Exit(0)
} }
log.Printf("\x1b[32mNotes\x1b[0m %s\n", VERSION) logger.Info("application", "version", VERSION)
config, err = ConfigRead(flagConfig) config, err = ConfigRead(flagConfig)
if err != nil { if err != nil {
fmt.Printf("%s\n", err) logger.Error("config", "error", err)
os.Exit(1) os.Exit(1)
} }
if err = dbInit(); err != nil { if err = dbInit(); err != nil {
fmt.Printf("%s\n", err) logger.Error("db", "error", err)
os.Exit(1) os.Exit(1)
} }
if flagCreateUser { if flagCreateUser {
err = createUser() err = createUser()
if err != nil { if err != nil {
fmt.Println(err) logger.Error("db", "error", err)
os.Exit(1) os.Exit(1)
} }
os.Exit(0) os.Exit(0)
@ -102,13 +106,12 @@ func main() { // {{{
http.HandleFunc("/", staticHandler) http.HandleFunc("/", staticHandler)
listen := fmt.Sprintf("%s:%d", LISTEN_HOST, flagPort) listen := fmt.Sprintf("%s:%d", LISTEN_HOST, flagPort)
log.Printf("\x1b[32mNotes\x1b[0m Listening on %s\n", listen) logger.Info("webserver", "listen", listen, "domains", config.Websocket.Domains)
log.Printf("\x1b[32mNotes\x1b[0m Answer for domains %s\n", strings.Join(config.Websocket.Domains, ", "))
http.ListenAndServe(listen, nil) http.ListenAndServe(listen, nil)
} // }}} } // }}}
func cssUpdateHandler(w http.ResponseWriter, r *http.Request) { // {{{ func cssUpdateHandler(w http.ResponseWriter, r *http.Request) { // {{{
log.Println("[BROADCAST] CSS updated") logger.Debug("webserver", "css", "updated")
connectionManager.Broadcast(struct { connectionManager.Broadcast(struct {
Ok bool Ok bool
ID string ID string
@ -120,7 +123,7 @@ func websocketHandler(w http.ResponseWriter, r *http.Request) { // {{{
_, err = connectionManager.NewConnection(w, r) _, err = connectionManager.NewConnection(w, r)
if err != nil { if err != nil {
log.Printf("[Connection] %s\n", err) logger.Error("websocket", "error", err)
return return
} }
} // }}} } // }}}
@ -134,7 +137,7 @@ func staticHandler(w http.ResponseWriter, r *http.Request) { // {{{
// URLs with pattern /(css|images)/v1.0.0/foobar are stripped of the version. // URLs with pattern /(css|images)/v1.0.0/foobar are stripped of the version.
// To get rid of problems with cached content in browser on a new version release, // To get rid of problems with cached content in browser on a new version release,
// while also not disabling cache altogether. // while also not disabling cache altogether.
log.Printf("static: %s", r.URL.Path) logger.Debug("webserver", "request", r.URL.Path)
if r.URL.Path == "/favicon.ico" { if r.URL.Path == "/favicon.ico" {
static.ServeHTTP(w, r) static.ServeHTTP(w, r)
return return
@ -149,7 +152,7 @@ func staticHandler(w http.ResponseWriter, r *http.Request) { // {{{
// Everything else is run through the template system. // Everything else is run through the template system.
// For now to get VERSION into files to fix caching. // For now to get VERSION into files to fix caching.
log.Printf("template: %s", r.URL.Path) logger.Debug("webserver", "template", r.URL.Path)
tmpl, err := newTemplate(r.URL.Path) tmpl, err := newTemplate(r.URL.Path)
if err != nil { if err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
@ -165,7 +168,7 @@ func staticHandler(w http.ResponseWriter, r *http.Request) { // {{{
} // }}} } // }}}
func sessionCreate(w http.ResponseWriter, r *http.Request) { // {{{ func sessionCreate(w http.ResponseWriter, r *http.Request) { // {{{
log.Println("/session/create") logger.Info("webserver", "request", "/session/create")
session, err := CreateSession() session, err := CreateSession()
if err != nil { if err != nil {
responseError(w, err) responseError(w, err)
@ -177,7 +180,7 @@ func sessionCreate(w http.ResponseWriter, r *http.Request) { // {{{
}) })
} // }}} } // }}}
func sessionRetrieve(w http.ResponseWriter, r *http.Request) { // {{{ func sessionRetrieve(w http.ResponseWriter, r *http.Request) { // {{{
log.Println("/session/retrieve") logger.Info("webserver", "request", "/session/retrieve")
var err error var err error
var found bool var found bool
var session Session var session Session
@ -194,7 +197,7 @@ func sessionRetrieve(w http.ResponseWriter, r *http.Request) { // {{{
}) })
} // }}} } // }}}
func sessionAuthenticate(w http.ResponseWriter, r *http.Request) { // {{{ func sessionAuthenticate(w http.ResponseWriter, r *http.Request) { // {{{
log.Println("/session/authenticate") logger.Info("webserver", "request", "/session/authenticate")
var err error var err error
var session Session var session Session
var authenticated bool var authenticated bool
@ -284,7 +287,7 @@ func nodeTree(w http.ResponseWriter, r *http.Request) { // {{{
}) })
} // }}} } // }}}
func nodeRetrieve(w http.ResponseWriter, r *http.Request) { // {{{ func nodeRetrieve(w http.ResponseWriter, r *http.Request) { // {{{
log.Println("/node/retrieve") logger.Info("webserver", "request", "/node/retrieve")
var err error var err error
var session Session var session Session
@ -311,7 +314,7 @@ func nodeRetrieve(w http.ResponseWriter, r *http.Request) { // {{{
}) })
} // }}} } // }}}
func nodeCreate(w http.ResponseWriter, r *http.Request) { // {{{ func nodeCreate(w http.ResponseWriter, r *http.Request) { // {{{
log.Println("/node/create") logger.Info("webserver", "request", "/node/create")
var err error var err error
var session Session var session Session
@ -341,7 +344,7 @@ func nodeCreate(w http.ResponseWriter, r *http.Request) { // {{{
}) })
} // }}} } // }}}
func nodeUpdate(w http.ResponseWriter, r *http.Request) { // {{{ func nodeUpdate(w http.ResponseWriter, r *http.Request) { // {{{
log.Println("/node/update") logger.Info("webserver", "request", "/node/update")
var err error var err error
var session Session var session Session
@ -371,6 +374,8 @@ func nodeUpdate(w http.ResponseWriter, r *http.Request) { // {{{
}) })
} // }}} } // }}}
func nodeRename(w http.ResponseWriter, r *http.Request) { // {{{ func nodeRename(w http.ResponseWriter, r *http.Request) { // {{{
logger.Info("webserver", "request", "/node/rename")
var err error var err error
var session Session var session Session
@ -399,6 +404,8 @@ func nodeRename(w http.ResponseWriter, r *http.Request) { // {{{
}) })
} // }}} } // }}}
func nodeDelete(w http.ResponseWriter, r *http.Request) { // {{{ func nodeDelete(w http.ResponseWriter, r *http.Request) { // {{{
logger.Info("webserver", "request", "/node/delete")
var err error var err error
var session Session var session Session
@ -426,7 +433,7 @@ func nodeDelete(w http.ResponseWriter, r *http.Request) { // {{{
}) })
} // }}} } // }}}
func nodeUpload(w http.ResponseWriter, r *http.Request) { // {{{ func nodeUpload(w http.ResponseWriter, r *http.Request) { // {{{
log.Println("/node/upload") logger.Info("webserver", "request", "/node/upload")
var err error var err error
var session Session var session Session
@ -510,7 +517,7 @@ func nodeUpload(w http.ResponseWriter, r *http.Request) { // {{{
}) })
} // }}} } // }}}
func nodeDownload(w http.ResponseWriter, r *http.Request) { // {{{ func nodeDownload(w http.ResponseWriter, r *http.Request) { // {{{
log.Println("/node/download") logger.Info("webserver", "request", "/node/download")
var err error var err error
var session Session var session Session
var files []File var files []File
@ -577,6 +584,7 @@ func nodeDownload(w http.ResponseWriter, r *http.Request) { // {{{
} // }}} } // }}}
func nodeFiles(w http.ResponseWriter, r *http.Request) { // {{{ func nodeFiles(w http.ResponseWriter, r *http.Request) { // {{{
logger.Info("webserver", "request", "/node/files")
var err error var err error
var session Session var session Session
var files []File var files []File
@ -606,7 +614,7 @@ func nodeFiles(w http.ResponseWriter, r *http.Request) { // {{{
}) })
} // }}} } // }}}
func nodeSearch(w http.ResponseWriter, r *http.Request) { // {{{ func nodeSearch(w http.ResponseWriter, r *http.Request) { // {{{
log.Println("/node/search") logger.Info("webserver", "request", "/node/search")
var err error var err error
var session Session var session Session
var nodes []Node var nodes []Node
@ -637,7 +645,7 @@ func nodeSearch(w http.ResponseWriter, r *http.Request) { // {{{
} // }}} } // }}}
func keyRetrieve(w http.ResponseWriter, r *http.Request) { // {{{ func keyRetrieve(w http.ResponseWriter, r *http.Request) { // {{{
log.Println("/key/retrieve") logger.Info("webserver", "request", "/key/retrieve")
var err error var err error
var session Session var session Session
@ -658,7 +666,7 @@ func keyRetrieve(w http.ResponseWriter, r *http.Request) { // {{{
}) })
} // }}} } // }}}
func keyCreate(w http.ResponseWriter, r *http.Request) { // {{{ func keyCreate(w http.ResponseWriter, r *http.Request) { // {{{
log.Println("/key/create") logger.Info("webserver", "request", "/key/create")
var err error var err error
var session Session var session Session
@ -688,7 +696,7 @@ func keyCreate(w http.ResponseWriter, r *http.Request) { // {{{
}) })
} // }}} } // }}}
func keyCounter(w http.ResponseWriter, r *http.Request) { // {{{ func keyCounter(w http.ResponseWriter, r *http.Request) { // {{{
log.Println("/key/counter") logger.Info("webserver", "request", "/key/counter")
var err error var err error
var session Session var session Session