github.com/lusis/distribution@v2.0.1+incompatible/registry/handlers/helpers.go (about)

     1  package handlers
     2  
     3  import (
     4  	"encoding/json"
     5  	"io"
     6  	"net/http"
     7  )
     8  
     9  // serveJSON marshals v and sets the content-type header to
    10  // 'application/json'. If a different status code is required, call
    11  // ResponseWriter.WriteHeader before this function.
    12  func serveJSON(w http.ResponseWriter, v interface{}) error {
    13  	w.Header().Set("Content-Type", "application/json; charset=utf-8")
    14  	enc := json.NewEncoder(w)
    15  
    16  	if err := enc.Encode(v); err != nil {
    17  		return err
    18  	}
    19  
    20  	return nil
    21  }
    22  
    23  // closeResources closes all the provided resources after running the target
    24  // handler.
    25  func closeResources(handler http.Handler, closers ...io.Closer) http.Handler {
    26  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    27  		for _, closer := range closers {
    28  			defer closer.Close()
    29  		}
    30  		handler.ServeHTTP(w, r)
    31  	})
    32  }