代码拉取完成,页面将自动刷新
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// App struct
type App struct {
ctx context.Context
}
// NewApp creates a new App application struct
func NewApp() *App {
return &App{}
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
}
func (a *App) DoHttp(config AxiosRequestConfig) AxiosResponse {
resp, _ := doRequest(config)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
bodyStr := string(body)
headers := make(map[string]string)
for key, value := range resp.Header {
headers[key] = strings.Join(value, " ")
}
return AxiosResponse{Status: resp.StatusCode, StatusText: resp.Status, Headers: headers, Config: config, Data: bodyStr}
}
type AxiosRequestConfig struct {
URL string `json:"url,omitempty"`
Method string `json:"method,omitempty"`
BaseURL string `json:"baseURL,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Auth map[string]string `json:"auth,omitempty"`
Params interface{} `json:"params,omitempty"`
Data interface{} `json:"data,omitempty"`
}
type AxiosResponse struct {
Status int `json:"status"`
StatusText string `json:"statusText"`
Headers map[string]string `json:"headers"`
Config AxiosRequestConfig `json:"config"`
Data interface{} `json:"data"`
}
func doRequest(config AxiosRequestConfig) (*http.Response, error) {
client := &http.Client{Timeout: 10 * time.Second}
// Build URL with parameters if any
fullUrl := config.BaseURL + config.URL
if config.Params != nil {
params := url.Values{}
for key, value := range config.Params.(map[string]interface{}) {
if val, ok := value.(string); ok {
params.Add(key, val)
}
}
fullUrl += "?" + params.Encode()
}
// Ceate request
req, err := http.NewRequest(config.Method, fullUrl, nil)
if err != nil {
return nil, err
}
if len(config.Auth) > 0 {
baseAuth := config.Auth["username"] + ":" + config.Auth["password"]
req.Header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(baseAuth)))
}
if len(config.Headers) > 0 {
for key, value := range config.Headers {
req.Header.Add(key, value)
}
}
// Set request body if any
if config.Data != nil {
if strValue, ok := config.Data.(string); ok {
req.Body = io.NopCloser(bytes.NewBuffer([]byte(strValue)))
} else {
byteData, _ := json.Marshal(config.Data)
req.Body = io.NopCloser(bytes.NewBuffer(byteData))
}
}
// Send request
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。