You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.4 KiB
68 lines
1.4 KiB
package httpapi
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"git.aiterp.net/stufflog3/stufflog3/models"
|
|
"github.com/gin-gonic/gin"
|
|
"log"
|
|
"strconv"
|
|
)
|
|
|
|
type statusError interface {
|
|
HttpStatus() (int, string, interface{})
|
|
}
|
|
|
|
func handler(key string, callback func(c *gin.Context) (interface{}, error)) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
res, err := callback(c)
|
|
if err != nil {
|
|
if statusError, ok := err.(statusError); ok {
|
|
code, msg, data := statusError.HttpStatus()
|
|
c.JSON(code, Error{
|
|
Code: code,
|
|
Message: msg,
|
|
Data: data,
|
|
})
|
|
} else {
|
|
id := make([]byte, 16)
|
|
_, _ = rand.Read(id)
|
|
idHex := hex.EncodeToString(id)
|
|
|
|
log.Println("Internal server error", idHex, "triggered by:", err)
|
|
|
|
c.JSON(500, Error{
|
|
Code: 500,
|
|
Message: "Internal server error (" + idHex + ")",
|
|
Data: nil,
|
|
})
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
resJson := make(map[string]interface{}, 1)
|
|
resJson[key] = res
|
|
|
|
c.JSON(200, resJson)
|
|
}
|
|
}
|
|
|
|
type Error struct {
|
|
Code int `json:"statusCode"`
|
|
Message string `json:"statusMessage"`
|
|
Data interface{} `json:"errorData,omitempty"`
|
|
}
|
|
|
|
func reqInt(c *gin.Context, key string) (int, error) {
|
|
v, err := strconv.Atoi(c.Param(key))
|
|
if err != nil {
|
|
return 0, models.BadInputError{
|
|
Object: "query",
|
|
Field: key,
|
|
Problem: "Value for " + key + " must be numeric",
|
|
}
|
|
}
|
|
|
|
return v, nil
|
|
}
|