api.spaceplanner.app

Spaceplanner API
git clone git://jacobedwards.org/api.spaceplanner.app
Log | Files | Refs

respond.go (818B)


      1 package main
      2 
      3 import  (
      4 	"fmt"
      5 	"errors"
      6 	"net/http"
      7 	"github.com/gin-gonic/gin"
      8 )
      9 
     10 type Response struct {
     11 	// Status of message, 'ok' for success, anything else for an error
     12 	Status string `json:"status"`
     13 
     14 	// Error message, should be set if status is not 'ok'
     15 	Error string `json:"error"`
     16 
     17 	// Body of message
     18 	Body any `json:"body"`
     19 }
     20 
     21 func Respond(c *gin.Context, status int, body any) {
     22 	if (status < 200 || status >= 300) {
     23 		c.AbortWithError(http.StatusInternalServerError,
     24 		    errors.New("Expected successful status"))
     25 	}
     26 	c.IndentedJSON(status, Response{ Status: "ok", Body: body })
     27 }
     28 
     29 func RespondError(c *gin.Context, status int, format string, args ...interface{}) {
     30 	msg := fmt.Sprintf(format, args...)
     31 	c.Set("error", msg)
     32 	c.AbortWithStatusJSON(status,
     33 	    Response{ Status: "error", Error: msg })
     34 }