-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
82 lines (67 loc) · 1.75 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package model
import (
"bytes"
"strings"
"text/template"
"github.com/apex/log"
"github.com/emicklei/proto"
)
type Handler struct {
// Name (full path) for the generated file
Name string
// Namespace to use in file
Namespace string
// Routes
RPCs []*proto.RPC
}
func NewHandler(name, namespace string, rpcs []*proto.RPC) *Handler {
return &Handler{
Name: name,
Namespace: namespace,
RPCs: rpcs,
}
}
func (f *Handler) Filename() string {
return f.Name + "Handlers.php"
}
func (f *Handler) Bytes() []byte {
funcMap := template.FuncMap{
"comment": comment,
}
tpl, err := template.New("render-php81-handler").Funcs(funcMap).Parse(handlerTemplate)
if err != nil {
log.WithError(err).Errorf("error loading template for %s", f.Filename())
return nil
}
out := new(bytes.Buffer)
err = tpl.Execute(out, f)
if err != nil {
log.WithError(err).Errorf("error rendering template for %s", f.Filename())
return nil
}
sOut := out.String()
sOut = strings.ReplaceAll(sOut, "\n\n\n", "\n\n")
sOut = strings.ReplaceAll(sOut, "-\n", "")
sOut = strings.ReplaceAll(sOut, "\n-", "")
sOut = strings.TrimSpace(sOut) + "\n"
return []byte(sOut)
}
const handlerTemplate = `
<?php
namespace {{ .Namespace }};
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
abstract class {{ .Name }}Handlers implements {{ .Name }}
{
{{- range .RPCs }}
/** {{ .Comment | comment }} */
public function handle{{ .Name }}(Request $request, Response $response, array $args): Response
{
$params = new {{ .RequestType }}($request);
$data = $this->{{ .Name }}($params);
$response->getBody()->write(json_encode($data));
return $response->withHeader('Content-Type', 'application/json');
}
-{{- end }}
}
`