Refactor JSON marshaling in Options to improve thread safety

This commit is contained in:
2025-11-14 21:50:58 +01:00
parent 4f4feacaa8
commit 7544fbb1ce
2 changed files with 25 additions and 15 deletions

View File

@@ -79,14 +79,8 @@ func (o *Options) UnmarshalJSON(data []byte) error {
}
func (o *Options) MarshalJSON() ([]byte, error) {
type Alias Options
aux := &struct {
*Alias
}{
Alias: (*Alias)(o),
}
// Get backend and marshal it
var backendOptions map[string]any
backend := o.getBackend()
if backend != nil {
optionsData, err := json.Marshal(backend)
@@ -94,13 +88,19 @@ func (o *Options) MarshalJSON() ([]byte, error) {
return nil, fmt.Errorf("failed to marshal backend options: %w", err)
}
// Create a new map to avoid concurrent map writes
aux.BackendOptions = make(map[string]any)
if err := json.Unmarshal(optionsData, &aux.BackendOptions); err != nil {
backendOptions = make(map[string]any)
if err := json.Unmarshal(optionsData, &backendOptions); err != nil {
return nil, fmt.Errorf("failed to unmarshal backend options to map: %w", err)
}
}
return json.Marshal(aux)
return json.Marshal(&struct {
BackendType BackendType `json:"backend_type"`
BackendOptions map[string]any `json:"backend_options,omitempty"`
}{
BackendType: o.BackendType,
BackendOptions: backendOptions,
})
}
// setBackendOptions stores the backend in the appropriate typed field