/
exampleserver.go
105 lines (80 loc) · 2.35 KB
/
exampleserver.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/SKF/go-utility/v2/log"
"github.com/gorilla/mux"
"go.opencensus.io/plugin/ochttp"
"github.com/SKF/go-rest-utility/server/gorillamux"
"github.com/SKF/go-rest-utility/server/specification"
)
var exampleFS = os.DirFS(".")
func main() {
router := setupRouter()
httpServer := &http.Server{
Addr: ":8080",
Handler: &ochttp.Handler{Handler: router},
ReadTimeout: 30 * time.Second, //nolint:gomnd
WriteTimeout: 30 * time.Second, //nolint:gomnd
MaxHeaderBytes: 1 << 20, //nolint:gomnd
}
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
serverClosed := make(chan struct{}, 1)
go func() {
<-sigs
log.Info("Will try to exit gracefully")
close(serverClosed)
}()
go func() {
log.WithField("port", httpServer.Addr).Info("Will start to listen and serve")
if err := httpServer.ListenAndServe(); err != http.ErrServerClosed {
log.WithError(err).Error("HTTP server ListenAndServe")
sigs <- syscall.SIGTERM
}
}()
<-serverClosed
log.Info("Exiting")
}
func setupRouter() *mux.Router {
router := mux.NewRouter()
api := router.PathPrefix("/").Subrouter()
docs := router.PathPrefix("/docs").Subrouter()
err := SetupSwaggerEndpoints(docs, api)
if err != nil {
log.Fatal(err)
}
return router
}
func SetupSwaggerEndpoints(docsEndpoints, apiEndpoints *mux.Router) error {
route := docsEndpoints.NewRoute().PathPrefix("/swagger/")
swaggerURL, err := route.URLPath()
if err != nil {
return err
}
endpointURL, err := apiEndpoints.Path("/").BuildOnly().URLPath()
if err != nil {
return err
}
swaggerFS := &specification.SwaggerFS{
FS: exampleFS,
SwaggerURLPrefix: swaggerURL.Path,
APIEndpointsURLPrefix: endpointURL.Path,
NotFoundHandler: gorillamux.NotFoundHandler(),
MethodNotAllowedHandler: gorillamux.MethodNotFoundHandler(apiEndpoints),
}
opts := []specification.Option{
specification.WithIndexFilePath("docs/index.html"),
specification.WithSwaggerUIDirectory("docs"),
specification.WithOpenAPIPath("oas.yaml"),
specification.WithSwaggerInitJSPath("docs/swagger-initializer.js"),
}
route.Handler(swaggerFS.Handler(opts...))
docsEndpoints.NewRoute().
Path("/swagger").
Handler(http.RedirectHandler(swaggerURL.Path, http.StatusMovedPermanently))
return nil
}