forked from foomo/gotsrpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gotsrpc.go
223 lines (194 loc) · 6.49 KB
/
gotsrpc.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
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
package gotsrpc
import (
"context"
"encoding/json"
"fmt"
"go/ast"
"go/parser"
"go/token"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"strings"
"time"
"github.com/foomo/gotsrpc/config"
"github.com/pkg/errors"
"github.com/ugorji/go/codec"
)
const contextStatsKey = "gotsrpcStats"
func GetCalledFunc(r *http.Request, endPoint string) string {
return strings.TrimPrefix(r.URL.Path, endPoint+"/")
}
func ErrorFuncNotFound(w http.ResponseWriter) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("method not found"))
}
func ErrorCouldNotLoadArgs(w http.ResponseWriter) {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("could not load args"))
}
func ErrorMethodNotAllowed(w http.ResponseWriter) {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("you gotta POST"))
}
func LoadArgs(args interface{}, callStats *CallStats, r *http.Request) error {
start := time.Now()
handle := getHandlerForContentType(r.Header.Get("Content-Type")).handle
if errDecode := codec.NewDecoder(r.Body, handle).Decode(args); errDecode != nil {
return errors.Wrap(errDecode, "could not decode arguments")
}
if callStats != nil {
callStats.Unmarshalling = time.Now().Sub(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
}
func RequestWithStatsContext(r *http.Request) *http.Request {
stats := &CallStats{}
return r.WithContext(context.WithValue(r.Context(), contextStatsKey, stats))
}
func GetStatsForRequest(r *http.Request) *CallStats {
value := r.Context().Value(contextStatsKey)
if value == nil {
return nil
}
return value.(*CallStats)
}
func ClearStats(r *http.Request) {
*r = *r.WithContext(context.WithValue(r.Context(), contextStatsKey, nil))
}
// Reply despite the fact, that 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) {
writer := newResponseWriterWithLength(w)
serializationStart := time.Now()
clientHandle := getHandlerForContentType(r.Header.Get("Content-Type"))
writer.Header().Set("Content-Type", clientHandle.contentType)
if errEncode := codec.NewEncoder(writer, clientHandle.handle).Encode(response); errEncode != nil {
http.Error(w, "could not encode data to accepted format", http.StatusInternalServerError)
return
}
if stats != nil {
stats.ResponseSize = writer.length
stats.Marshalling = time.Now().Sub(serializationStart)
}
}
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, error) {
if gomod.Name != "" && strings.HasPrefix(packageName, gomod.Name) {
fset := token.NewFileSet()
dir := strings.Replace(packageName, gomod.Name, gomod.Path, 1)
return parser.ParseDir(fset, dir, parserExcludeFiles, parser.AllErrors)
}
errorStrings := map[string]string{}
for _, goPath := range goPaths {
fset := token.NewFileSet()
var dir string
if gomod.ModFile != nil {
for _, req := range gomod.ModFile.Require {
if req.Syntax.Token[0] == packageName {
packageName = req.Mod.String()
break
}
}
for _, rep := range gomod.ModFile.Replace {
if strings.HasPrefix(packageName, rep.Old.String()) {
if strings.HasPrefix(rep.New.String(), ".") || strings.HasPrefix(rep.New.String(), "/") {
dir := strings.Replace(packageName, rep.Old.String(), filepath.Join(gomod.Path, rep.New.String()), 1)
return parser.ParseDir(fset, dir, parserExcludeFiles, parser.AllErrors)
} else {
packageName = rep.New.String()
break
}
}
}
dir = path.Join(goPath, "pkg", "mod", packageName)
} else 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, nil
}
errorStrings[dir] = err.Error()
}
return nil, errors.New("could not parse dir for package name: " + packageName + " in goPaths " + strings.Join(goPaths, ", ") + " : " + fmt.Sprint(errorStrings))
}
type byLen []string
func (a byLen) Len() int {
return len(a)
}
func (a byLen) Less(i, j int) bool {
return len(a[i]) > len(a[j])
}
func (a byLen) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func parsePackage(goPaths []string, gomod config.Namespace, packageName string) (pkg *ast.Package, err error) {
pkgs, 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))
for iGoPath := range goPaths {
sortedGoPaths[iGoPath] = goPaths[iGoPath]
}
sort.Sort(byLen(sortedGoPaths))
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 {
return pkg, nil
}
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 {
return pkg, nil
}
}
}
}
}
foundPackages = append(foundPackages, pkgName)
}
return nil, errors.New("package \"" + packageName + "\" not found in " + strings.Join(foundPackages, ", ") + " looking in go paths" + strings.Join(goPaths, ", "))
}