ch18.3
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"database/sql"
|
||||
"flag"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -45,6 +46,9 @@ type config struct {
|
||||
password string
|
||||
sender string
|
||||
}
|
||||
cors struct {
|
||||
trustedOrigins []string
|
||||
}
|
||||
}
|
||||
|
||||
func openDB(cfg config) (*sql.DB, error) {
|
||||
@@ -93,6 +97,11 @@ func main() {
|
||||
flag.StringVar(&cfg.smtp.password, "smtp-password", "d8672aa2264bb5", "SMTP password")
|
||||
flag.StringVar(&cfg.smtp.sender, "smtp-sender", "Greenlight <no-reply@greenlight.net", "SMTP sender")
|
||||
|
||||
flag.Func("cors-trusted-origins", "Trusted CORS origins (space separated)", func(s string) error {
|
||||
cfg.cors.trustedOrigins = strings.Fields(s)
|
||||
return nil
|
||||
})
|
||||
|
||||
flag.Parse()
|
||||
|
||||
logger := jsonlog.New(os.Stdout, jsonlog.LevelInfo)
|
||||
|
||||
@@ -170,3 +170,22 @@ func (app *application) requirePermissions(code string, next http.HandlerFunc) h
|
||||
}
|
||||
return app.requireActivatedUser(fn)
|
||||
}
|
||||
|
||||
func (app *application) enableCORS(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Vary", "Origin")
|
||||
|
||||
origin := r.Header.Get("Origin")
|
||||
|
||||
if origin != "" {
|
||||
for i := range app.config.cors.trustedOrigins {
|
||||
if origin == app.config.cors.trustedOrigins[i] {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -25,5 +25,5 @@ func (app *application) routes() http.Handler {
|
||||
|
||||
router.HandlerFunc(http.MethodPost, "/v1/tokens/authentication", app.createAuthenticationTokenHandler)
|
||||
|
||||
return app.recoverPanic(app.rateLimit(app.authenticate(router)))
|
||||
return app.recoverPanic(app.enableCORS(app.rateLimit(app.authenticate(router))))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user