Created
August 19, 2019 02:27
-
-
Save Pheric/7aa64987e09a55d5a7316fface55ee9f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package imgbbapi | |
import ( | |
"encoding/base64" | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"net/url" | |
) | |
type ImgbbClient string | |
type ImgbbResponse struct { | |
Success bool | |
Status int | |
Data struct { | |
Id string | |
UrlViewer string | |
Url string | |
DisplayUrl string | |
DeleteUrl string | |
Title string | |
Time string | |
Image struct { | |
ImgData | |
Size int | |
} | |
Thumb struct { | |
ImgData | |
Size string | |
} | |
Medium struct { | |
ImgData | |
Size string | |
} | |
} | |
} | |
type ImgData struct { | |
Filename string | |
Name string | |
Mime string | |
Extension string | |
Url string | |
} | |
// image will be base64 encoded before uploading | |
func (client ImgbbClient) Upload(name string, image []byte) (ImgbbResponse, error) { | |
if len(image) == 0 { | |
return ImgbbResponse{}, fmt.Errorf("image size is zero") | |
} | |
imgData := base64.StdEncoding.EncodeToString(image) | |
resp, err := http.PostForm("https://api.imgbb.com/1/upload", url.Values{"key": {string(client)}, "image": {imgData}, "name": {name}}) | |
if err != nil { | |
return ImgbbResponse{Success: false}, err | |
} | |
defer resp.Body.Close() // ignore unhandled error | |
b, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
return ImgbbResponse{Success: false}, err | |
} | |
r := ImgbbResponse{} | |
err = json.Unmarshal(b, &r) | |
return r, err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment