-
Notifications
You must be signed in to change notification settings - Fork 144
/
server.go
79 lines (64 loc) · 1.55 KB
/
server.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
package servertest
import (
"fmt"
"net"
"net/http"
"sync"
"github.com/Admiral-Piett/goaws/app/router"
log "github.com/sirupsen/logrus"
"github.com/Admiral-Piett/goaws/app"
"strings"
)
// Server is a fake SQS / SNS server for testing purposes.
type Server struct {
closed bool
handler http.Handler
listener net.Listener
mu sync.Mutex
}
// Quit closes down the server.
func (srv *Server) Quit() error {
srv.mu.Lock()
srv.closed = true
srv.mu.Unlock()
return srv.listener.Close()
}
// URL returns a URL for the server.
func (srv *Server) URL() string {
return "http://" + srv.listener.Addr().String()
}
// New starts a new server and returns it.
func New(addr string) (*Server, error) {
if addr == "" {
addr = "localhost:0"
}
localURL := strings.Split(addr, ":")
app.CurrentEnvironment.Host = localURL[0]
app.CurrentEnvironment.Port = localURL[1]
log.WithFields(log.Fields{
"host": app.CurrentEnvironment.Host,
"port": app.CurrentEnvironment.Port,
}).Info("URL Sarting to listen")
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, fmt.Errorf("cannot listen on localhost: %v", err)
}
if err != nil {
return nil, fmt.Errorf("cannot listen on localhost: %v", err)
}
srv := Server{listener: l, handler: router.New()}
go http.Serve(l, &srv)
return &srv, nil
}
func (srv *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
srv.mu.Lock()
closed := srv.closed
srv.mu.Unlock()
if closed {
hj := w.(http.Hijacker)
conn, _, _ := hj.Hijack()
conn.Close()
return
}
srv.handler.ServeHTTP(w, req)
}