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.
39 lines
803 B
39 lines
803 B
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
)
|
|
|
|
func JSON(w http.ResponseWriter, status int, data interface{}) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
json.NewEncoder(w).Encode(data)
|
|
}
|
|
|
|
func Error(w http.ResponseWriter, status int, msg string) {
|
|
JSON(w, status, map[string]string{"error": msg})
|
|
}
|
|
|
|
func Decode(r *http.Request, v interface{}) error {
|
|
return json.NewDecoder(r.Body).Decode(v)
|
|
}
|
|
|
|
func valueToString(v interface{}) (string, error) {
|
|
switch val := v.(type) {
|
|
case string:
|
|
return val, nil
|
|
case map[string]interface{}, []interface{}:
|
|
b, err := json.Marshal(val)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(b), nil
|
|
default:
|
|
b, err := json.Marshal(val)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(b), nil
|
|
}
|
|
}
|
|
|