mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-16 13:23:41 +00:00
feat: support RESTful api (#33)
This commit is contained in:
1 parent
e292926697
commit
c6aa83194f
22 files changed
+603
-125
No files matched your search
@@ -0,0 +1,79 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/monkeyWie/gopeed-core/pkg/base"
|
||||
"github.com/monkeyWie/gopeed-core/pkg/download"
|
||||
"github.com/monkeyWie/gopeed-core/pkg/rest/model"
|
||||
"github.com/monkeyWie/gopeed-core/pkg/rest/util"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func Resolve(w http.ResponseWriter, r *http.Request) {
|
||||
var req base.Request
|
||||
if util.ReadJson(w, r, &req) {
|
||||
resource, err := Downloader.Resolve(&req)
|
||||
if err != nil {
|
||||
util.WriteJson(w, 500, model.NewResultWithMsg(err.Error()))
|
||||
return
|
||||
}
|
||||
util.WriteJsonOk(w, model.NewResultWithData(resource))
|
||||
}
|
||||
}
|
||||
|
||||
func CreateTask(w http.ResponseWriter, r *http.Request) {
|
||||
var req model.CreateTaskReq
|
||||
if util.ReadJson(w, r, &req) {
|
||||
taskId, err := Downloader.Create(req.Resource, req.Options)
|
||||
if err != nil {
|
||||
util.WriteJson(w, 500, model.NewResultWithMsg(err.Error()))
|
||||
return
|
||||
}
|
||||
util.WriteJsonOk(w, model.NewResultWithData(taskId))
|
||||
}
|
||||
}
|
||||
|
||||
func PauseTask(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
taskId := vars["id"]
|
||||
Downloader.Pause(taskId)
|
||||
util.WriteJsonOk(w, nil)
|
||||
}
|
||||
|
||||
func ContinueTask(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
taskId := vars["id"]
|
||||
Downloader.Continue(taskId)
|
||||
util.WriteJsonOk(w, nil)
|
||||
}
|
||||
|
||||
func GetTask(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
taskId := vars["id"]
|
||||
task := Downloader.GetTask(taskId)
|
||||
if task == nil {
|
||||
util.WriteJson(w, 404, model.NewResultWithMsg("task not found"))
|
||||
return
|
||||
}
|
||||
util.WriteJsonOk(w, model.NewResultWithData(task))
|
||||
}
|
||||
|
||||
func GetTasks(w http.ResponseWriter, r *http.Request) {
|
||||
status := r.FormValue("status")
|
||||
if status == "" {
|
||||
util.WriteJson(w, 400, model.NewResultWithMsg("param is required: status"))
|
||||
return
|
||||
}
|
||||
statusArr := strings.Split(status, ",")
|
||||
tasks := Downloader.GetTasks()
|
||||
var result []*download.Task
|
||||
for _, task := range tasks {
|
||||
for _, s := range statusArr {
|
||||
if task.Status == base.Status(s) {
|
||||
result = append(result, task)
|
||||
}
|
||||
}
|
||||
}
|
||||
util.WriteJsonOk(w, model.NewResultWithData(tasks))
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package model
|
||||
|
||||
type Result[T any] struct {
|
||||
Msg string `json:"msg"`
|
||||
Data T `json:"data"`
|
||||
}
|
||||
|
||||
func NewResult[T any](msg string, data T) *Result[T] {
|
||||
return &Result[T]{
|
||||
Msg: msg,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
func NewResultWithMsg(msg string) *Result[any] {
|
||||
return NewResult[any](msg, nil)
|
||||
}
|
||||
|
||||
func NewResultWithData[T any](data T) *Result[T] {
|
||||
return NewResult[T]("", data)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package model
|
||||
|
||||
import "github.com/monkeyWie/gopeed-core/pkg/base"
|
||||
|
||||
type CreateTaskReq struct {
|
||||
Resource *base.Resource `json:"resource"`
|
||||
Options *base.Options `json:"options"`
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/monkeyWie/gopeed-core/internal/protocol/bt"
|
||||
fhttp "github.com/monkeyWie/gopeed-core/internal/protocol/http"
|
||||
"github.com/monkeyWie/gopeed-core/pkg/download"
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var (
|
||||
srv *http.Server
|
||||
|
||||
Downloader = download.NewDownloader(new(fhttp.FetcherBuilder), new(bt.FetcherBuilder))
|
||||
)
|
||||
|
||||
func Start(addr string, port int) (int, error) {
|
||||
listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", addr, port))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var r = mux.NewRouter()
|
||||
r.Methods(http.MethodPost).Path("/api/v1/resolve").HandlerFunc(Resolve)
|
||||
r.Methods(http.MethodPost).Path("/api/v1/tasks").HandlerFunc(CreateTask)
|
||||
r.Methods(http.MethodPut).Path("/api/v1/tasks/{id}/pause").HandlerFunc(PauseTask)
|
||||
r.Methods(http.MethodPut).Path("/api/v1/tasks/{id}/continue").HandlerFunc(ContinueTask)
|
||||
r.Methods(http.MethodGet).Path("/api/v1/tasks/{id}").HandlerFunc(GetTask)
|
||||
r.Methods(http.MethodGet).Path("/api/v1/tasks").HandlerFunc(GetTasks)
|
||||
|
||||
srv = &http.Server{Handler: r}
|
||||
go func() {
|
||||
if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
|
||||
// TODO log
|
||||
panic(err)
|
||||
}
|
||||
}()
|
||||
return listener.Addr().(*net.TCPAddr).Port, nil
|
||||
}
|
||||
|
||||
func Stop() error {
|
||||
if srv != nil {
|
||||
return srv.Shutdown(context.TODO())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/monkeyWie/gopeed-core/pkg/base"
|
||||
"github.com/monkeyWie/gopeed-core/pkg/download"
|
||||
"github.com/monkeyWie/gopeed-core/pkg/rest/model"
|
||||
"github.com/monkeyWie/gopeed-core/pkg/test"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var (
|
||||
restPort int
|
||||
|
||||
taskReq = &base.Request{}
|
||||
taskRes = &base.Resource{
|
||||
Req: taskReq,
|
||||
Size: test.BuildSize,
|
||||
Range: true,
|
||||
Files: []*base.FileInfo{
|
||||
{
|
||||
Name: test.BuildName,
|
||||
Path: "",
|
||||
Size: test.BuildSize,
|
||||
},
|
||||
},
|
||||
}
|
||||
createReq = &model.CreateTaskReq{
|
||||
Resource: taskRes,
|
||||
Options: &base.Options{
|
||||
Path: test.Dir,
|
||||
Name: test.DownloadName,
|
||||
Connections: 2,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
func TestResolve(t *testing.T) {
|
||||
doTest(func() {
|
||||
resp := httpRequestCheckOk[*base.Resource](http.MethodPost, "/api/v1/resolve", taskReq)
|
||||
if !reflect.DeepEqual(taskRes, resp) {
|
||||
t.Errorf("Resolve() got = %v, want %v", resp, taskRes)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCreateTask(t *testing.T) {
|
||||
doTest(func() {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
Downloader.Listener(func(event *download.Event) {
|
||||
if event.Key == download.EventKeyFinally {
|
||||
wg.Done()
|
||||
}
|
||||
})
|
||||
|
||||
taskId := httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", createReq)
|
||||
if taskId == "" {
|
||||
t.Fatal("create task failed")
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
want := test.FileMd5(test.BuildFile)
|
||||
got := test.FileMd5(test.DownloadFile)
|
||||
if want != got {
|
||||
t.Errorf("CreateTask() got = %v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestPauseAndContinueTask(t *testing.T) {
|
||||
doTest(func() {
|
||||
type result struct {
|
||||
pauseCount int
|
||||
continueCount int
|
||||
md5 string
|
||||
}
|
||||
|
||||
var got = result{
|
||||
pauseCount: 0,
|
||||
continueCount: 0,
|
||||
md5: "",
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
Downloader.Listener(func(event *download.Event) {
|
||||
switch event.Key {
|
||||
case download.EventKeyPause:
|
||||
got.pauseCount++
|
||||
case download.EventKeyContinue:
|
||||
got.continueCount++
|
||||
case download.EventKeyFinally:
|
||||
wg.Done()
|
||||
}
|
||||
})
|
||||
|
||||
taskId := httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", createReq)
|
||||
t1 := httpRequestCheckOk[*download.Task](http.MethodGet, "/api/v1/tasks/"+taskId, nil)
|
||||
if t1.Status != base.DownloadStatusRunning {
|
||||
t.Errorf("CreateTask() got = %v, want %v", t1.Status, base.DownloadStatusRunning)
|
||||
}
|
||||
httpRequestCheckOk[any](http.MethodPut, "/api/v1/tasks/"+taskId+"/pause", nil)
|
||||
t2 := httpRequestCheckOk[*download.Task](http.MethodGet, "/api/v1/tasks/"+taskId, nil)
|
||||
if t2.Status != base.DownloadStatusPause {
|
||||
t.Errorf("PauseTask() got = %v, want %v", t2.Status, base.DownloadStatusPause)
|
||||
}
|
||||
httpRequestCheckOk[any](http.MethodPut, "/api/v1/tasks/"+taskId+"/continue", nil)
|
||||
t3 := httpRequestCheckOk[*download.Task](http.MethodGet, "/api/v1/tasks/"+taskId, nil)
|
||||
if t3.Status != base.DownloadStatusRunning {
|
||||
t.Errorf("ContinueTask() got = %v, want %v", t3.Status, base.DownloadStatusRunning)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
want := result{
|
||||
pauseCount: 1,
|
||||
continueCount: 1,
|
||||
md5: test.FileMd5(test.BuildFile),
|
||||
}
|
||||
got.md5 = test.FileMd5(test.DownloadFile)
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("PauseAndContinueTask() got = %v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetTasks(t *testing.T) {
|
||||
doTest(func() {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
Downloader.Listener(func(event *download.Event) {
|
||||
if event.Key == download.EventKeyFinally {
|
||||
wg.Done()
|
||||
}
|
||||
})
|
||||
|
||||
httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", createReq)
|
||||
code, _ := httpRequest[[]*download.Task](http.MethodGet, "/api/v1/tasks", nil)
|
||||
checkCode(code, 400)
|
||||
|
||||
wg.Wait()
|
||||
r := httpRequestCheckOk[[]*download.Task](http.MethodGet, "/api/v1/tasks?status=done", nil)
|
||||
if r[0].Status != base.DownloadStatusDone {
|
||||
t.Errorf("GetTasks() got = %v, want %v", r[0].Status, base.DownloadStatusDone)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func doTest(handler func()) {
|
||||
fileListener := doStart()
|
||||
defer func() {
|
||||
fileListener.Close()
|
||||
Stop()
|
||||
}()
|
||||
taskReq.URL = "http://" + fileListener.Addr().String() + "/" + test.BuildName
|
||||
handler()
|
||||
}
|
||||
|
||||
func doStart() net.Listener {
|
||||
port, err := Start("127.0.0.1", 0)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
restPort = port
|
||||
return test.StartTestFileServer()
|
||||
}
|
||||
|
||||
func httpRequest[T any](method string, path string, req any) (int, *model.Result[T]) {
|
||||
var body io.Reader
|
||||
if req != nil {
|
||||
buf, _ := json.Marshal(req)
|
||||
body = bytes.NewBuffer(buf)
|
||||
}
|
||||
|
||||
request, err := http.NewRequest(method, fmt.Sprintf("http://127.0.0.1:%d%s", restPort, path), body)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
var r model.Result[T]
|
||||
if err := json.NewDecoder(response.Body).Decode(&r); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return response.StatusCode, &r
|
||||
}
|
||||
|
||||
func httpRequestCheckOk[T any](method string, path string, req any) T {
|
||||
code, result := httpRequest[T](method, path, req)
|
||||
checkOk(code)
|
||||
return result.Data
|
||||
}
|
||||
|
||||
func checkOk(code int) {
|
||||
checkCode(code, 200)
|
||||
}
|
||||
|
||||
func checkCode(code int, exceptCode int) {
|
||||
if code != exceptCode {
|
||||
panic(fmt.Sprintf("code got = %d, want %d", code, exceptCode))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/monkeyWie/gopeed-core/pkg/rest/model"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func ReadJson(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
|
||||
WriteJson(w, 500, model.NewResultWithMsg(err.Error()))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func WriteJsonOk(w http.ResponseWriter, v any) {
|
||||
WriteJson(w, 200, v)
|
||||
}
|
||||
|
||||
func WriteJson(w http.ResponseWriter, code int, v any) {
|
||||
w.WriteHeader(code)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
Reference in new issue
Block a user