/
request.go
78 lines (63 loc) · 1.68 KB
/
request.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
package langserver
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/x1unix/go-playground/pkg/goplay"
"go.uber.org/zap"
"github.com/x1unix/go-playground/pkg/analyzer"
)
type SuggestionRequest struct {
PackageName string `json:"packageName"`
Value string `json:"value"`
}
func (sr SuggestionRequest) Trim() SuggestionRequest {
return SuggestionRequest{
PackageName: strings.TrimSpace(sr.PackageName),
Value: strings.TrimSpace(sr.Value),
}
}
type ErrorResponse struct {
code int `json:"-"`
Error string `json:"error"`
}
func NewErrorResponse(err error) ErrorResponse {
return ErrorResponse{Error: err.Error(), code: http.StatusInternalServerError}
}
// Errorf creates error response
func Errorf(code int, format string, args ...interface{}) ErrorResponse {
return ErrorResponse{
code: code,
Error: fmt.Sprintf(format, args...),
}
}
func (r ErrorResponse) Write(w http.ResponseWriter) http.ResponseWriter {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(r.code)
if err := json.NewEncoder(w).Encode(r); err != nil {
zap.S().Error(err)
}
return w
}
type SuggestionsResponse struct {
Suggestions []*analyzer.CompletionItem `json:"suggestions"`
}
func (r SuggestionsResponse) Write(w http.ResponseWriter) {
WriteJSON(w, r)
}
type CompilerResponse struct {
Formatted string `json:"formatted,omitempty"`
Events []*goplay.CompileEvent `json:"events,omitempty"`
}
func WriteJSON(w http.ResponseWriter, i interface{}) {
data, err := json.Marshal(i)
if err != nil {
NewErrorResponse(err).Write(w)
return
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(data)
return
}