Implement `echo` action (#18)

This commit is contained in:
Maxim Baz 2018-04-19 23:53:34 +02:00 committed by GitHub
parent d24b54e8b6
commit ebfe600b0b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 34 additions and 19 deletions

View File

@ -182,3 +182,22 @@ Get the decrypted contents of a specific file.
}
}
```
### Echo
Send the `echoResponse` in the request as a response.
#### Request
```
{
"action": "echo",
"echoResponse": <anything>
}
```
#### Response
```
<echoResponse>
```

View File

@ -22,10 +22,11 @@ type settings struct {
}
type request struct {
Action string `json:"action"`
Settings settings `json:"settings"`
File string `json:"file"`
Store string `json:"store"`
Action string `json:"action"`
Settings settings `json:"settings"`
File string `json:"file"`
Store string `json:"store"`
EchoResponse interface{} `json:"echoResponse"`
}
// Process handles browser request
@ -61,6 +62,8 @@ func Process() {
listFiles(request)
case "fetch":
fetchDecryptedContents(request)
case "echo":
response.SendRaw(request.EchoResponse)
default:
log.Errorf("Received a browser request with an unknown action: %+v", request)
response.SendErrorAndExit(

View File

@ -64,7 +64,7 @@ func MakeFetchResponse() *FetchResponse {
// SendOk sends a success response to the browser extension in the predefined json format
func SendOk(data interface{}) {
send(&okResponse{
SendRaw(&okResponse{
Status: "ok",
Version: version.Code,
Data: data,
@ -73,7 +73,7 @@ func SendOk(data interface{}) {
// SendErrorAndExit sends an error response to the browser extension in the predefined json format and exits with the specified exit code
func SendErrorAndExit(errorCode errors.Code, params *map[errors.Field]string) {
send(&errorResponse{
SendRaw(&errorResponse{
Status: "error",
Code: errorCode,
Version: version.Code,
@ -83,24 +83,17 @@ func SendErrorAndExit(errorCode errors.Code, params *map[errors.Field]string) {
errors.ExitWithCode(errorCode)
}
func send(data interface{}) {
switch data.(type) {
case *okResponse:
case *errorResponse:
break
default:
log.Fatalf("Only data of type OkResponse and ErrorResponse is allowed to be sent to the browser extension, attempted to send: %+v", data)
}
// SendRaw sends a raw data to the browser extension
func SendRaw(response interface{}) {
var bytesBuffer bytes.Buffer
if err := json.NewEncoder(&bytesBuffer).Encode(data); err != nil {
log.Fatal("Unable to encode data for sending: ", err)
if err := json.NewEncoder(&bytesBuffer).Encode(response); err != nil {
log.Fatal("Unable to encode response for sending: ", err)
}
if err := binary.Write(os.Stdout, binary.LittleEndian, uint32(bytesBuffer.Len())); err != nil {
log.Fatal("Unable to send the length of the response data: ", err)
log.Fatal("Unable to send the length of the response: ", err)
}
if _, err := bytesBuffer.WriteTo(os.Stdout); err != nil {
log.Fatal("Unable to send the response data: ", err)
log.Fatal("Unable to send the response: ", err)
}
}