-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathserver.go
More file actions
81 lines (71 loc) · 2.17 KB
/
server.go
File metadata and controls
81 lines (71 loc) · 2.17 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
package http
import (
"fmt"
"net/http"
"sync"
"sync/atomic"
"time"
)
// HTTPRequestKeyProvider represents request key provider to extract a request field.
type HTTPRequestKeyProvider func(source interface{}) (string, error)
// HTTPRequestKeyProviders represents key providers
var HTTPRequestKeyProviders = make(map[string]HTTPRequestKeyProvider)
type Server struct {
http.Server
*httpHandler
trips map[string]*HTTPResponses
mux sync.Mutex
rotate bool
indexKeys []string
requestTemplate string
responseTemplate string
}
func (s *Server) Append(trips *HTTPServerTrips) {
s.mux.Lock()
defer s.mux.Unlock()
if len(s.trips) > 0 {
for k, v := range s.trips {
if _, ok := trips.Trips[k]; ok {
continue
}
trips.Trips[k] = v
}
}
s.httpHandler.handler = getServerHandler(&s.Server, s.httpHandler, trips)
}
// StartServer starts http request, the server has ability to replay recorded HTTP trips with https://github.com/viant/toolbox/blob/master/bridge/http_bridge_recording_util.go#L82
func StartServer(port int, trips *HTTPServerTrips, reqTemplate, respTemplate string) (*Server, error) {
err := trips.Init(reqTemplate, respTemplate)
if err != nil {
return nil, fmt.Errorf("failed to start http server :%v, %v", port, err)
}
var httpHandler = &httpHandler{
running: 1,
}
server := &Server{
rotate: trips.Rotate,
indexKeys: trips.IndexKeys,
httpHandler: httpHandler,
trips: trips.Trips,
Server: http.Server{Addr: fmt.Sprintf(":%v", port), Handler: httpHandler},
requestTemplate: reqTemplate,
responseTemplate: respTemplate,
}
httpHandler.handler = getServerHandler(&server.Server, httpHandler, trips)
errorNotification := make(chan bool, 1)
go func() {
fmt.Printf("Starting server on %v\n", port)
err = server.Server.ListenAndServe()
atomic.StoreInt32(&httpHandler.running, 0)
errorNotification <- true
if err != nil {
err = fmt.Errorf("failed to start http server on port %v, %v", port, err)
}
}()
//if there is error in starting server quite immediately
select {
case <-errorNotification:
case <-time.After(time.Second * 2):
}
return server, err
}