package core

import (
	"encoding/json"
	"fmt"
	"net/http"
)

// SendObject sends a object through the writer
func SendObject(writer *http.ResponseWriter, data interface{}) {
	js := ToJSON(data)
	if js == "" {
		SendJSON(writer, "{\"server_message\":\"internal_sending_error\"")
		return
	}
	SendJSON(writer, js)
}

// SendJSON sends JSON string through the writer
func SendJSON(writer *http.ResponseWriter, data string) {
	(*writer).Header().Set("Content-Type", "application/json")
	fmt.Fprintf((*writer), data)
}

// ToJSON converts an object to a JSON string
func ToJSON(in interface{}) string {
	data, err := json.Marshal(in)
	if err != nil {
		return ""
	}
	return string(data)
}
