b8be14ea8d
* Add a world cities database with type-ahead search on the Member Directory. * Users can search for a known city to order users by distance from that city rather than from their own configured location on their settings page. * Users must opt-in their own location before this feature may be used, in order to increase adoption of the location feature and to enforce fairness. * The `nonshy setup locations` command can import the world cities database.
66 lines
1.3 KiB
Go
66 lines
1.3 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"io/ioutil"
|
|
"net/http"
|
|
)
|
|
|
|
// Envelope is the standard JSON response envelope.
|
|
type Envelope struct {
|
|
Data interface{} `json:"data"`
|
|
StatusCode int
|
|
}
|
|
|
|
// ParseJSON request body.
|
|
func ParseJSON(r *http.Request, v interface{}) error {
|
|
if r.Header.Get("Content-Type") != "application/json" {
|
|
return errors.New("request Content-Type must be application/json")
|
|
}
|
|
|
|
// Parse request body.
|
|
body, err := ioutil.ReadAll(r.Body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Parse params from JSON.
|
|
if err := json.Unmarshal(body, v); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// SendJSON response.
|
|
func SendJSON(w http.ResponseWriter, statusCode int, v interface{}) {
|
|
buf, err := json.Marshal(Envelope{
|
|
Data: v,
|
|
StatusCode: statusCode,
|
|
})
|
|
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(statusCode)
|
|
w.Write(buf)
|
|
}
|
|
|
|
// SendRawJSON response without the standard API wrapper.
|
|
func SendRawJSON(w http.ResponseWriter, statusCode int, v interface{}) {
|
|
buf, err := json.Marshal(v)
|
|
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(statusCode)
|
|
w.Write(buf)
|
|
}
|