remove duplicate codes

This commit is contained in:
Wenkai Yin 2017-03-20 13:55:03 +08:00
parent 3a167ddfce
commit a40994852f
4 changed files with 21 additions and 16 deletions

View File

@ -16,6 +16,7 @@
package api package api
import ( import (
"encoding/json"
"net/http" "net/http"
) )
@ -32,3 +33,17 @@ func handleUnauthorized(w http.ResponseWriter) {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.Error(w, http.StatusText(http.StatusUnauthorized),
http.StatusUnauthorized) http.StatusUnauthorized)
} }
// response status code will be written automatically if there is an error
func writeJSON(w http.ResponseWriter, v interface{}) error {
b, err := json.Marshal(v)
if err != nil {
handleInternalServerError(w)
return err
}
if _, err = w.Write(b); err != nil {
return err
}
return nil
}

View File

@ -33,14 +33,9 @@ func ListCfgs(w http.ResponseWriter, r *http.Request) {
return return
} }
b, err := json.MarshalIndent(cfg, "", " ") if err = writeJSON(w, cfg); err != nil {
if err != nil {
log.Errorf("failed to marshal configurations: %v", err)
handleInternalServerError(w)
return
}
if _, err = w.Write(b); err != nil {
log.Errorf("failed to write response: %v", err) log.Errorf("failed to write response: %v", err)
return
} }
} }

View File

@ -16,7 +16,6 @@
package api package api
import ( import (
"encoding/json"
"net/http" "net/http"
"github.com/vmware/harbor/src/adminserver/systeminfo/imagestorage" "github.com/vmware/harbor/src/adminserver/systeminfo/imagestorage"
@ -32,14 +31,8 @@ func Capacity(w http.ResponseWriter, r *http.Request) {
return return
} }
b, err := json.Marshal(capacity) if err = writeJSON(w, capacity); err != nil {
if err != nil { log.Errorf("failed to write response: %v", err)
log.Errorf("failed to marshal capacity: %v", err)
handleInternalServerError(w)
return return
} }
if _, err = w.Write(b); err != nil {
log.Errorf("failed to write response: %v", err)
}
} }

View File

@ -24,6 +24,8 @@ import (
"github.com/vmware/harbor/src/common/utils/log" "github.com/vmware/harbor/src/common/utils/log"
) )
// NewHandler returns a gorilla router which is wrapped by authenticate handler
// and logging handler
func NewHandler() http.Handler { func NewHandler() http.Handler {
h := newRouter() h := newRouter()
secrets := map[string]string{ secrets := map[string]string{