72 lines
1.7 KiB
Go
72 lines
1.7 KiB
Go
package handlers
|
|
|
|
import (
|
|
"docker-manager/docker"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
func ListImagesHandler(w http.ResponseWriter, r *http.Request, client *docker.Client) {
|
|
var images []map[string]interface{}
|
|
if err := client.GetJSON("/images/json", &images); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if images == nil {
|
|
w.Write([]byte("[]"))
|
|
} else {
|
|
json.NewEncoder(w).Encode(images)
|
|
}
|
|
}
|
|
|
|
func RemoveImageHandler(w http.ResponseWriter, r *http.Request, client *docker.Client, id string) {
|
|
if resp, err := client.Do("DELETE", fmt.Sprintf("/images/%s?force=true", id), nil); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
} else {
|
|
defer resp.Body.Close()
|
|
w.WriteHeader(resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func PullImageHandler(w http.ResponseWriter, r *http.Request, client *docker.Client) {
|
|
name := r.URL.Query().Get("name")
|
|
if name == "" {
|
|
http.Error(w, "name parameter required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Strip tag if contains ":"
|
|
ref := name
|
|
if strings.Contains(name, ":") {
|
|
parts := strings.Split(name, ":")
|
|
ref = parts[0]
|
|
}
|
|
|
|
body, err := client.DoStream("POST", fmt.Sprintf("/images/create?fromImage=%s", ref), nil)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
defer body.Close()
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Header().Set("Transfer-Encoding", "chunked")
|
|
|
|
// Stream pull progress as JSON lines
|
|
decoder := json.NewDecoder(body)
|
|
for {
|
|
var line map[string]interface{}
|
|
if err := decoder.Decode(&line); err != nil {
|
|
break
|
|
}
|
|
json.NewEncoder(w).Encode(line)
|
|
if flusher, ok := w.(http.Flusher); ok {
|
|
flusher.Flush()
|
|
}
|
|
}
|
|
}
|