Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

go - Upload a file with POST request golang

I'm new to golang and I'm trying to write a function that uploads a file with a post request to telegram for a bot I'm writing.

I've tried with this code but the error I'm getting from telegram is Bad Request: there is no photo in the request.

I've searched on the net for how to do that, but none of what I found helped me through the problem.

func SendPostRequest (url string, filename string) []byte {
    file, err := os.Open(filename)

    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    response, err := http.Post(url, "binary/octet-stream", file)

    if err != nil {
        log.Fatal(err)
    }
    defer response.Body.Close()

    content, err := ioutil.ReadAll(response.Body)

    if err != nil {
        log.Fatal(err)
    }

    return content
}

The function I'm calling the SendPostRequest from is

func (e Engine) SendPhoto (filename string, chatId int64) APIResponse {
    var url = fmt.Sprintf("%ssendPhoto?chat_id=%d", e.baseUrl, chatId)

    var content []byte = SendPostRequest(url, filename)
    var response APIResponse

    json.Unmarshal(content, &response)
    return response
}

EDIT: The link to the Telegram bot api I'm using in the code is https://core.telegram.org/bots/api

And the api method is https://core.telegram.org/bots/api#sendphoto

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...