1
0
mirror of https://github.com/fumiama/NanoBot.git synced 2026-06-08 12:10:23 +08:00

add: postopenapiof codegen

This commit is contained in:
源文雨
2023-10-10 14:34:36 +09:00
parent 3dbb8d7b34
commit f04743c7a5
5 changed files with 134 additions and 1 deletions

22
http.go
View File

@@ -1,14 +1,17 @@
package nano
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"strings"
)
// NewHTTPEndpointGetRequestWithAuth 新建带鉴权头的 HTTP 请求
// NewHTTPEndpointGetRequestWithAuth 新建带鉴权头的 HTTP GET 请求
func NewHTTPEndpointGetRequestWithAuth(ep string, auth string) (req *http.Request, err error) {
req, err = http.NewRequest("GET", StandardAPI+ep, nil)
if err != nil {
@@ -18,6 +21,16 @@ func NewHTTPEndpointGetRequestWithAuth(ep string, auth string) (req *http.Reques
return
}
// NewHTTPEndpointPostRequestWithAuth 新建带鉴权头的 HTTP POST 请求
func NewHTTPEndpointPostRequestWithAuth(ep string, auth string, body io.Reader) (req *http.Request, err error) {
req, err = http.NewRequest("POST", StandardAPI+ep, body)
if err != nil {
return
}
req.Header.Add("Authorization", auth)
return
}
// WriteHTTPQueryIfNotNil 如果非空则将请求添加到 baseurl 后
//
// ex. WriteHTTPQueryIfNotNil("http://a.com/api", "a", 0, "b", 1, "c", 2) is http://a.com/api?b=1&c=2
@@ -51,3 +64,10 @@ func WriteHTTPQueryIfNotNil(baseurl string, queries ...any) string {
}
return sb.String()[:sb.Len()-1]
}
// WritePostBodyFromJSON 从 json 结构体 ptr 写入 bytes.Buffer, 忽略 error (内部使用不会出错)
func WritePostBodyFromJSON(ptr any) *bytes.Buffer {
buf := bytes.NewBuffer(make([]byte, 0, 1024))
_ = json.NewEncoder(buf).Encode(ptr)
return buf
}