-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
195 lines (182 loc) · 7.28 KB
/
router.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//go:generate oapi-codegen -package=app_openapi -generate types -o ../app_openapi/types.gen.go ../app_openapi/openapi.yaml
//go:generate oapi-codegen -package=app_openapi -generate chi-server -o ../app_openapi/chi_server.gen.go ../app_openapi/openapi.yaml
//go:generate oapi-codegen -package=app_openapi -generate spec -o ../app_openapi/spec.gen.go ../app_openapi/openapi.yaml
// Package router based on Chi server boilerplate generated by https://github.com/deepmap/oapi-codegen
// guided by oapi-codegen/examples/petstore-expanded/chi/petstore.go
package router
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/go-chi/chi"
chi_middleware "github.com/go-chi/chi/middleware"
api "github.com/nj-eka/shurl/api/app_openapi"
"github.com/nj-eka/shurl/app"
"github.com/nj-eka/shurl/config"
cu "github.com/nj-eka/shurl/internal/contexts"
"github.com/nj-eka/shurl/internal/errs"
"github.com/nj-eka/shurl/internal/logging"
"github.com/sirupsen/logrus"
"html/template"
"net/http"
"path/filepath"
"time"
)
var _ api.ServerInterface = (*AppRouter)(nil)
type AppRouter struct {
http.Handler
a *app.App
cfg *config.RouterConfig
}
func NewAppRouter(ctx context.Context, a *app.App, cfg *config.RouterConfig) (*AppRouter, error) {
ctx = cu.BuildContext(ctx, cu.AddContextOperation("router.init"), errs.SetDefaultErrsKind(errs.KindRouter), errs.SetDefaultErrsSeverity(errs.SeverityCritical))
logging.Msg(ctx).Debugf("router config: %v", cfg)
art := &AppRouter{a: a, cfg: cfg}
r := chi.NewRouter()
// middlewares
r.Use(chi_middleware.RequestID)
r.Use(chi_middleware.RealIP)
r.Use(NewStructuredLogger(logrus.StandardLogger()))
r.Use(chi_middleware.Recoverer)
//r.Use(chi_middleware.URLFormat)
swagger, err := api.GetSwagger()
if err != nil {
return nil, errs.E(ctx, fmt.Errorf("loading swagger spec failed: %w", err))
}
//swagger.Servers = nil
//r.Use(oapi_middleware.OapiRequestValidator(swagger)) // to check all requests against the OpenAPI schema + cut off everything else including !temporary! frontend screwed here for demo need (=
// add openapi (swagger) ui frontend
r.Get("/openapi/swagger.json", func(w http.ResponseWriter, r *http.Request) {
ctx := cu.BuildContext(r.Context(), cu.AddContextOperation("openapi"), errs.SetDefaultErrsKind(errs.KindRouter))
//if data, err := swagger.MarshalJSON(); err != nil {
// logging.LogError(ctx, fmt.Errorf("marshaling swagger failed: %w", err))
//} else {
// logging.Msg(ctx).Debugln(string(data))
//}
if err = json.NewEncoder(w).Encode(swagger); err != nil {
logging.LogError(ctx, fmt.Errorf("marshaling swagger failed: %w", err))
}
})
r.Get("/openapi", art.GetOpenAPI)
// frontend is just a start index page + openapi ui (added here for app + api demonstration purposes)
// add frontend index page
r.Get("/", art.GetMainPage)
// add static web server support
logging.Msg(ctx).Debug("file server starts on dir: ", filepath.Join(cfg.WebPath, "static"))
fileServer := http.FileServer(http.Dir(filepath.Join(cfg.WebPath, "static")))
r.Get("/static/*", func(w http.ResponseWriter, r *http.Request) {
ctx := cu.BuildContext(r.Context(), cu.AddContextOperation("file_server"), errs.SetDefaultErrsKind(errs.KindRouter))
logging.Msg(ctx).Debug(r.RequestURI)
http.StripPrefix("/static", fileServer).ServeHTTP(w, r)
})
//register AppRouter as handler for api.ServerInterface
//api.HandlerFromMux(art, r)
r.Mount("/", api.Handler(art))
art.Handler = r
logging.Msg(ctx).Debug("router init - ok")
return art, nil
}
func (art *AppRouter) GetMainPage(w http.ResponseWriter, r *http.Request) {
ctx := cu.BuildContext(r.Context(), cu.AddContextOperation("get_main"), errs.SetDefaultErrsSeverity(errs.SeverityCritical), errs.SetDefaultErrsKind(errs.KindRouter))
ts, err := template.ParseFiles(filepath.Join(art.cfg.WebPath, "templates/index.html"))
if err != nil {
logging.LogError(ctx, fmt.Errorf("parsing main page template failed: %w", err))
http.Error(w, "Internal Server Error", 500)
return
}
if err != ts.Execute(w, nil) {
logging.LogError(ctx, fmt.Errorf("executing main page template failed: %w", err))
http.Error(w, "Internal Server Error", 500)
return
}
}
func (art *AppRouter) GetOpenAPI(w http.ResponseWriter, r *http.Request) {
ctx := cu.BuildContext(r.Context(), cu.AddContextOperation("get_openapi"), errs.SetDefaultErrsSeverity(errs.SeverityCritical), errs.SetDefaultErrsKind(errs.KindRouter))
ts, err := template.ParseFiles(filepath.Join(art.cfg.WebPath, "templates/openapi_index.html"))
if err != nil {
logging.LogError(ctx, fmt.Errorf("parsing openapi template failed: %w", err))
http.Error(w, "Internal Server Error", 500)
return
}
if err != ts.Execute(w, nil) {
logging.LogError(ctx, fmt.Errorf("executing openapi template failed: %w", err))
http.Error(w, "Internal Server Error", 500)
return
}
}
func (art *AppRouter) CreateShortUrl(w http.ResponseWriter, r *http.Request) {
ctx := cu.BuildContext(r.Context(), cu.AddContextOperation("create_shurl"), errs.SetDefaultErrsKind(errs.KindRouter))
defer func() {
_ = r.Body.Close()
}()
var requestShurl api.RequestShortUrl
if err := json.NewDecoder(r.Body).Decode(&requestShurl); err != nil {
logging.LogError(ctx, fmt.Errorf("invalid request format: %w", err))
http.Error(w, "", http.StatusBadRequest)
return
}
var expiredAt *time.Time
if requestShurl.ExpiredInDays != nil {
t := time.Now().UTC().AddDate(0, 0, int(*requestShurl.ExpiredInDays))
expiredAt = &t
}
token, added, err := art.a.CreateToken(ctx, requestShurl.TargetUrl, expiredAt)
if err != nil {
logging.LogError(ctx, err)
http.Error(w, "", http.StatusBadRequest)
return
}
if added {
w.WriteHeader(http.StatusCreated)
} else {
w.WriteHeader(http.StatusOK)
}
shurlInfo := fmt.Sprintf("/%s/info", token) // todo: use entry point from cfg
result := &api.ResponseShortUrl{
ShortUrl: fmt.Sprintf("/%s", token),
ShortUrlInfo: &shurlInfo,
}
if err := json.NewEncoder(w).Encode(result); err != nil {
logging.LogError(ctx, fmt.Errorf("encoding [%v] to json failed: %w", result, err))
}
}
func (art *AppRouter) HitShortUrl(w http.ResponseWriter, r *http.Request, token string) {
ctx := cu.BuildContext(r.Context(), cu.AddContextOperation("hit_shurl"), errs.SetDefaultErrsKind(errs.KindRouter))
link, err := art.a.HitLink(ctx, token)
if err != nil {
if errors.Is(err, app.ErrNotFound) {
http.Error(w, "", http.StatusNotFound)
return
}
logging.LogError(ctx, err)
http.Error(w, "", http.StatusInternalServerError)
return
}
http.Redirect(w, r, link.TargetUrl, http.StatusSeeOther)
}
func (art *AppRouter) GetShortUrlInfo(w http.ResponseWriter, r *http.Request, token string) {
ctx := cu.BuildContext(r.Context(), cu.AddContextOperation("hit_shurl"), errs.SetDefaultErrsKind(errs.KindRouter))
link, err := art.a.GetLink(ctx, token)
if err != nil {
if errors.Is(err, app.ErrNotFound) {
http.Error(w, "", http.StatusNotFound)
return
}
logging.LogError(ctx, err)
http.Error(w, "", http.StatusInternalServerError)
return
}
result := api.Link{
CreatedAt: link.CreatedAt,
DeletedAt: link.DeletedAt,
ExpiredAt: link.ExpiredAt,
Hits: int32(link.Hits),
TargetUrl: link.TargetUrl,
Token: link.Key,
}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(result); err != nil {
logging.LogError(ctx, fmt.Errorf("encoding [%v] to json failed: %w", result, err))
}
}