Skeleton contracts / contracts (pull_request) Blocked by required conditions
Реализован контракт lab1 (X-User-Id), non-root образ, SIGTERM ≤10s, DEFENSE/REPORT.
91 lines
2.2 KiB
Go
91 lines
2.2 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type ctxKey int
|
|
|
|
const (
|
|
ctxUserID ctxKey = iota
|
|
ctxReqID
|
|
)
|
|
|
|
type responseTap struct {
|
|
http.ResponseWriter
|
|
status int
|
|
}
|
|
|
|
func (t *responseTap) WriteHeader(code int) {
|
|
t.status = code
|
|
t.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
func requestIdentity(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
rid := strings.TrimSpace(r.Header.Get("X-Request-Id"))
|
|
if rid == "" {
|
|
rid = uuid.NewString()
|
|
}
|
|
w.Header().Set("X-Request-Id", rid)
|
|
ctx := context.WithValue(r.Context(), ctxReqID, rid)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
func accessLog(next http.Handler) http.Handler {
|
|
quiet := strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "0") ||
|
|
strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "false")
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
tap := &responseTap{ResponseWriter: w, status: http.StatusOK}
|
|
next.ServeHTTP(tap, r)
|
|
if quiet && strings.HasPrefix(r.URL.Path, "/api/") && tap.status < 400 {
|
|
return
|
|
}
|
|
if strings.HasPrefix(r.URL.Path, "/health/") && tap.status == 200 {
|
|
return
|
|
}
|
|
rid := tap.Header().Get("X-Request-Id")
|
|
if rid == "" {
|
|
rid, _ = r.Context().Value(ctxReqID).(string)
|
|
}
|
|
log.Printf("http method=%s path=%s status=%d request_id=%s ms=%d",
|
|
r.Method, r.URL.Path, tap.status, rid, time.Since(start).Milliseconds())
|
|
})
|
|
}
|
|
|
|
func (s *Service) requireUser(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
raw := strings.TrimSpace(r.Header.Get("X-User-Id"))
|
|
if raw == "" {
|
|
s.writeErr(w, r, http.StatusUnauthorized, "unauthorized", "authentication required")
|
|
return
|
|
}
|
|
id, err := uuid.Parse(raw)
|
|
if err != nil || !s.DB.UserExists(id) {
|
|
s.writeErr(w, r, http.StatusUnauthorized, "unauthorized", "authentication required")
|
|
return
|
|
}
|
|
next(w, r.WithContext(context.WithValue(r.Context(), ctxUserID, id)))
|
|
}
|
|
}
|
|
|
|
func actorID(r *http.Request) uuid.UUID {
|
|
v, _ := r.Context().Value(ctxUserID).(uuid.UUID)
|
|
return v
|
|
}
|
|
|
|
func reqID(r *http.Request) string {
|
|
if v, ok := r.Context().Value(ctxReqID).(string); ok && v != "" {
|
|
return v
|
|
}
|
|
return uuid.NewString()
|
|
} |