forked from cloudfoundry/cli-plugin-repo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
62 lines (49 loc) · 1.1 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
package server
import (
"fmt"
"net"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
type RepoServer interface {
Serve()
Stop()
Port() string
}
type server struct {
port int
listener net.Listener
handles ServerHandles
}
func NewRepoServer(port int, addr string, handles ServerHandles) RepoServer {
listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", addr, port))
if err != nil {
panic(err)
}
return server{
port: port,
listener: listener,
handles: handles,
}
}
func (s server) registerHandlers() {
r := mux.NewRouter()
r.Methods("GET").Path("/list").HandlerFunc(s.handles.ListPlugins)
r.Methods("GET").Path("/").HandlerFunc(redirectBase)
http.Handle("/ui/", http.StripPrefix("/ui/", http.FileServer(http.Dir("ui"))))
http.Handle("/", r)
}
func redirectBase(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/ui", http.StatusFound)
}
func (s server) Serve() {
s.registerHandlers()
http.Serve(s.listener, nil)
}
func (s server) Stop() {
s.listener.Close()
}
func (s server) Port() string {
return strconv.Itoa(s.listener.Addr().(*net.TCPAddr).Port)
}