github.com/giovannyortegon/go@v0.0.0-20220115155912-8890063f5bdd/src/APIRest/models/response.go (about)

     1  package models
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  )
     8  
     9  type Response struct {
    10  	Status      int         `json:"status"`
    11  	Data        interface{} `json:"data"`
    12  	Message     string      `json:"message"`
    13  	contentType string
    14  	respWrite   http.ResponseWriter
    15  }
    16  
    17  func CreateDefaultResponse(rw http.ResponseWriter) Response {
    18  	return Response{
    19  		Status:      http.StatusOK,
    20  		respWrite:   rw,
    21  		contentType: "application/json",
    22  	}
    23  }
    24  
    25  func (resp *Response) Send() {
    26  	resp.respWrite.Header().Set("Content-Type", resp.contentType)
    27  	resp.respWrite.WriteHeader(resp.Status)
    28  
    29  	output, _ := json.Marshal(&resp)
    30  	fmt.Fprintln(resp.respWrite, string(output))
    31  }
    32  
    33  func SendData(rw http.ResponseWriter, data interface{}) {
    34  	response := CreateDefaultResponse(rw)
    35  	response.Data = data
    36  	response.Send()
    37  }
    38  
    39  func (resp *Response) NotFound() {
    40  	resp.Status = http.StatusNotFound
    41  	resp.Message = "Resource Not Found"
    42  }
    43  
    44  func SendNotFound(rw http.ResponseWriter) {
    45  	response := CreateDefaultResponse(rw)
    46  	response.NotFound()
    47  	response.Send()
    48  }
    49  
    50  func (resp *Response) UnprocessableEntity() {
    51  	resp.Status = http.StatusUnprocessableEntity
    52  	resp.Message = "Resource Not Found"
    53  }
    54  func SendUnprocessableEntity(rw http.ResponseWriter) {
    55  	response := CreateDefaultResponse(rw)
    56  	response.NotFound()
    57  	response.Send()
    58  }