Debian Codegraph @

caddyconfig/configadapters.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package caddyconfig
16
17 import (
18 "encoding/json"
19 "fmt"
20
21 "github.com/caddyserver/caddy/v2"
22 )
23
24 // Adapter is a type which can adapt a configuration to Caddy JSON.
25 // It returns the results and any warnings, or an error.
26 type Adapter interface {
27 Adapt(body []byte, options map[string]any) ([]byte, []Warning, error)
28 }
29
30 // Warning represents a warning or notice related to conversion.
31 type Warning struct {
32 File string `json:"file,omitempty"`
33 Line int `json:"line,omitempty"`
34 Directive string `json:"directive,omitempty"`
35 Message string `json:"message,omitempty"`
36 }
37
38 func (w Warning) String() string {
39 var directive string
40 if w.Directive != "" {
41 directive = fmt.Sprintf(" (%s)", w.Directive)
42 }
43 return fmt.Sprintf("%s:%d%s: %s", w.File, w.Line, directive, w.Message)
44 }
45
46 // JSON encodes val as JSON, returning it as a json.RawMessage. Any
47 // marshaling errors (which are highly unlikely with correct code)
48 // are converted to warnings. This is convenient when filling config
49 // structs that require a json.RawMessage, without having to worry
50 // about errors.
51 func JSON(val any, warnings *[]Warning) json.RawMessage {
52 b, err := json.Marshal(val)
53 if err != nil {
54 if warnings != nil {
55 *warnings = append(*warnings, Warning{Message: err.Error()})
56 }
57 return nil
58 }
59 return b
60 }
61
62 // JSONModuleObject is like JSON(), except it marshals val into a JSON object
63 // with an added key named fieldName with the value fieldVal. This is useful
64 // for encoding module values where the module name has to be described within
65 // the object by a certain key; for example, `"handler": "file_server"` for a
66 // file server HTTP handler (fieldName="handler" and fieldVal="file_server").
67 // The val parameter must encode into a map[string]any (i.e. it must be
68 // a struct or map). Any errors are converted into warnings.
69 func JSONModuleObject(val any, fieldName, fieldVal string, warnings *[]Warning) json.RawMessage {
70 // encode to a JSON object first
71 enc, err := json.Marshal(val)
72 if err != nil {
73 if warnings != nil {
74 *warnings = append(*warnings, Warning{Message: err.Error()})
75 }
76 return nil
77 }
78
79 // then decode the object
80 var tmp map[string]any
81 err = json.Unmarshal(enc, &tmp)
82 if err != nil {
83 if warnings != nil {
84 message := err.Error()
85 if jsonErr, ok := err.(*json.SyntaxError); ok {
86 message = fmt.Sprintf("%v, at offset %d", jsonErr.Error(), jsonErr.Offset)
87 }
88 *warnings = append(*warnings, Warning{Message: message})
89 }
90 return nil
91 }
92
93 // so we can easily add the module's field with its appointed value
94 tmp[fieldName] = fieldVal
95
96 // then re-marshal as JSON
97 result, err := json.Marshal(tmp)
98 if err != nil {
99 if warnings != nil {
100 *warnings = append(*warnings, Warning{Message: err.Error()})
101 }
102 return nil
103 }
104
105 return result
106 }
107
108 // RegisterAdapter registers a config adapter with the given name.
109 // This should usually be done at init-time. It panics if the
110 // adapter cannot be registered successfully.
111 func RegisterAdapter(name string, adapter Adapter) {
112 if _, ok := configAdapters[name]; ok {
113 panic(fmt.Errorf("%s: already registered", name))
114 }
115 configAdapters[name] = adapter
116 caddy.RegisterModule(adapterModule{name, adapter})
117 }
118
119 // GetAdapter returns the adapter with the given name,
120 // or nil if one with that name is not registered.
121 func GetAdapter(name string) Adapter {
122 return configAdapters[name]
123 }
124
125 // adapterModule is a wrapper type that can turn any config
126 // adapter into a Caddy module, which has the benefit of being
127 // counted with other modules, even though they do not
128 // technically extend the Caddy configuration structure.
129 // See caddyserver/caddy#3132.
130 type adapterModule struct {
131 name string
132 Adapter
133 }
134
135 func (am adapterModule) CaddyModule() caddy.ModuleInfo {
136 return caddy.ModuleInfo{
137 ID: caddy.ModuleID("caddy.adapters." + am.name),
138 New: func() caddy.Module { return am },
139 }
140 }
141
142 var configAdapters = make(map[string]Adapter)