oidc-idp/internal/handlers/observability.go
Jan Dittberner 16a3dbedc8 Small IDP refactoring
- move internal code to internal directory
- add translations for texts on missing email in client certificate page
- add error handling for missing login_challenge request parameter
- add Markdown support via goldmark
- use https:// URLs in Apache license headers
2023-07-18 20:37:04 +02:00

108 lines
2.5 KiB
Go

/*
Copyright 2020-2023 CAcert Inc.
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package handlers
import (
"context"
"fmt"
"net/http"
"sync/atomic"
log "github.com/sirupsen/logrus"
)
type key int
const (
requestIDKey key = iota
)
type statusCodeInterceptor struct {
http.ResponseWriter
code int
count int
}
func (sci *statusCodeInterceptor) WriteHeader(code int) {
sci.code = code
sci.ResponseWriter.WriteHeader(code)
}
func (sci *statusCodeInterceptor) Write(content []byte) (int, error) {
count, err := sci.ResponseWriter.Write(content)
sci.count += count
if err != nil {
return count, fmt.Errorf("could not write response: %w", err)
}
return count, nil
}
func Logging(logger *log.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
interceptor := &statusCodeInterceptor{w, http.StatusOK, 0}
defer func() {
requestID, ok := r.Context().Value(requestIDKey).(string)
if !ok {
requestID = "unknown"
}
logger.Infof(
"%s %s \"%s %s\" %d %d \"%s\"",
requestID,
r.RemoteAddr,
r.Method,
r.URL.Path,
interceptor.code,
interceptor.count,
r.UserAgent(),
)
}()
next.ServeHTTP(interceptor, r)
})
}
}
func Tracing(nextRequestID func() string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestID := r.Header.Get("X-Request-Id")
if requestID == "" {
requestID = nextRequestID()
}
ctx := context.WithValue(r.Context(), requestIDKey, requestID)
w.Header().Set("X-Request-Id", requestID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
var Healthy int32
func NewHealthHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if atomic.LoadInt32(&Healthy) == 1 {
w.WriteHeader(http.StatusNoContent)
return
}
w.WriteHeader(http.StatusServiceUnavailable)
})
}