feat: 重构
This commit is contained in:
50
api.go
Normal file
50
api.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
)
|
||||
|
||||
const backendURL = "http://localhost:3131"
|
||||
|
||||
type StepResponse struct {
|
||||
Actions []Action `json:"actions"`
|
||||
}
|
||||
|
||||
type Action struct {
|
||||
Type string `json:"type"`
|
||||
Path string `json:"path"`
|
||||
NewPath string `json:"new_path,omitempty"`
|
||||
Unzip bool `json:"unzip,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Mirrors []string `json:"mirrors,omitempty"`
|
||||
}
|
||||
|
||||
type actionsReceivedMsg struct{ actions []Action }
|
||||
type apiErrorMsg struct{ err error }
|
||||
|
||||
func fetchActions(code string) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
url := fmt.Sprintf("%s/tools?code=%s", backendURL, code)
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return apiErrorMsg{err: fmt.Errorf("request failed: %w", err)}
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return apiErrorMsg{err: fmt.Errorf("server returned %d: %s", resp.StatusCode, string(body))}
|
||||
}
|
||||
|
||||
var step StepResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&step); err != nil {
|
||||
return apiErrorMsg{err: fmt.Errorf("decode failed: %w", err)}
|
||||
}
|
||||
return actionsReceivedMsg{actions: step.Actions}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user