diff --git a/README.md b/README.md index 75fdda6..d5262ea 100644 --- a/README.md +++ b/README.md @@ -88,10 +88,20 @@ conversionsTotal := user.ConversionsTotal conversionsConsumed := user.ConversionsConsumed ``` -### Alternative domain +### Set conversion location (optional) + +You can choose from multiple conversion locations, including the EU API location for GDPR compliance. +However, this selection is optional as ConvertAPI automatically detects the nearest server using GEO DNS. +For more details, visit [ConvertAPI Servers Location](https://www.convertapi.com/doc/servers-location). + +```go +// Using convertapi.io server in Europe +u, _ := url.Parse("https://eu-api.convertapi.io") +config.Default = config.New(token, u, nil) +``` How to set an alternative domain can be found in the [advanced example](https://github.com/ConvertAPI/convertapi-go/blob/master/examples/advanced/main.go). -Dedicated to the region [domain list](https://www.convertapi.com/doc/servers-location). + ### More examples diff --git a/convert_test.go b/convert_test.go index 253637b..910a31d 100644 --- a/convert_test.go +++ b/convert_test.go @@ -27,12 +27,12 @@ func TestConvertPath(t *testing.T) { func TestChained(t *testing.T) { config.Default = config.NewDefault(authCred) - jpgRes := convertapi.Convert("docx", "jpg", []param.IParam{ + jpgRes := convertapi.Convert("docx", "jpg", []param.Parameter{ param.NewPath("file", "assets/test.docx", nil), }, nil) - zipRes := convertapi.Convert("any", "zip", []param.IParam{ - param.NewResult("files", jpgRes, nil), + zipRes := convertapi.Convert("any", "zip", []param.Parameter{ + param.NewResult("file", jpgRes, nil), }, nil) zipCost, err := zipRes.Cost() diff --git a/examples/advanced/main.go b/examples/advanced/main.go index 2afa6ca..da96ff7 100644 --- a/examples/advanced/main.go +++ b/examples/advanced/main.go @@ -14,18 +14,18 @@ func main() { token := os.Getenv("API_TOKEN") // Using convertapi.com server in Europe - domain, _ := url.Parse("https://eu-v2.convertapi.com") + u, _ := url.Parse("https://eu-api.convertapi.io") // Using HTTP proxy server proxy, _ := url.Parse("http://127.0.0.1:8888") transport := &http.Transport{Proxy: http.ProxyURL(proxy)} // Setting this configuration as default - config.Default = config.New(token, domain, transport) + config.Default = config.New(token, u, transport) fmt.Println("Converting remote PPTX to PDF") fileParam := param.NewString("file", "https://cdn.convertapi.com/cara/testfiles/presentation.pptx") - pptxRes := convertapi.Convert("pptx", "pdf", []param.IParam{fileParam}, nil) + pptxRes := convertapi.Convert("pptx", "pdf", []param.Parameter{fileParam}, nil) if files, errs := pptxRes.ToPath("/tmp/converted.pdf"); errs == nil { fmt.Println("PDF file saved to: ", files[0].Name()) diff --git a/examples/chaining/main.go b/examples/chaining/main.go index 867ca40..a586138 100644 --- a/examples/chaining/main.go +++ b/examples/chaining/main.go @@ -2,11 +2,12 @@ package main import ( "fmt" + "os" + "github.com/ConvertAPI/convertapi-go/pkg" "github.com/ConvertAPI/convertapi-go/pkg/config" "github.com/ConvertAPI/convertapi-go/pkg/lib" "github.com/ConvertAPI/convertapi-go/pkg/param" - "os" ) func main() { @@ -14,9 +15,9 @@ func main() { fmt.Println("Converting PDF to JPG and compressing result files with ZIP") - jpgRes := convertapi.ConvDef("docx", "jpg", param.NewPath("file", "assets/test.docx", nil)) + jpgRes := convertapi.ConvertDefault("docx", "jpg", param.NewPath("file", "assets/test.docx", nil)) - zipRes := convertapi.ConvDef("jpg", "zip", param.NewResult("files", jpgRes, nil)) + zipRes := convertapi.ConvertDefault("jpg", "zip", param.NewResult("file", jpgRes, nil)) if cost, err := jpgRes.Cost(); lib.PrintErr(err) { fmt.Println("DOCX -> JPG conversion cost: ", cost) @@ -35,4 +36,4 @@ func main() { } else { fmt.Println(errs) } -} \ No newline at end of file +} diff --git a/examples/direct/main.go b/examples/direct/main.go index 1eb7171..c1bf762 100644 --- a/examples/direct/main.go +++ b/examples/direct/main.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "io" "mime" "mime/multipart" @@ -17,7 +18,8 @@ func main() { multipartWriter := multipart.NewWriter(pipeWriter) // Adjust URL according your converter and set API_TOKEN. - req, _ := http.NewRequest("POST", "https://v2.convertapi.com/convert/docx/to/pdf?secret=API_TOKEN", pipeReader) + req, _ := http.NewRequest("POST", "https://api.convertapi.io/v3/convert/docx/to/pdf", pipeReader) + req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", os.Getenv("API_TOKEN"))) req.Header.Set("Content-Type", multipartWriter.FormDataContentType()) req.Header.Set("Accept", "multipart/mixed") @@ -47,4 +49,4 @@ func save(resp *http.Response, file string) { defer resFile.Close() io.Copy(resFile, part) // If conversion returns multiple files, it can be red using multipartReader.NextPart() multiple times. -} \ No newline at end of file +} diff --git a/examples/parallel/main.go b/examples/parallel/main.go index c38345b..b332035 100644 --- a/examples/parallel/main.go +++ b/examples/parallel/main.go @@ -13,8 +13,8 @@ func main() { fmt.Println("Converting DOCX to PDF and JPG in parallel using same source file") fileParam := param.NewPath("file", "assets/test.docx", nil) - pdfRes := convertapi.ConvDef("docx", "pdf", fileParam) - jpgRes := convertapi.ConvDef("docx", "jpg", fileParam) + pdfRes := convertapi.ConvertDefault("docx", "pdf", fileParam) + jpgRes := convertapi.ConvertDefault("docx", "jpg", fileParam) // Downloading and saving files also in parallel c1 := save(pdfRes) @@ -34,4 +34,4 @@ func save(res *convertapi.Result) (finish chan struct{}) { } }() return -} \ No newline at end of file +} diff --git a/examples/remote/main.go b/examples/remote/main.go index 7907a27..4c6eb45 100644 --- a/examples/remote/main.go +++ b/examples/remote/main.go @@ -12,7 +12,7 @@ func main() { config.Default = config.NewDefault(os.Getenv("API_TOKEN")) // Get your token at https://www.convertapi.com/a/authentication fmt.Println("Converting remote PPTX to PDF") - pptxRes := convertapi.ConvDef("pptx", "pdf", + pptxRes := convertapi.ConvertDefault("pptx", "pdf", param.NewString("file", "https://cdn.convertapi.com/public/files/demo.pptx")) if files, errs := pptxRes.ToPath("/tmp/converted.pdf"); errs == nil { @@ -20,4 +20,4 @@ func main() { } else { fmt.Println(errs) } -} \ No newline at end of file +} diff --git a/examples/splitmerge/main.go b/examples/splitmerge/main.go index 9ca0a10..d3ae10e 100644 --- a/examples/splitmerge/main.go +++ b/examples/splitmerge/main.go @@ -12,13 +12,13 @@ func main() { config.Default = config.NewDefault(os.Getenv("API_TOKEN")) // Get your token at https://www.convertapi.com/a/authentication fmt.Println("Creating PDF with the first and the last pages") - splitRes := convertapi.ConvDef("pdf", "split", + splitRes := convertapi.ConvertDefault("pdf", "split", param.NewPath("file", "assets/test.pdf", nil), ) - mergeRes := convertapi.ConvDef("pdf", "merge", - param.NewResultIdx("files", splitRes, 0, nil), - param.NewResultIdx("files", splitRes, -1, nil), + mergeRes := convertapi.ConvertDefault("pdf", "merge", + param.NewResultIdx("file", splitRes, 0, nil), + param.NewResultIdx("file", splitRes, -1, nil), ) if files, errs := mergeRes.ToPath("/tmp"); errs == nil { @@ -26,4 +26,4 @@ func main() { } else { fmt.Println(errs) } -} \ No newline at end of file +} diff --git a/examples/streams/main.go b/examples/streams/main.go index f592d7a..6436d7f 100644 --- a/examples/streams/main.go +++ b/examples/streams/main.go @@ -18,7 +18,7 @@ func main() { reader := strings.NewReader("
My first paragraph.
\n") - htmlRes := convertapi.ConvDef("html", "txt", + htmlRes := convertapi.ConvertDefault("html", "txt", // Reading source file body from the io.Reader param.NewReader("file", reader, "page.html", nil), ) @@ -29,4 +29,4 @@ func main() { if _, err := io.Copy(os.Stdout, htmlRes); err != nil { log.Fatalf("failed to copy data: %s", err) } -} \ No newline at end of file +} diff --git a/examples/thumbnail/main.go b/examples/thumbnail/main.go index 15da9d7..5434cdc 100644 --- a/examples/thumbnail/main.go +++ b/examples/thumbnail/main.go @@ -12,12 +12,12 @@ func main() { config.Default = config.NewDefault(os.Getenv("API_TOKEN")) // Get your token at https://www.convertapi.com/a/authentication fmt.Println("Creating PDF thumbnail") - extractRes := convertapi.ConvDef("pdf", "jpg", + extractRes := convertapi.ConvertDefault("pdf", "jpg", param.NewPath("file", "assets/test.pdf", nil), param.NewString("pagerange", "1"), ) - jpgRes := convertapi.ConvDef("jpg", "jpg", + jpgRes := convertapi.ConvertDefault("jpg", "jpg", param.NewResult("file", extractRes, nil), param.NewBool("scaleimage", true), param.NewBool("scaleproportions", true), @@ -30,4 +30,4 @@ func main() { fmt.Println(errs) } -} \ No newline at end of file +} diff --git a/examples/token/main.go b/examples/token/main.go deleted file mode 100644 index c99027c..0000000 --- a/examples/token/main.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - convertapi "github.com/ConvertAPI/convertapi-go/pkg" - "github.com/ConvertAPI/convertapi-go/pkg/config" - "os" -) - -func main() { - config.Default = config.NewDefault(os.Getenv("CONVERTAPI_TOKEN")) // Get your secret at https://www.convertapi.com/a/access-tokens - - if file, errs := convertapi.ConvertPath("assets/test.docx", "/tmp/result.pdf"); errs == nil { - fmt.Println("PDF file saved to: ", file.Name()) - } else { - fmt.Println(errs) - } -} diff --git a/examples/web/main.go b/examples/web/main.go index 9fba812..68b5f03 100644 --- a/examples/web/main.go +++ b/examples/web/main.go @@ -12,7 +12,7 @@ func main() { config.Default = config.NewDefault(os.Getenv("API_TOKEN")) // Get your token at https://www.convertapi.com/a/authentication fmt.Println("Converting WEB page to PDF") - webRes := convertapi.ConvDef("web", "pdf", + webRes := convertapi.ConvertDefault("web", "pdf", param.NewString("url", "https://en.wikipedia.org/wiki/Data_conversion"), param.NewString("filename", "web-example"), ) @@ -22,4 +22,4 @@ func main() { } else { fmt.Println(errs) } -} \ No newline at end of file +} diff --git a/pkg/config/config.go b/pkg/config/config.go index d6e454d..f5c6a5d 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -10,14 +10,14 @@ var Default *Config type Config struct { BaseURL *url.URL CaTransport *CaTransport - HttpClient *http.Client + HTTPClient *http.Client } func NewDefault(authCred string) *Config { - baseUrl, _ := url.ParseRequestURI("https://v2.convertapi.com") + baseURL, _ := url.ParseRequestURI("https://api.convertapi.io") transport := NewCaTransport(authCred, nil) client := &http.Client{Transport: transport} - return &Config{baseUrl, transport, client} + return &Config{baseURL, transport, client} } func New(authCred string, url *url.URL, transport *http.Transport) *Config { @@ -26,5 +26,5 @@ func New(authCred string, url *url.URL, transport *http.Transport) *Config { } caTransport := NewCaTransport(authCred, transport) - return &Config{BaseURL: url, HttpClient: &http.Client{Transport: caTransport}} + return &Config{BaseURL: url, HTTPClient: &http.Client{Transport: caTransport}} } diff --git a/pkg/config/transport.go b/pkg/config/transport.go index e64b15d..77066b5 100644 --- a/pkg/config/transport.go +++ b/pkg/config/transport.go @@ -3,6 +3,7 @@ package config import ( "fmt" "net/http" + "reflect" "runtime" ) @@ -12,16 +13,16 @@ type CaTransport struct { } func NewCaTransport(authCred string, roundTripper http.RoundTripper) *CaTransport { - if roundTripper == nil { + if roundTripper == nil || (reflect.ValueOf(roundTripper).Kind() == reflect.Ptr && reflect.ValueOf(roundTripper).IsNil()) { roundTripper = http.DefaultTransport } return &CaTransport{roundTripper, authCred} } -func (this *CaTransport) RoundTrip(req *http.Request) (*http.Response, error) { +func (t *CaTransport) RoundTrip(req *http.Request) (*http.Response, error) { runtime.Version() agent := fmt.Sprintf("ConvertAPI-Go/%d (%s)", Version, runtime.GOOS) req.Header.Add("User-Agent", agent) - req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", this.AuthCred)) - return this.RoundTripper.RoundTrip(req) + req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", t.AuthCred)) + return t.RoundTripper.RoundTrip(req) } diff --git a/pkg/convertapi.go b/pkg/convertapi.go index df3cdbd..2090850 100644 --- a/pkg/convertapi.go +++ b/pkg/convertapi.go @@ -2,18 +2,19 @@ package convertapi import ( "fmt" + "net/url" + "os" + "github.com/ConvertAPI/convertapi-go/pkg/config" "github.com/ConvertAPI/convertapi-go/pkg/lib" "github.com/ConvertAPI/convertapi-go/pkg/param" - "net/url" - "os" ) -func ConvDef(fromFormat string, toFormat string, params ...param.IParam) (result *Result) { +func ConvertDefault(fromFormat string, toFormat string, params ...param.Parameter) (result *Result) { return Convert(fromFormat, toFormat, params, nil) } -func Convert(fromFormat string, toFormat string, params []param.IParam, conf *config.Config) (result *Result) { +func Convert(fromFormat string, toFormat string, params []param.Parameter, conf *config.Config) (result *Result) { result = NewResult() go func() { if conf == nil { @@ -28,21 +29,20 @@ func Convert(fromFormat string, toFormat string, params []param.IParam, conf *co return } + values.Add("storefile", "true") for name, vals := range paramVals { if !lib.Contains(ignoreParams, name) { if len(vals) == 1 { values.Add(name, vals[0]) } else { - for i, val := range vals { - values.Add(fmt.Sprintf("%s[%d]", name, i), val) + for _, val := range vals { + values.Add(name, val) } } } } - query := url.Values{} - query.Add("storefile", "true") - path := fmt.Sprintf("/convert/%s/to/%s?%s", fromFormat, toFormat, query.Encode()) + path := fmt.Sprintf("/v3/convert/%s/to/%s", fromFormat, toFormat) pathURL, err := url.Parse(path) if err != nil { result.reject(err) @@ -50,12 +50,12 @@ func Convert(fromFormat string, toFormat string, params []param.IParam, conf *co } convertURL := conf.BaseURL.ResolveReference(pathURL) - result.start(convertURL.String(), values, conf.HttpClient) + result.start(convertURL.String(), values, conf.HTTPClient) }() return } -func prepareValues(params []param.IParam) (vals map[string][]string, err error) { +func prepareValues(params []param.Parameter) (vals map[string][]string, err error) { vals = make(map[string][]string) for _, p := range params { paramVal, err := p.Values() @@ -74,7 +74,7 @@ func prepareValues(params []param.IParam) (vals map[string][]string, err error) } func ConvertPath(fromPath string, toPath string) (file *os.File, errs []error) { - res := Convert(lib.PathExt(fromPath), lib.PathExt(toPath), []param.IParam{ + res := Convert(lib.PathExt(fromPath), lib.PathExt(toPath), []param.Parameter{ param.NewPath("file", fromPath, nil), }, nil) diff --git a/pkg/param/file.go b/pkg/param/file.go index 5469b29..f830427 100644 --- a/pkg/param/file.go +++ b/pkg/param/file.go @@ -18,7 +18,7 @@ func NewFile(name string, file *os.File, conf *config.Config) *ParamFile { return &ParamFile{*paramReader, file.Name()} } -func NewPath(name string, path string, conf *config.Config) IParam { +func NewPath(name string, path string, conf *config.Config) Parameter { file, err := os.Open(path) if err != nil { return NewError(name, err) @@ -26,20 +26,20 @@ func NewPath(name string, path string, conf *config.Config) IParam { return NewFile(name, file, conf) } -func (this *ParamFile) Prepare() error { - file, err := os.Open(this.filePath) +func (pf *ParamFile) Prepare() error { + file, err := os.Open(pf.filePath) if err != nil { return err } - this.reader = file - return this.ParamReader.Prepare() + pf.reader = file + return pf.ParamReader.Prepare() } -func (this *ParamFile) Values() ([]string, error) { - err := this.Prepare() - return this.values, err +func (pf *ParamFile) Values() ([]string, error) { + err := pf.Prepare() + return pf.values, err } -func (this *ParamFile) String() string { - return fmt.Sprintf("%s: %s -> %s", this.name, this.filePath, strings.Join(this.values, " ")) +func (pf *ParamFile) String() string { + return fmt.Sprintf("%s: %s -> %s", pf.name, pf.filePath, strings.Join(pf.values, " ")) } diff --git a/pkg/param/interface.go b/pkg/param/interface.go index 971f037..153cd1a 100644 --- a/pkg/param/interface.go +++ b/pkg/param/interface.go @@ -4,13 +4,13 @@ import ( "github.com/ConvertAPI/convertapi-go/pkg/config" ) -type IParam interface { +type Parameter interface { Prepare() error Name() string Values() ([]string, error) Delete(conf *config.Config) []error } -type IResult interface { - Urls() ([]string, error) +type ResultParameter interface { + Ids() ([]string, error) } diff --git a/pkg/param/param.go b/pkg/param/param.go index 692c14c..60eeb40 100644 --- a/pkg/param/param.go +++ b/pkg/param/param.go @@ -43,30 +43,30 @@ func NewBool(name string, value bool) *Param { return NewString(name, strconv.FormatBool(value)) } -func (this *Param) Prepare() error { - return this.err +func (p *Param) Prepare() error { + return p.err } -func (this *Param) Name() string { - return strings.ToLower(this.name) +func (p *Param) Name() string { + return strings.ToLower(p.name) } -func (this *Param) Values() ([]string, error) { - return this.values, this.err +func (p *Param) Values() ([]string, error) { + return p.values, p.err } -func (this *Param) String() string { - return fmt.Sprintf("%s: %s", this.name, strings.Join(this.values, " ")) +func (p *Param) String() string { + return fmt.Sprintf("%s: %s", p.name, strings.Join(p.values, " ")) } -func (this *Param) Delete(conf *config.Config) (errs []error) { +func (p *Param) Delete(conf *config.Config) (errs []error) { if conf == nil { conf = config.Default } - if urls, err := this.Values(); lib.AddErr(&errs, err) { + if urls, err := p.Values(); lib.AddErr(&errs, err) { for _, val := range urls { if _, err := url.ParseRequestURI(val); lib.AddErr(&errs, err) { - lib.AddErr(&errs, lib.RequestDelete(val, conf.HttpClient)) + lib.AddErr(&errs, lib.RequestDelete(val, conf.HTTPClient)) } } } diff --git a/pkg/param/reader.go b/pkg/param/reader.go index f3d6703..dae8b2b 100644 --- a/pkg/param/reader.go +++ b/pkg/param/reader.go @@ -25,25 +25,25 @@ func NewReader(name string, reader io.Reader, filename string, conf *config.Conf return &ParamReader{*New(name), reader, filename, conf, sync.Mutex{}} } -func (this *ParamReader) Prepare() error { - this.Lock() - defer this.Unlock() +func (pr *ParamReader) Prepare() error { + pr.Lock() + defer pr.Unlock() - if this.values == nil { - if err := this.Param.Prepare(); err != nil { + if pr.values == nil { + if err := pr.Param.Prepare(); err != nil { return err } query := url.Values{} - query.Add("filename", this.fileName) + query.Add("filename", pr.fileName) - pathURL, err := url.Parse("/upload?" + query.Encode()) + pathURL, err := url.Parse("/v3/upload?" + query.Encode()) if err != nil { return err } - uploadURL := this.config.BaseURL.ResolveReference(pathURL) - resp, err := this.config.HttpClient.Post(uploadURL.String(), "application/octet-stream", this.reader) + uploadURL := pr.config.BaseURL.ResolveReference(pathURL) + resp, err := pr.config.HTTPClient.Post(uploadURL.String(), "application/octet-stream", pr.reader) if err != nil { return err @@ -54,16 +54,16 @@ func (this *ParamReader) Prepare() error { if _, err := buf.ReadFrom(resp.Body); err != nil { return err } - this.values = []string{buf.String()} + pr.values = []string{buf.String()} } return nil } -func (this *ParamReader) Values() ([]string, error) { - err := this.Prepare() - return this.values, err +func (pr *ParamReader) Values() ([]string, error) { + err := pr.Prepare() + return pr.values, err } -func (this *ParamReader) String() string { - return fmt.Sprintf("%s: %s -> %s", this.name, this.fileName, strings.Join(this.values, " ")) +func (pr *ParamReader) String() string { + return fmt.Sprintf("%s: %s -> %s", pr.name, pr.fileName, strings.Join(pr.values, " ")) } diff --git a/pkg/param/result.go b/pkg/param/result.go index 911c1ff..4181139 100644 --- a/pkg/param/result.go +++ b/pkg/param/result.go @@ -7,12 +7,12 @@ import ( type ParamResult struct { Param - res IResult + res ResultParameter config *config.Config sync.Mutex } -func NewResult(name string, res IResult, conf *config.Config) (param *ParamResult) { +func NewResult(name string, res ResultParameter, conf *config.Config) (param *ParamResult) { if conf == nil { conf = config.Default } @@ -20,27 +20,27 @@ func NewResult(name string, res IResult, conf *config.Config) (param *ParamResul return } -func (this *ParamResult) Prepare() error { - this.Lock() - defer this.Unlock() +func (pr *ParamResult) Prepare() error { + pr.Lock() + defer pr.Unlock() - if this.values == nil { - if err := this.Param.Prepare(); err != nil { + if pr.values == nil { + if err := pr.Param.Prepare(); err != nil { return err } - urls, err := this.res.Urls() + ids, err := pr.res.Ids() if err != nil { return err } - for _, url := range urls { - this.values = append(this.values, url) + for _, fid := range ids { + pr.values = append(pr.values, fid) } } return nil } -func (this *ParamResult) Values() ([]string, error) { - err := this.Prepare() - return this.values, err +func (pr *ParamResult) Values() ([]string, error) { + err := pr.Prepare() + return pr.values, err } diff --git a/pkg/param/resultidx.go b/pkg/param/resultidx.go index f22e597..9ae5b14 100644 --- a/pkg/param/resultidx.go +++ b/pkg/param/resultidx.go @@ -9,14 +9,14 @@ type ParamResultIdx struct { idx int } -func NewResultIdx(name string, res IResult, idx int, conf *config.Config) *ParamResultIdx { +func NewResultIdx(name string, res ResultParameter, idx int, conf *config.Config) *ParamResultIdx { return &ParamResultIdx{*NewResult(name, res, conf), idx} } -func (this *ParamResultIdx) Values() ([]string, error) { - err := this.ParamResult.Prepare() - if this.idx < 0 { - this.idx = len(this.values) + this.idx +func (pri *ParamResultIdx) Values() ([]string, error) { + err := pri.ParamResult.Prepare() + if pri.idx < 0 { + pri.idx = len(pri.values) + pri.idx } - return []string{this.values[this.idx]}, err + return []string{pri.values[pri.idx]}, err } diff --git a/pkg/resfile.go b/pkg/resfile.go index efb6d16..aaa53f2 100644 --- a/pkg/resfile.go +++ b/pkg/resfile.go @@ -13,45 +13,46 @@ type ResFile struct { resp *http.Response FileName string FileSize int - Url string + FileID string + URL string } -func (this *ResFile) download() (err error) { - if this.resp == nil { - this.resp, err = this.client.Get(this.Url) +func (f *ResFile) download() (err error) { + if f.resp == nil { + f.resp, err = f.client.Get(f.URL) } return } -func (this *ResFile) Read(p []byte) (n int, err error) { - err = this.download() +func (f *ResFile) Read(p []byte) (n int, err error) { + err = f.download() if err == nil { - n, err = this.resp.Body.Read(p) + n, err = f.resp.Body.Read(p) if err != nil { - this.resp.Body.Close() - this.resp = nil + f.resp.Body.Close() + f.resp = nil } } return } -func (this *ResFile) ToFile(file *os.File) (err error) { - _, err = io.Copy(file, this) +func (f *ResFile) ToFile(file *os.File) (err error) { + _, err = io.Copy(file, f) return } -func (this *ResFile) ToPath(path string) (file *os.File, err error) { +func (f *ResFile) ToPath(path string) (file *os.File, err error) { if info, e := os.Stat(path); e == nil && info.IsDir() { - path = filepath.Join(path, this.FileName) + path = filepath.Join(path, f.FileName) } if file, err = os.Create(path); err == nil { defer file.Close() - err = this.ToFile(file) + err = f.ToFile(file) } return } -func (this *ResFile) Delete() error { - return lib.RequestDelete(this.Url, this.client) +func (f *ResFile) Delete() error { + return lib.RequestDelete(f.URL, f.client) } diff --git a/pkg/result.go b/pkg/result.go index a85a92d..402aaa1 100644 --- a/pkg/result.go +++ b/pkg/result.go @@ -23,7 +23,7 @@ func NewResult() *Result { return &Result{make(chan struct{}), nil, nil} } -func (this *Result) start(url string, data *url.Values, client *http.Client) { +func (r *Result) start(url string, data *url.Values, client *http.Client) { if resp, err := lib.RespExtractErr(client.PostForm(url, *data)); err == nil { defer resp.Body.Close() response := &response{} @@ -32,56 +32,66 @@ func (this *Result) start(url string, data *url.Values, client *http.Client) { for _, file := range response.Files { file.client = client } - this.resolve(response) + r.resolve(response) } else { - this.reject(err) + r.reject(err) } } -func (this *Result) Cost() (cost int, err error) { - <-this.waitCh - if this.response != nil { - cost = this.response.ConversionCost +func (r *Result) Cost() (cost int, err error) { + <-r.waitCh + if r.response != nil { + cost = r.response.ConversionCost } - return cost, this.err + return cost, r.err } -func (this *Result) Files() (files []*ResFile, err error) { - <-this.waitCh - if this.response != nil { - files = this.response.Files +func (r *Result) Files() (files []*ResFile, err error) { + <-r.waitCh + if r.response != nil { + files = r.response.Files } - return files, this.err + return files, r.err } -func (this *Result) Urls() (urls []string, err error) { - files, err := this.Files() +func (r *Result) Ids() (ids []string, err error) { + files, err := r.Files() if err == nil { for _, file := range files { - urls = append(urls, file.Url) + ids = append(ids, file.FileID) } } return } -func (this *Result) Read(p []byte) (n int, err error) { - files, err := this.Files() +func (r *Result) Urls() (urls []string, err error) { + files, err := r.Files() + if err == nil { + for _, file := range files { + urls = append(urls, file.URL) + } + } + return +} + +func (r *Result) Read(p []byte) (n int, err error) { + files, err := r.Files() if err == nil { return files[0].Read(p) } return } -func (this *Result) ToFile(file *os.File) (err error) { - files, err := this.Files() +func (r *Result) ToFile(file *os.File) (err error) { + files, err := r.Files() if err == nil { return files[0].ToFile(file) } return } -func (this *Result) ToPath(path string) (files []*os.File, errs []error) { - if resFiles, err := this.Files(); lib.AddErr(&errs, err) { +func (r *Result) ToPath(path string) (files []*os.File, errs []error) { + if resFiles, err := r.Files(); lib.AddErr(&errs, err) { if !lib.IsDir(path) { resFiles = []*ResFile{resFiles[0]} } @@ -95,8 +105,8 @@ func (this *Result) ToPath(path string) (files []*os.File, errs []error) { return } -func (this *Result) Delete() (errs []error) { - if files, err := this.Files(); lib.AddErr(&errs, err) { +func (r *Result) Delete() (errs []error) { + if files, err := r.Files(); lib.AddErr(&errs, err) { for _, file := range files { lib.AddErr(&errs, file.Delete()) } @@ -104,12 +114,12 @@ func (this *Result) Delete() (errs []error) { return } -func (this *Result) resolve(response *response) { - this.response = response - close(this.waitCh) +func (r *Result) resolve(response *response) { + r.response = response + close(r.waitCh) } -func (this *Result) reject(err error) { - this.err = err - close(this.waitCh) +func (r *Result) reject(err error) { + r.err = err + close(r.waitCh) } diff --git a/pkg/user.go b/pkg/user.go index d442eda..854d4b8 100644 --- a/pkg/user.go +++ b/pkg/user.go @@ -24,14 +24,14 @@ func UserInfo(conf *config.Config) (user *User, err error) { conf = config.Default } query := url.Values{} - path := fmt.Sprintf("/user?%s", query.Encode()) + path := fmt.Sprintf("/v3/user?%s", query.Encode()) pathURL, err := url.Parse(path) if err != nil { return } userURL := conf.BaseURL.ResolveReference(pathURL) - resp, err := lib.RespExtractErr(conf.HttpClient.Get(userURL.String())) + resp, err := lib.RespExtractErr(conf.HTTPClient.Get(userURL.String())) if err == nil { defer resp.Body.Close() user = &User{}