title: Uploading Form Files and Custom Cookies Using Go's Built-in net Library and GoFrame
date: 2021-09-17 13:26:00
toc: true
category:
- Golang
tags: - Golang
- net
- http
- library
- GoFrame
- implementation
- form
- file
- upload
- custom
- Cookie
This article implements using the Go language to call the Chain Drop image bed.
The following image shows two ways to upload the same image to the Chain Drop image bed.
The code is as follows:
package main
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/os/glog"
)
const (
// loginUrl login URL
loginUrl = "https://ld246.com/login"
// uploadImgUrl image upload URL
uploadImgUrl = "https://ld246.com/upload/editor"
// uploadImgUrl = "http://localhost:9999"
// uploadFilePath path of the uploaded file
uploadFilePath = "C:/Users/biuaxia/Downloads/Snipaste_2021-09-07_15-03-20.png"
)
type loginReqData struct {
NameOrEmail string `json:"nameOrEmail"`
UserPassword string `json:"userPassword"`
Captcha string `json:"captcha"`
}
type loginRespData struct {
Msg string `json:"msg"`
Code int `json:"code"`
Goto string `json:"goto"`
TokenName string `json:"tokenName"`
Token string `json:"token"`
}
// main Chain Drop image bed upload interface
func main() {
data := getLoginRespData()
uploadImg(data)
uploadPic(data)
}
// uploadImg implements file upload using goFrame
func uploadImg(data loginRespData) {
m := make(map[string]string)
m[data.TokenName] = data.Token
r, e := g.Client().
Cookie(m).
Post(uploadImgUrl, "file[]=@file:"+uploadFilePath)
if e != nil {
glog.Error(e)
} else {
fmt.Println("uploadImg-resp:", string(r.ReadAll()))
err := r.Close()
if err != nil {
panic(err)
}
}
}
// uploadPic implements file upload using native methods
// key:file contains a file
// multipart/form-data sends a file
func uploadPic(data loginRespData) {
m := make(map[string]string)
m[data.TokenName] = data.Token
var (
buffer = bytes.NewBuffer(nil)
writer = multipart.NewWriter(buffer)
)
formFile, _ := writer.CreateFormFile("file[]", filepath.Base(uploadFilePath))
file, _ := os.Open(uploadFilePath)
_, _ = io.Copy(formFile, file)
defer func(file *os.File) {
err := file.Close()
if err != nil {
panic(err)
}
}(file)
defer func(writer *multipart.Writer) {
err := writer.Close()
if err != nil {
panic(err)
}
}(writer)
req, _ := http.NewRequest("POST", uploadImgUrl, buffer)
req.Header.Set("Content-Type", writer.FormDataContentType())
req = req.WithContext(context.Background())
req.Header.Set("Cookie", data.TokenName+"="+data.Token)
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.47")
resp, _ := http.DefaultClient.Do(req)
readAll, _ := ioutil.ReadAll(resp.Body)
fmt.Println("uploadPic-resp:", string(readAll))
}
// getLoginRespData gets login information, mainly the Token obtained from the response, used to concatenate the Cookie information for the image bed request
func getLoginRespData() loginRespData {
ld := loginReqData{
NameOrEmail: "Your Account",
UserPassword: getPassword("Your Account"),
Captcha: "",
}
// Prepare the request content
reqBody, _ := json.Marshal(ld)
log.Println("Request content:", string(reqBody))
resp, _ := http.Post(loginUrl, "application/json", strings.NewReader(string(reqBody)))
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
panic(err)
}
}(resp.Body)
body, _ := ioutil.ReadAll(resp.Body)
log.Println("Response content:", string(body))
var lrd loginRespData
_ = json.Unmarshal(body, &lrd)
return lrd
}
// getPassword gets the MD5 encrypted content
func getPassword(password string) string {
h := md5.New()
h.Write([]byte(password))
return hex.EncodeToString(h.Sum(nil))
}