Skip to content

Instantly share code, notes, and snippets.

@x893675
Created July 23, 2020 09:08
Show Gist options
  • Save x893675/4a79f5fddfd0c9382224bd1862f432ca to your computer and use it in GitHub Desktop.
Save x893675/4a79f5fddfd0c9382224bd1862f432ca to your computer and use it in GitHub Desktop.
package main
// docker client package version error, always import github.com/docker/docker v1.13.1
// Issue: https://github.com/moby/moby/issues/39302
import (
"context"
"github.com/docker/docker/client"
"github.com/emicklei/go-restful"
"io"
"log"
"net/http"
_ "net/http/pprof"
)
const DockerHost = "tcp://localhost:2376"
var dockerCli *client.Client
func init() {
var err error
dockerCli, err = client.NewClientWithOpts(client.WithHost(DockerHost), client.WithAPIVersionNegotiation())
if err != nil {
panic(err)
}
}
type Response struct {
Msg string `json:"msg"`
Code int `json:"code"`
}
type ResourceController struct {
}
func (u ResourceController) WebService() *restful.WebService {
ws := new(restful.WebService)
ws.
Path("").
Consumes(restful.MIME_XML, restful.MIME_JSON).
Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well
ws.Route(ws.POST("/uploads").To(u.uploadFile).Consumes("multipart/form-data").
Doc("upload image to project").
Param(ws.FormParameter("file", "docker image tarball").Required(true).DataType("file")))
return ws
}
func (u *ResourceController) uploadFile(req *restful.Request, resp *restful.Response) {
reader, err := req.Request.MultipartReader()
if err != nil {
log.Println(err)
_ = resp.WriteError(http.StatusInternalServerError, err)
return
}
for {
part, err := reader.NextPart()
if err != nil {
if err == io.EOF {
break
}
log.Println(err)
_ = resp.WriteError(http.StatusInternalServerError, err)
return
}
log.Printf("form header is %v, form filename is %s, part form name is %s", part.Header, part.FileName(), part.FormName())
_, err = dockerCli.ImageLoad(context.TODO(), part, true)
if err != nil {
log.Println(err)
_ = resp.WriteError(http.StatusInternalServerError, err)
return
}
}
resp.WriteHeaderAndEntity(http.StatusOK, Response{Msg: "ok", Code: http.StatusOK})
}
func main() {
u := ResourceController{}
restful.DefaultContainer.Add(u.WebService())
log.Printf("start listening on localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment