/
http.go
86 lines (70 loc) · 1.91 KB
/
http.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
80
81
82
83
84
85
86
package rpcserver
import (
"log"
"net/http"
"path"
"strings"
"github.com/elazarl/go-bindata-assetfs"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/lxlxw/s3-micro/pkg/swagger"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
gw "github.com/lxlxw/s3-micro/proto"
)
var (
ServerHttpPort string
HttpEndPoint string
)
// Run httpserver.
func RunHttpServer() (err error) {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// grpc server
EndPoint = ":" + ServerPort
gwmux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithInsecure()}
// Grpc to HTTP
err = gw.RegisterStoreApiServiceHandlerFromEndpoint(ctx, gwmux, EndPoint, opts)
if err != nil {
grpclog.Fatalf("Register handler err:%v\n", err)
}
HttpEndPoint = ":" + ServerHttpPort
// swagger ui
mux := http.NewServeMux()
mux.Handle("/", gwmux)
mux.HandleFunc("/swagger/", serveSwaggerFile)
serveSwaggerUI(mux)
log.Println("HTTP Listen success:", HttpEndPoint)
s := &http.Server{
Addr: HttpEndPoint,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mux.ServeHTTP(w, r)
}),
}
s.ListenAndServe()
return err
}
// Swagger json file, http://localhost:port/swagger/rpc.swagger.json
func serveSwaggerFile(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, "swagger.json") {
log.Printf("Not Found: %s", r.URL.Path)
http.NotFound(w, r)
return
}
p := strings.TrimPrefix(r.URL.Path, "/swagger/")
p = path.Join("rpc", p)
log.Printf("Serving swagger-file: %s", p)
http.ServeFile(w, r, p)
}
// Swagger ui, http://localhost:port/swagger-ui
func serveSwaggerUI(mux *http.ServeMux) {
fileServer := http.FileServer(&assetfs.AssetFS{
Asset: swagger.Asset,
AssetDir: swagger.AssetDir,
Prefix: "swagger-ui",
})
prefix := "/swagger-ui/"
mux.Handle(prefix, http.StripPrefix(prefix, fileServer))
}