From 0bc27e5fb1252716f82c2b5af56189e8b46ead3c Mon Sep 17 00:00:00 2001 From: Ririsoft Date: Sat, 8 Jun 2024 19:34:18 +0200 Subject: [PATCH] logging: fix file mode configuration parsing (#6383) Commit 101d3e7 introduced file mode setting, but was missing a JSON Marshaller so that CaddyFile can be converted to JSON safely. --- modules/logging/filewriter.go | 5 ++++ modules/logging/filewriter_test.go | 39 ++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/modules/logging/filewriter.go b/modules/logging/filewriter.go index 393228fda44..09cea1b4e1f 100644 --- a/modules/logging/filewriter.go +++ b/modules/logging/filewriter.go @@ -59,6 +59,11 @@ func (m *fileMode) UnmarshalJSON(b []byte) error { return err } +// MarshalJSON satisfies json.Marshaler. +func (m *fileMode) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf("\"%04o\"", *m)), nil +} + // parseFileMode parses a file mode string, // adding support for `chmod` unix command like // 1 to 4 digital octal values. diff --git a/modules/logging/filewriter_test.go b/modules/logging/filewriter_test.go index 2787eeff197..ab403930c75 100644 --- a/modules/logging/filewriter_test.go +++ b/modules/logging/filewriter_test.go @@ -306,3 +306,42 @@ func TestFileModeJSON(t *testing.T) { }) } } + +func TestFileModeToJSON(t *testing.T) { + tests := []struct { + name string + mode fileMode + want string + wantErr bool + }{ + { + name: "none zero", + mode: 0644, + want: `"0644"`, + wantErr: false, + }, + { + name: "zero mode", + mode: 0, + want: `"0000"`, + wantErr: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var b []byte + var err error + + if b, err = json.Marshal(&tt.mode); (err != nil) != tt.wantErr { + t.Fatalf("MarshalJSON() error = %v, want %v", err, tt.wantErr) + } + + got := string(b[:]) + + if got != tt.want { + t.Errorf("got mode %v, want %v", got, tt.want) + } + }) + } +}