config minmod | error 'AddArgument' + 'MarshalJSON'

This commit is contained in:
Adrien Marquès 2018-05-20 10:40:04 +02:00
parent c0a72e7e3d
commit 5438680867
2 changed files with 41 additions and 4 deletions

View File

@ -5,9 +5,9 @@ import (
"os"
)
// LoadConfig builds a struct representation of the
// LoadConfig builds a structured representation of the
// configuration file located at @path
// The structure checks for most format errors
// The struct definition checks for most format errors
func LoadConfig(path string) (*controller, error) {
/* (1) Extract data

View File

@ -1,6 +1,7 @@
package gfw
import (
"encoding/json"
"fmt"
)
@ -43,6 +44,42 @@ var (
InvalidDefaultParam = &Err{402, "invalid default param", nil}
)
func (e Err) Error() string {
return fmt.Sprintf("[%d] %s", e.Code, e.Reason)
// BindArgument adds an argument to the error
// to be displayed back to API caller
func (e *Err) BindArgument(arg interface{}) {
/* (1) Make slice if not */
if e.Arguments == nil {
e.Arguments = make([]interface{}, 0)
}
/* (2) Append argument */
e.Arguments = append(e.Arguments, arg)
}
// Implements 'error'
func (e Err) Error() string {
return fmt.Sprintf("[%d] %s", e.Code, e.Reason)
}
// Implements json.Marshaler
func (e Err) MarshalJSON() ([]byte, error) {
var json_arguments string
/* (1) Marshal 'Arguments' if set */
if e.Arguments != nil && len(e.Arguments) > 0 {
arg_representation, err := json.Marshal(e.Arguments)
if err == nil {
json_arguments = fmt.Sprintf(",\"arguments\":%s", arg_representation)
}
}
/* (2) Render JSON manually */
return []byte(fmt.Sprintf("{\"error\":%d,\"reason\":\"%s\"%s}", e.Code, e.Reason, json_arguments)), nil
}