package sshAPI import ( "encoding/json" "fmt" "github.com/sirupsen/logrus" ) // APIError : Structure for holding a response from the sshapi http router type APIError struct { APIVer string `json:"api_ver"` ConnectionID string `json:"connection_id"` Data struct { Host string `json:"host"` Command string `json:"command"` Prompt string `json:"prompt"` RePrompt string `json:"re_prompt"` Timeout int `json:"timeout"` Response string `json:"response"` Platform string `json:"platform"` UserInfo struct { Username string `json:"username"` } `json:"user_info"` } `json:"data"` Err string `json:"error"` Success bool `json:"success"` } // Error : Returns a string of the error func (a APIError) Error() string { p := a.Data.Prompt if a.Data.RePrompt != "" { p = a.Data.RePrompt } return fmt.Sprintf("error executing command: '%s'; prompt: '%s'; response: '%s', error: '%s'", a.Data.Command, p, a.Data.Response, a.Err) } // UnmarshalAPIError : Parses a raw response from the API in to a structure and returns it if it can, otherwise returns nil // Sample for usage: // res, err := PostCommand("blah", "# ", 30) // if err != nil { // e := UnmarshalAPIError([]byte(*res.Response)); e != nil { // return e // } // return err // } func UnmarshalAPIError(raw []byte) error { log := logrus.New() log.Info(string(raw)) e := new(APIError) if err := json.Unmarshal(raw, e); err == nil { // Only consider this a successful unmarshal if we have all the required data if e.Data.Command != "" && e.Data.Response != "" && e.Err != "" { if e.Data.Prompt != "" || e.Data.RePrompt != "" { return e } } } return nil }