@@ -93,26 +93,34 @@ func (p *ConfigParser) Get(section, option string) (string, error) {
9393 return "" , err
9494 }
9595
96- return value .( string ), nil
96+ return assertValue [ string ]( value )
9797}
9898
9999func (p * ConfigParser ) get (section , option string ) (string , error ) {
100- if ! p . HasSection ( section ) {
101- if ! p .isDefaultSection (section ) {
102- return "" , getNoSectionError ( section )
103- }
104- if value , err := p . defaults . Get ( option ); err != nil {
105- return "" , getNoOptionError ( section , option )
106- } else {
107- return value , nil
108- }
109- } else if value , err := p . config [ section ]. Get ( option ); err == nil {
110- return value , nil
111- } else if value , err := p . defaults . Get ( option ); err == nil {
112- return value , nil
100+ // Special case.
101+ if p .isDefaultSection (section ) {
102+ return p . defaults . Get ( option )
103+ }
104+
105+ s , ok := p . config [ section ]
106+ if ! ok {
107+ return "" , getNoSectionError ( section )
108+ }
109+
110+ v , err := s . Get ( option )
111+ if err == nil {
112+ return v , nil
113113 }
114114
115- return "" , getNoOptionError (section , option )
115+ // If given section has no option, fallback to check default.
116+ dv , derr := p .defaults .Get (option )
117+ if derr != nil {
118+ // If option is not present in default section, return
119+ // original error with the requested section name.
120+ return "" , err
121+ }
122+
123+ return dv , nil
116124}
117125
118126// ItemsWithDefaults returns a copy of the named section Dict including
@@ -185,7 +193,7 @@ func (p *ConfigParser) GetInt64(section, option string) (int64, error) {
185193 return 0 , err
186194 }
187195
188- return value .( int64 ), nil
196+ return assertValue [ int64 ]( value )
189197}
190198
191199// GetFloat64 returns float64 representation of the named option.
@@ -204,7 +212,7 @@ func (p *ConfigParser) GetFloat64(section, option string) (float64, error) {
204212 return 0 , err
205213 }
206214
207- return value .( float64 ), nil
215+ return assertValue [ float64 ]( value )
208216}
209217
210218// GetBool returns bool representation of the named option.
@@ -223,7 +231,7 @@ func (p *ConfigParser) GetBool(section, option string) (bool, error) {
223231 return false , err
224232 }
225233
226- return value .( bool ), nil
234+ return assertValue [ bool ]( value )
227235}
228236
229237// RemoveSection removes given section from the ConfigParser.
@@ -316,3 +324,16 @@ func defaultGetBool(value string) (any, error) {
316324
317325 return booleanValue , nil
318326}
327+
328+ // assertValue tries value assertion to the given type, returns error if unsuccessful.
329+ func assertValue [T ~ string | ~ int64 | ~ float64 | ~ bool ](value any ) (T , error ) {
330+ v , ok := value .(T )
331+ if ok {
332+ return v , nil
333+ }
334+
335+ // Default value of the type.
336+ var d T
337+
338+ return d , fmt .Errorf ("assertion to %T failed: incorrect value %q" , d , value )
339+ }
0 commit comments