2020-02-07 16:36:28 +00:00
|
|
|
// Copyright (C) 2020 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package admin
|
|
|
|
|
2020-08-05 14:13:11 +01:00
|
|
|
import (
|
2023-09-05 20:28:39 +01:00
|
|
|
"encoding/hex"
|
2020-08-05 14:13:11 +01:00
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/zeebo/errs"
|
2023-09-05 20:28:39 +01:00
|
|
|
|
|
|
|
"storj.io/common/uuid"
|
2020-08-05 14:13:11 +01:00
|
|
|
)
|
2020-02-07 16:36:28 +00:00
|
|
|
|
|
|
|
// Error is default error class for admin package.
|
|
|
|
var Error = errs.Class("admin")
|
2020-08-05 14:13:11 +01:00
|
|
|
|
2021-10-01 12:50:21 +01:00
|
|
|
func sendJSONError(w http.ResponseWriter, errMsg, detail string, statusCode int) {
|
2020-08-05 14:13:11 +01:00
|
|
|
errStr := struct {
|
|
|
|
Error string `json:"error"`
|
|
|
|
Detail string `json:"detail"`
|
|
|
|
}{
|
2021-10-01 12:36:41 +01:00
|
|
|
Error: errMsg,
|
2020-08-05 14:13:11 +01:00
|
|
|
Detail: detail,
|
|
|
|
}
|
2021-10-01 12:36:41 +01:00
|
|
|
body, err := json.Marshal(errStr)
|
2020-08-05 14:13:11 +01:00
|
|
|
if err != nil {
|
2021-10-01 12:36:41 +01:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
2020-08-05 14:13:11 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-10-01 12:36:41 +01:00
|
|
|
sendJSONData(w, statusCode, body)
|
|
|
|
}
|
|
|
|
|
|
|
|
func sendJSONData(w http.ResponseWriter, statusCode int, data []byte) {
|
2020-08-05 14:13:11 +01:00
|
|
|
w.Header().Set("Content-Type", "application/json")
|
2021-10-01 12:36:41 +01:00
|
|
|
w.WriteHeader(statusCode)
|
|
|
|
_, _ = w.Write(data) // any error here entitles a client side disconnect or similar, which we do not care about.
|
2020-08-05 14:13:11 +01:00
|
|
|
}
|
2023-09-05 20:28:39 +01:00
|
|
|
|
|
|
|
// uuidFromString converts a hex string into a UUID type. It works regardless of whether the string version contains `-` characters.
|
|
|
|
func uuidFromString(uuidString string) (id uuid.UUID, err error) {
|
|
|
|
if len(uuidString) == len(uuid.UUID{}.String()) {
|
|
|
|
id, err = uuid.FromString(uuidString)
|
|
|
|
if err != nil {
|
|
|
|
return id, Error.Wrap(err)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// this case means that dashes may not have been included in the ID passed in
|
|
|
|
// to parse, decode from hex, and create UUID from bytes
|
|
|
|
b, err := hex.DecodeString(uuidString)
|
|
|
|
if err != nil {
|
|
|
|
return id, Error.Wrap(err)
|
|
|
|
}
|
|
|
|
id, err = uuid.FromBytes(b)
|
|
|
|
if err != nil {
|
|
|
|
return id, Error.Wrap(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return id, nil
|
|
|
|
}
|