signald-go/tools/generator/requests.go.tmpl

67 lines
1.8 KiB
Cheetah

package {{.Version}}
// DO NOT EDIT: this file is automatically generated by ./tools/generator in this repo
import ({{if .Responses}}
"encoding/json"
"fmt"
"log"{{end}}
"math/rand"
"gitlab.com/signald/signald-go/signald"
)
{{range $type, $action := .Actions}}
{{if ne $action.Request ""}}
{{if ne $action.Doc ""}}// Submit: {{$action.Doc}}{{end}}
func (r *{{$action.Request}}) Submit(conn *signald.Signald) ({{if ne $action.Response ""}}response {{$action.Response}}, err {{end}}error) {
r.Version = "{{$.Version}}"
{{else}}
{{if ne $action.Doc ""}}// {{$action.FnName}}: {{$action.Doc}}{{end}}
func {{$action.FnName}}(conn *signald.Signald) ({{if ne $action.Response ""}}response {{$action.Response}}, {{end}}err error) {
r := Request{Version: "{{.Version}}"}
{{end}} r.Type = "{{$type}}"
if(r.ID == "") {
r.ID = generateID()
}
{{if ne $action.Response ""}}
err = conn.RawRequest(r)
if err != nil {
log.Println("signald-go: error submitting request to signald")
return response, err
}
responseChannel := conn.GetResponseListener(r.ID)
defer conn.CloseResponseListener(r.ID)
rawResponse := <- responseChannel
if rawResponse.Error != nil {
err = fmt.Errorf("signald error: %s", string(rawResponse.Error))
return
}
err = json.Unmarshal(rawResponse.Data, &response)
if err != nil {
rawResponseJson, _ := rawResponse.Data.MarshalJSON()
log.Println("signald-go: error unmarshalling response from signald of type", rawResponse.Type, string(rawResponseJson))
return response, err
}
return response, nil
{{else}}
return conn.RawRequest(r)
{{end}}
}
{{end}}
const idsize = 10
var charset = []rune("abcdefghijklmnopqrstuvwxyz0123456789")
func generateID() string {
id := make([]rune, idsize)
for i := range id {
id[i]= charset[rand.Intn(len(charset))]
}
return string(id)
}