46 lines
1.1 KiB
Go
46 lines
1.1 KiB
Go
package errors_handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// 404 - Not Found
|
|
func GetNotFoundError(c *gin.Context) {
|
|
errorData := gin.H{
|
|
"code": http.StatusNotFound,
|
|
"msg": c.Request.Method + " > the requested API endpoint was not found",
|
|
"data": gin.H{
|
|
"path": c.Request.URL.Path,
|
|
"method": c.Request.Method,
|
|
"endpoints": gin.H{
|
|
"health": "/health",
|
|
"downloads": "/download/versions",
|
|
},
|
|
},
|
|
}
|
|
|
|
acceptHeader := c.GetHeader("Accept")
|
|
if strings.Contains(acceptHeader, "text/html") {
|
|
// for browser requests, return HTML
|
|
jsonBytes, err := json.Marshal(errorData)
|
|
if err != nil {
|
|
jsonBytes = []byte(`{"error": "json_serialization_failed"}`)
|
|
}
|
|
jsonStr := string(jsonBytes)
|
|
c.HTML(http.StatusNotFound, "404.html", gin.H{
|
|
"title": "404 - Not Found",
|
|
"path": c.Request.URL.Path,
|
|
"method": c.Request.Method,
|
|
"baseURL": c.Request.Host,
|
|
"jsonData": jsonStr,
|
|
})
|
|
return
|
|
}
|
|
// for General requests (no text/html in Accept header), return JSON
|
|
c.JSON(http.StatusNotFound, errorData)
|
|
}
|