responses.go 714 B

123456789101112131415161718192021222324252627282930313233
  1. package api
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "net/http"
  6. )
  7. //SimpleResponseMessage a simple message as response
  8. type SimpleResponseMessage struct {
  9. Message string `json:"message"`
  10. Code int `json:"code"`
  11. }
  12. //MsgResponse writes a response with a message as json
  13. func MsgResponse(w http.ResponseWriter, code int, message string) {
  14. m := SimpleResponseMessage{
  15. Message: message,
  16. Code: code,
  17. }
  18. buf := &bytes.Buffer{}
  19. enc := json.NewEncoder(buf)
  20. enc.SetEscapeHTML(true)
  21. if err := enc.Encode(m); err != nil {
  22. http.Error(w, err.Error(), http.StatusInternalServerError)
  23. return
  24. }
  25. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  26. w.WriteHeader(code)
  27. w.Write(buf.Bytes())
  28. }