-
Notifications
You must be signed in to change notification settings - Fork 1
/
mock_service.go
73 lines (61 loc) · 2.4 KB
/
mock_service.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
package mockservice
import (
"errors"
"net/http"
"strings"
)
var (
// ErrRegistrationEndpointConflict happens when attempting to register a mock endpoint that is the same as the registration endpoint
ErrRegistrationEndpointConflict = errors.New("Endpoint conflicts with registration endpoint")
// ErrEmptyRegistrationEndpoint happens when an empty registration endpoint is used to create a new mock service
ErrEmptyRegistrationEndpoint = errors.New("Empty registration endpoint provided")
)
// MockService is a service that allows endpoints to be mocked
type MockService struct {
mockRegistrationEndpoint string
registrationService *RegistrationService
endpointService *EndpointService
}
// Conf is a quick and easy way to configure the mock service with the registration endpoint and pre-determined mock endpoints
type Conf struct {
RegistrationEndpoint string `json:"regisgtrationEndpoint" xml:"registrationEndpoint"`
Endpoints []*MockEndpoint `json:"endpoints" xml:"endpoints"`
}
// New creates a mock service
func New(mockRegistrationEndpoint string) (*MockService, error) {
if strings.Trim(mockRegistrationEndpoint, " ") == "" {
return nil, ErrEmptyRegistrationEndpoint
}
mockEndpoints := NewEndpoints()
return &MockService{
mockRegistrationEndpoint: mockRegistrationEndpoint,
registrationService: NewRegistrationService(mockEndpoints),
endpointService: NewEndpointService(mockEndpoints),
}, nil
}
// NewWithConf creates a mock service with a pre-determined configuration
func NewWithConf(conf *Conf) (*MockService, error) {
if strings.Trim(conf.RegistrationEndpoint, " ") == "" {
return nil, ErrEmptyRegistrationEndpoint
}
mockEndpoints := NewEndpoints()
if err := mockEndpoints.Load(conf.Endpoints); err != nil {
return nil, err
}
registrationService := NewRegistrationService(mockEndpoints)
endpointService := NewEndpointService(mockEndpoints)
m := &MockService{
mockRegistrationEndpoint: conf.RegistrationEndpoint,
endpointService: endpointService,
registrationService: registrationService,
}
return m, nil
}
// ServeHTTP serves HTTP requests to the registration and mock endpoints
func (m *MockService) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodPost && req.URL.Path == m.mockRegistrationEndpoint {
m.registrationService.ServeHTTP(w, req)
return
}
m.endpointService.ServeHTTP(w, req)
}