summaryrefslogtreecommitdiff
path: root/cli/imgup/upload.go
diff options
context:
space:
mode:
authorHorus32015-04-21 05:57:21 +0200
committerHorus32015-04-21 05:57:21 +0200
commit7e4ccc40be46366fd8c0550aca1bfb6e73c3b5c6 (patch)
tree659e0206d73607dbe2cdb75ab871e078d06d37ad /cli/imgup/upload.go
parentc92ed3c93c379368f615809aa599426890bf2057 (diff)
downloadmandible-7e4ccc40be46366fd8c0550aca1bfb6e73c3b5c6.tar.gz
Add cli program.
Diffstat (limited to 'cli/imgup/upload.go')
-rw-r--r--cli/imgup/upload.go102
1 files changed, 102 insertions, 0 deletions
diff --git a/cli/imgup/upload.go b/cli/imgup/upload.go
new file mode 100644
index 0000000..d2da497
--- /dev/null
+++ b/cli/imgup/upload.go
@@ -0,0 +1,102 @@
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "mime/multipart"
+ "net/http"
+ "net/url"
+ "os"
+)
+
+func fileUpload(url, file, name string) (err error) {
+ // Prepare a form that you will submit to that URL.
+ var b bytes.Buffer
+ w := multipart.NewWriter(&b)
+ // Add your image file
+ f, err := os.Open(file)
+ if err != nil {
+ return
+ }
+ fw, err := w.CreateFormFile("image", file)
+ if err != nil {
+ return
+ }
+ if _, err = io.Copy(fw, f); err != nil {
+ return
+ }
+ // Add the other fields
+ if fw, err = w.CreateFormField("key"); err != nil {
+ return
+ }
+ if _, err = fw.Write([]byte("KEY")); err != nil {
+ return
+ }
+ // Don't forget to close the multipart writer.
+ // If you don't close it, your request will be missing the terminating boundary.
+ w.Close()
+
+ // Now that you have a form, you can submit it to your handler.
+ req, err := http.NewRequest("POST", url, &b)
+ if err != nil {
+ return
+ }
+ // Don't forget to set the content type, this will contain the boundary.
+ req.Header.Set("Content-Type", w.FormDataContentType())
+
+ // Submit the request
+ client := &http.Client{}
+ res, err := client.Do(req)
+ if err != nil {
+ return
+ }
+
+ // Check the response
+ if res.StatusCode != http.StatusOK {
+ err = fmt.Errorf("bad status: %s", res.Status)
+ }
+
+ defer res.Body.Close()
+ contents, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ return
+ }
+
+ printResponse(contents, name)
+
+ return
+}
+
+func urlUpload(targetUrl, file, name string) (err error) {
+ form := url.Values{}
+ form.Set("image", file)
+ imageUrl := form.Encode()
+ req, err := http.NewRequest("POST", targetUrl, bytes.NewBuffer([]byte(imageUrl)))
+ if err != nil {
+ return
+ }
+
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+ client := &http.Client{}
+ res, err := client.Do(req)
+ if err != nil {
+ return
+ }
+
+ if res.StatusCode != http.StatusOK {
+ err = fmt.Errorf("bad status: %s", res.Status)
+ }
+
+ defer res.Body.Close()
+ contents, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ return
+ }
+
+ printResponse(contents, name)
+
+ return
+}