-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathgotsrpc.go
More file actions
240 lines (214 loc) · 7.01 KB
/
gotsrpc.go
File metadata and controls
240 lines (214 loc) · 7.01 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package gotsrpc
import (
"encoding/json"
"fmt"
"go/ast"
"go/parser"
"go/token"
"net/http"
"os"
"path"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/foomo/gotsrpc/v2/config"
)
func GetCalledFunc(r *http.Request, endPoint string) string {
return strings.TrimPrefix(r.URL.Path, endPoint+"/")
}
func LoadArgs(args interface{}, callStats *CallStats, r *http.Request) error {
var start time.Time
if callStats != nil {
start = time.Now()
}
ch := getHandlerForContentType(r.Header.Get("Content-Type"))
dec := ch.getDecoder(r.Body)
errDecode := dec.Decode(args)
ch.putDecoder(dec)
if errDecode != nil {
return errors.Wrap(errDecode, "could not decode arguments")
}
if callStats != nil {
callStats.Unmarshalling = time.Since(start)
callStats.RequestSize = int(r.ContentLength)
}
return nil
}
func loadArgs(args interface{}, jsonBytes []byte) error {
if err := json.Unmarshal(jsonBytes, &args); err != nil {
return err
}
return nil
}
// Reply although this is a public method - do not call it, it will be called by generated code
func Reply(response []interface{}, stats *CallStats, r *http.Request, w http.ResponseWriter) error {
var errorIndices []int
for i, v := range response {
if er, ok := v.(*errorReply); ok {
errorIndices = append(errorIndices, i)
response[i] = er.err
}
}
var serializationStart time.Time
if stats != nil {
serializationStart = time.Now()
}
ch := getHandlerForContentType(r.Header.Get("Content-Type"))
w.Header().Set("Content-Type", ch.contentType)
if ch.beforeEncodeReply != nil {
if err := ch.beforeEncodeReply(&response, errorIndices); err != nil {
return errors.Wrap(err, "error during before encoder reply")
}
}
buf := getBuffer()
defer putBuffer(buf)
enc := ch.getEncoder(buf)
err := enc.Encode(response)
ch.putEncoder(enc)
if err != nil {
return errors.Wrap(err, "could not encode data to accepted format")
}
w.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
if _, err := w.Write(buf.Bytes()); err != nil {
return errors.Wrap(err, "could not write response")
}
if stats != nil {
stats.ResponseSize = buf.Len()
stats.Marshalling = time.Since(serializationStart)
for _, i := range errorIndices {
if v, ok := response[i].(error); ok && v != nil {
if !reflect.ValueOf(v).IsZero() {
stats.ErrorCode = 1
stats.ErrorType = fmt.Sprintf("%T", v)
stats.ErrorMessage = v.Error()
if v, ok := v.(interface {
ErrorCode() int
}); ok {
stats.ErrorCode = v.ErrorCode()
}
}
}
}
}
return nil
}
func parserExcludeFiles(info os.FileInfo) bool {
return !strings.HasSuffix(info.Name(), "_test.go")
}
func parseDir(goPaths []string, gomod config.Namespace, packageName string) (map[string]*ast.Package, *token.FileSet, error) {
if gomod.Name != "" && strings.HasPrefix(packageName, gomod.Name) {
fset := token.NewFileSet()
dir := strings.Replace(packageName, gomod.Name, gomod.Path, 1)
pkgs, err := parser.ParseDir(fset, dir, parserExcludeFiles, parser.DeclarationErrors|parser.AllErrors)
return pkgs, fset, err
}
errorStrings := map[string]string{}
for _, goPath := range goPaths {
var dir string
fset := token.NewFileSet()
if gomod.ModFile != nil {
for _, rep := range gomod.ModFile.Replace {
if packageName == rep.Old.Path || strings.HasPrefix(packageName, rep.Old.Path+"/") {
if strings.HasPrefix(rep.New.String(), ".") || strings.HasPrefix(rep.New.Path, "/") {
trace("replacing package with local dir", packageName, rep.Old.String(), rep.New.String())
dir = strings.Replace(packageName, rep.Old.Path, filepath.Join(gomod.Path, rep.New.Path), 1)
} else {
trace("replacing package", packageName, rep.Old.String(), rep.New.String())
dir = strings.TrimSuffix(path.Join(goPath, "pkg", "mod", rep.New.String(), strings.TrimPrefix(packageName, rep.Old.Path)), "/")
}
break
}
}
if dir == "" {
for _, req := range gomod.ModFile.Require {
if packageName == req.Mod.Path || strings.HasPrefix(packageName, req.Mod.Path+"/") {
trace("resolving mod package", packageName, req.Mod.String())
dir = strings.TrimSuffix(path.Join(goPath, "pkg", "mod", req.Mod.String(), strings.TrimPrefix(packageName, req.Mod.Path)), "/")
break
}
}
}
}
if dir == "" {
if strings.HasSuffix(goPath, "vendor") {
dir = path.Join(goPath, packageName)
} else {
dir = path.Join(goPath, "src", packageName)
}
}
pkgs, err := parser.ParseDir(fset, dir, parserExcludeFiles, parser.AllErrors)
if err == nil {
return pkgs, fset, nil
}
errorStrings[dir] = err.Error()
}
return nil, nil, errors.New("could not parse dir for package name: " + packageName + " in goPaths " + strings.Join(goPaths, ", ") + " : " + fmt.Sprint(errorStrings))
}
func parsePackage(goPaths []string, gomod config.Namespace, packageName string) (pkg *ast.Package, err error) {
pkgs, fset, err := parseDir(goPaths, gomod, packageName)
if err != nil {
return nil, errors.New("could not parse package " + packageName + ": " + err.Error())
}
packageNameParts := strings.Split(packageName, "/")
if len(packageNameParts) == 0 {
return nil, errors.New("invalid package name given")
}
strippedPackageName := packageNameParts[len(packageNameParts)-1]
if len(pkgs) == 1 {
for _, v := range pkgs {
strippedPackageName = v.Name
break
}
}
var foundPackages []string
sortedGoPaths := make([]string, len(goPaths))
copy(sortedGoPaths, goPaths)
sort.Sort(byLen(sortedGoPaths))
var parsedPkg *ast.Package
Loop:
for pkgName, pkg := range pkgs {
// fmt.Println("---------------------> got", pkgName, "looking for", packageName, strippedPackageName)
// fmt.Println(goPaths)
// if pkgName == "stripe" {
// //spew.Dump(pkg)
// for pkgFile, pkg := range pkg.Files {
// fmt.Println("file = ", pkgFile)
// spew.Dump(pkg)
// }
// }
if pkgName == strippedPackageName {
parsedPkg = pkg
break
}
for pkgFile := range pkg.Files {
for _, goPath := range sortedGoPaths {
// fmt.Println("::::::::::::::::::::::::::::::::", iGoPath, goPath)
prefix := goPath + "/" // + "/src/"
if strings.HasPrefix(pkgFile, prefix) && !strings.HasSuffix(pkgFile, "_test.go") && !strings.HasSuffix(pkgFile, "_generator.go") {
trimmedFilename := strings.TrimPrefix(pkgFile, prefix)
parts := strings.Split(trimmedFilename, "/")
if len(parts) > 1 {
parts = parts[0 : len(parts)-1]
// fmt.Println(">>>>>>", strings.Join(parts, "/"))
// fmt.Println("==========>", pkgFile, prefix)
if strings.Join(parts, "/") == packageName {
parsedPkg = pkg
break Loop
}
}
}
}
}
foundPackages = append(foundPackages, pkgName)
}
if parsedPkg == nil {
return nil, errors.New("package \"" + packageName + "\" not found in " + strings.Join(foundPackages, ", ") + " looking in go paths" + strings.Join(goPaths, ", "))
}
// create new package with resolved objects
resolvedPkg, _ := ast.NewPackage(fset, parsedPkg.Files, nil, nil) // ignore error
return resolvedPkg, nil
}