-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.go
More file actions
78 lines (62 loc) · 1.91 KB
/
runtime.go
File metadata and controls
78 lines (62 loc) · 1.91 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
package mason
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/tailbits/mason/model"
)
type RouteHandler interface {
Handle(method string, path string, handler WebHandler, mws ...func(WebHandler) WebHandler)
}
type WebResponder interface {
Respond(ctx context.Context, w http.ResponseWriter, data any, status int) error
}
type Runtime interface {
RouteHandler
WebResponder
}
// ==========================================================================
// HTTPRuntime is a concrete implementation of the Runtime interface for HTTP-based applications.
var _ Runtime = (*HTTPRuntime)(nil)
type HTTPRuntime struct {
*http.ServeMux
}
func (r *HTTPRuntime) Handle(method string, path string, handler WebHandler, mws ...func(WebHandler) WebHandler) {
r.HandleFunc(fmt.Sprintf("%s %s", method, path), func(w http.ResponseWriter, req *http.Request) {
if req.Method != method {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
ctx := req.Context()
if err := handler(ctx, w, req); err != nil {
var fe model.ValidationError
if errors.As(err, &fe) {
// Return well-formatted validation errors
if err := r.Respond(ctx, w, fe, http.StatusUnprocessableEntity); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
}
func (r *HTTPRuntime) Respond(ctx context.Context, w http.ResponseWriter, data any, status int) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if data != nil {
if err := json.NewEncoder(w).Encode(data); err != nil {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusInternalServerError)
return fmt.Errorf("failed to encode response data: %w", err)
}
}
return nil
}
func NewHTTPRuntime() *HTTPRuntime {
return &HTTPRuntime{
ServeMux: http.NewServeMux(),
}
}