...
1 package gateway
2
3 import (
4 "fmt"
5 "net/http"
6 "path"
7 "strings"
8
9 "github.com/golang/glog"
10 "google.golang.org/grpc"
11 "google.golang.org/grpc/connectivity"
12 )
13
14
15 func swaggerServer(dir string) http.HandlerFunc {
16 return func(w http.ResponseWriter, r *http.Request) {
17 if !strings.HasSuffix(r.URL.Path, ".swagger.json") {
18 glog.Errorf("Not Found: %s", r.URL.Path)
19 http.NotFound(w, r)
20 return
21 }
22
23 glog.Infof("Serving %s", r.URL.Path)
24 p := strings.TrimPrefix(r.URL.Path, "/swagger/")
25 p = path.Join(dir, p)
26 http.ServeFile(w, r, p)
27 }
28 }
29
30
31
32 func allowCORS(h http.Handler) http.Handler {
33 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
34 if origin := r.Header.Get("Origin"); origin != "" {
35 w.Header().Set("Access-Control-Allow-Origin", origin)
36 if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
37 preflightHandler(w, r)
38 return
39 }
40 }
41 h.ServeHTTP(w, r)
42 })
43 }
44
45
46
47
48 func preflightHandler(w http.ResponseWriter, r *http.Request) {
49 headers := []string{"Content-Type", "Accept", "Authorization"}
50 w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ","))
51 methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"}
52 w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ","))
53 glog.Infof("preflight request for %s", r.URL.Path)
54 }
55
56
57 func healthzServer(conn *grpc.ClientConn) http.HandlerFunc {
58 return func(w http.ResponseWriter, r *http.Request) {
59 w.Header().Set("Content-Type", "text/plain")
60 if s := conn.GetState(); s != connectivity.Ready {
61 http.Error(w, fmt.Sprintf("grpc server is %s", s), http.StatusBadGateway)
62 return
63 }
64 fmt.Fprintln(w, "ok")
65 }
66 }
67
View as plain text