storj/multinode/console/controllers/common.go
Egon Elbre 8beb78ec3f {satellite,multinode}/console: fix WriteHeader
w.Header().Set needs to be called before WriteHeader,
because WriteHeader sends all the headers and calls to
Set won't have any effect afterwards.

Change-Id: Ia6b1c5e2cd54201a6c3980d63de04a0095b2db9a
2023-05-08 18:18:30 +00:00

46 lines
955 B
Go

// Copyright (C) 2020 Storj Labs, Inc.
// See LICENSE for copying information.
package controllers
import (
"encoding/json"
"net/http"
"github.com/spacemonkeygo/monkit/v3"
"go.uber.org/zap"
)
var (
mon = monkit.Package()
)
// NotFound handles API response for not found routes.
type NotFound struct {
log *zap.Logger
}
// NewNotFound creates new instance of NotFound handler.
func NewNotFound(log *zap.Logger) http.Handler {
return &NotFound{
log: log,
}
}
// ServeHTTP serves 404 response with json error when resource is not found.
func (handler *NotFound) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
var response struct {
Error string `json:"error"`
}
response.Error = "resource not found"
err := json.NewEncoder(w).Encode(response)
if err != nil {
handler.log.Error("failed to write json error response", zap.Error(err))
}
}