47 lines
1.1 KiB
Go
47 lines
1.1 KiB
Go
package utils
|
|
|
|
import (
|
|
"encoding/json"
|
|
"math/rand"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
type LogError struct {
|
|
Code string `json:"code" db:"ErrorLogCode"`
|
|
TraceID string `json:"trace_id" db:"ErrorTraceID"`
|
|
Type string `json:"type" db:"ErrorLogType"`
|
|
Params string `json:"params" db:"ErrorLogParams"`
|
|
Query string `json:"query" db:"ErrorLogQuery"`
|
|
Message string `json:"message" db:"ErrorMessage"`
|
|
TimeStamp string `json:"timestamp" db:"ErrorLogTimestamp"`
|
|
}
|
|
|
|
func (e *LogError) Error() string {
|
|
return e.Message
|
|
}
|
|
|
|
func (e *LogError) LogError() LogError {
|
|
return *e
|
|
}
|
|
|
|
func RandomTraceID(n int) string {
|
|
src := rand.NewSource(time.Now().UnixNano())
|
|
r := rand.New(src)
|
|
|
|
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
|
|
b := make([]byte, n)
|
|
for i := range b {
|
|
b[i] = letterBytes[r.Intn(len(letterBytes))]
|
|
}
|
|
return string(b)
|
|
}
|
|
|
|
func WriteErrorLog(w http.ResponseWriter, status int, err LogError) {
|
|
w.Header().Add("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
resp := map[string]any{"status": "ERR", "error": err}
|
|
json.NewEncoder(w).Encode(resp)
|
|
}
|