1
0
Fork 0
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
pasteapi.go/client_new.go

69 lines
2.0 KiB

// Copyright 2022 Leonid Maslakov. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package pasteapi
import (
"encoding/json"
"net/http"
"net/url"
"strconv"
"strings"
)
type newPasteAnswer struct {
ID string `json:"id"`
CreateTime int64 `json:"createTime"`
DeleteTime int64 `json:"deleteTime"`
}
// New creates a new paste and returns its ID, create time, delete time.
// If the delete time is 0, then the paste will exist forever.
//
// Remember that you observe the limits on header length, body length, and maximum lifetime on your own.
// If this function returns ErrBadRequest, the problem is probably not respecting the limits.
func (server Server) New(newPaste NewPaste) (string, int64, int64, error) {
// Prepare data
data := url.Values{}
data.Add("title", newPaste.Title)
data.Add("body", newPaste.Body) // Required
data.Add("lineEnd", newPaste.LineEnd)
data.Add("syntax", newPaste.Syntax)
data.Add("oneUse", strconv.FormatBool(newPaste.OneUse)) // Default in Go: false
data.Add("expiration", strconv.FormatInt(newPaste.Expiration, 10)) // Default in Go: 0
data.Add("author", newPaste.Author)
data.Add("authorEmail", newPaste.AuthorEmail)
data.Add("authorURL", newPaste.AuthorURL)
// Make POST request
req, err := http.NewRequest("POST", server.Server+"/api/v1/new", strings.NewReader(data.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if server.AuthUser != "" && server.AuthPass != "" {
req.SetBasicAuth(server.AuthUser, server.AuthPass)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", 0, 0, err
}
defer resp.Body.Close()
// Check HTTP response code
err = checkStatus(resp)
if err != nil {
return "", 0, 0, err
}
// Parse answer
var paste newPasteAnswer
err = json.NewDecoder(resp.Body).Decode(&paste)
if err != nil {
return paste.ID, paste.CreateTime, paste.DeleteTime, err
}
return paste.ID, paste.CreateTime, paste.DeleteTime, nil
}