2023-08-03 10:40:02 +03:00
|
|
|
package swagger // import "go.unistack.org/micro-server-http/v4/handler/swagger"
|
2023-06-18 17:28:29 +03:00
|
|
|
|
|
|
|
import (
|
2023-08-03 10:40:02 +03:00
|
|
|
"context"
|
2023-06-18 17:28:29 +03:00
|
|
|
"io/fs"
|
|
|
|
"net/http"
|
|
|
|
|
2023-08-03 10:40:02 +03:00
|
|
|
httpsrv "go.unistack.org/micro-server-http/v4"
|
|
|
|
"go.unistack.org/micro/v4/server"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
Hook func([]byte) []byte
|
|
|
|
ErrorHandler func(ctx context.Context, s server.Handler, w http.ResponseWriter, r *http.Request, err error, status int)
|
2023-06-18 17:28:29 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// Handler append to generated swagger data from dst map[string]interface{}
|
2023-08-03 10:40:02 +03:00
|
|
|
var Handler = func(fsys fs.FS, hooks []Hook, h httpsrv.ErrorHandler) http.HandlerFunc {
|
2023-06-18 17:28:29 +03:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if r.Method != http.MethodGet {
|
2023-08-03 10:40:02 +03:00
|
|
|
h(r.Context())
|
2023-06-18 17:28:29 +03:00
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
path := r.URL.Path
|
|
|
|
if len(path) > 1 && path[0] == '/' {
|
|
|
|
path = path[1:]
|
|
|
|
}
|
|
|
|
|
|
|
|
buf, err := fs.ReadFile(fsys, path)
|
|
|
|
if err != nil {
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
_, _ = w.Write([]byte(err.Error()))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
_, _ = w.Write(buf)
|
|
|
|
}
|
|
|
|
}
|