impl image upload to imgur
parent
1334295204
commit
cf9d6d83c6
|
|
@ -0,0 +1,64 @@
|
|||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"local/truckstop/config"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func UploadImage(b []byte) (string, error) {
|
||||
return uploadImage(b)
|
||||
}
|
||||
|
||||
func uploadImage(b []byte) (string, error) {
|
||||
buff := bytes.NewBuffer(nil)
|
||||
writer := multipart.NewWriter(buff)
|
||||
part, err := writer.CreateFormFile("image", "name")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if n, err := part.Write(b); err != nil {
|
||||
return "", err
|
||||
} else if n < len(b) {
|
||||
return "", errors.New("short write")
|
||||
}
|
||||
writer.Close()
|
||||
|
||||
images := config.Get().Images
|
||||
request, err := http.NewRequest(
|
||||
images.UploadMethod,
|
||||
images.UploadURI,
|
||||
buff,
|
||||
)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+images.AccessToken)
|
||||
request.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
c := &http.Client{Timeout: time.Minute}
|
||||
response, err := c.Do(request)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
b, _ = ioutil.ReadAll(response.Body)
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("error uploading image: (%d) %s", response.StatusCode, b)
|
||||
}
|
||||
var result struct {
|
||||
Data struct {
|
||||
Link string `json:"link"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &result); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return result.Data.Link, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package message
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"local/truckstop/config"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestImageUpload(t *testing.T) {
|
||||
if os.Getenv("INTEGRATION") == "" {
|
||||
t.Skip("$INTEGRATION not set")
|
||||
}
|
||||
os.Setenv("CONFIG", "../config.json")
|
||||
b, err := ioutil.ReadFile("./testdata/whatever.jpg")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := config.Refresh(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := UploadImage(b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(got)
|
||||
}
|
||||
Loading…
Reference in New Issue