2015-02-11 01:25:40 +00:00
|
|
|
package handlers
|
2014-11-11 02:57:38 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2014-11-21 03:57:01 +00:00
|
|
|
"io"
|
2014-11-11 02:57:38 +00:00
|
|
|
"net/http"
|
2015-05-27 01:16:45 +00:00
|
|
|
|
|
|
|
"github.com/docker/distribution/registry/api/errcode"
|
2014-11-11 02:57:38 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// serveJSON marshals v and sets the content-type header to
|
|
|
|
// 'application/json'. If a different status code is required, call
|
|
|
|
// ResponseWriter.WriteHeader before this function.
|
|
|
|
func serveJSON(w http.ResponseWriter, v interface{}) error {
|
2014-12-31 04:09:45 +00:00
|
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
2015-05-15 01:21:39 +00:00
|
|
|
sc := http.StatusInternalServerError
|
|
|
|
|
2015-05-27 00:18:32 +00:00
|
|
|
if errs, ok := v.(errcode.Errors); ok && len(errs) > 0 {
|
2015-06-03 13:52:39 +00:00
|
|
|
if err, ok := errs[0].(errcode.ErrorCoder); ok {
|
|
|
|
if sc2 := err.ErrorCode().Descriptor().HTTPStatusCode; sc2 != 0 {
|
|
|
|
sc = sc2
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if err, ok := v.(errcode.ErrorCoder); ok {
|
|
|
|
if sc2 := err.ErrorCode().Descriptor().HTTPStatusCode; sc2 != 0 {
|
|
|
|
sc = sc2
|
2015-05-15 01:21:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
w.WriteHeader(sc)
|
|
|
|
|
2014-11-11 02:57:38 +00:00
|
|
|
enc := json.NewEncoder(w)
|
|
|
|
|
|
|
|
if err := enc.Encode(v); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2014-11-21 03:57:01 +00:00
|
|
|
|
|
|
|
// closeResources closes all the provided resources after running the target
|
|
|
|
// handler.
|
|
|
|
func closeResources(handler http.Handler, closers ...io.Closer) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
for _, closer := range closers {
|
|
|
|
defer closer.Close()
|
|
|
|
}
|
|
|
|
handler.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|