User Tools

Site Tools


Response

response.go
package main
 
import (
    "encoding/json"
    "errors"
    "fmt"
)
 
type Response struct {
	Error   bool        `json:"error"`
        // ErrorCode   int64        `json:"errorCode"`
	Result  interface{} `json:"result,omitempty"`
	Message string      `json:"message,omitempty"`
}
 
func SendErrorResponse(err error) {
    var response Response
    response.Error = true
    if (err != nil) {
        response.Message = err.Error()
    }
    jsonBin, _ := json.MarshalIndent(response, "", "  ")
    fmt.Println(string(jsonBin))
}
 
func SendGoodResponse(result interface{})  {
    var response Response
    response.Result = result
    jsonBin, _ := json.MarshalIndent(response, "", "  ")
    fmt.Println(string(jsonBin))
}
 
type ExampleRes struct {
    Ident   int64       `json:"ident"`
    Name    string      `json:"name"`
}
 
func main() {
    SendErrorResponse(errors.New("wrong parameter foo"))
 
    someResp := ExampleRes{ Ident: 12345, Name: "qwerty" }
    SendGoodResponse(someResp)
}

Typescript

response.ts
export interface Response {
  result: string
  error: boolean
  message: string
}

Out

$ go run response.go

{
  "error": true,
  "message": "wrong parameter foo"
}


{
  "error": false,
  "result": {
    "ident": 123,
    "name": "qwerty"
  }
}