2024-07-30 09:58:18 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
2024-08-29 07:28:41 +00:00
|
|
|
"strings"
|
2024-09-06 03:40:42 +00:00
|
|
|
"time"
|
2024-07-30 09:58:18 +00:00
|
|
|
)
|
|
|
|
|
2024-08-29 07:28:41 +00:00
|
|
|
func GetAuthorizationToken(h http.Header) string {
|
|
|
|
auth := h.Get("Authorization")
|
|
|
|
splitResult := strings.Split(auth, " ")
|
|
|
|
if len(splitResult) > 1 {
|
|
|
|
return splitResult[1]
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2024-07-30 09:58:18 +00:00
|
|
|
func HttpCommon(method, url string, header map[string][]string, reader io.Reader) (int, []byte, error) {
|
2024-09-06 03:40:42 +00:00
|
|
|
header["Content-Type"] = []string{"application/json"}
|
|
|
|
header["User-Agent"] = []string{"Seafile Server"}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
req, err := http.NewRequestWithContext(ctx, method, url, reader)
|
2024-07-30 09:58:18 +00:00
|
|
|
if err != nil {
|
|
|
|
return -1, nil, err
|
|
|
|
}
|
|
|
|
req.Header = header
|
|
|
|
|
|
|
|
rsp, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return -1, nil, err
|
|
|
|
}
|
|
|
|
defer rsp.Body.Close()
|
|
|
|
|
|
|
|
if rsp.StatusCode == http.StatusNotFound {
|
|
|
|
return rsp.StatusCode, nil, fmt.Errorf("url %s not found", url)
|
|
|
|
}
|
2024-09-06 03:40:42 +00:00
|
|
|
|
|
|
|
if rsp.StatusCode != http.StatusOK {
|
|
|
|
return rsp.StatusCode, nil, fmt.Errorf("bad response %d for %s", rsp.StatusCode, url)
|
|
|
|
}
|
|
|
|
|
2024-07-30 09:58:18 +00:00
|
|
|
body, err := io.ReadAll(rsp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return rsp.StatusCode, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return rsp.StatusCode, body, nil
|
|
|
|
}
|