ooni-probe-cli/internal/engine/experiment/dash/collect.go
Simone Basso 273b70bacc
refactor: interfaces and data types into the model package (#642)
## Checklist

- [x] I have read the [contribution guidelines](https://github.com/ooni/probe-cli/blob/master/CONTRIBUTING.md)
- [x] reference issue for this pull request: https://github.com/ooni/probe/issues/1885
- [x] related ooni/spec pull request: N/A

Location of the issue tracker: https://github.com/ooni/probe

## Description

This PR contains a set of changes to move important interfaces and data types into the `./internal/model` package.

The criteria for including an interface or data type in here is roughly that the type should be important and used by several packages. We are especially interested to move more interfaces here to increase modularity.

An additional side effect is that, by reading this package, one should be able to understand more quickly how different parts of the codebase interact with each other.

This is what I want to move in `internal/model`:

- [x] most important interfaces from `internal/netxlite`
- [x] everything that was previously part of `internal/engine/model`
- [x] mocks from `internal/netxlite/mocks` should also be moved in here as a subpackage
2022-01-03 13:53:23 +01:00

58 lines
1.4 KiB
Go

package dash
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"github.com/ooni/probe-cli/v3/internal/model"
)
type collectDeps interface {
HTTPClient() *http.Client
JSONMarshal(v interface{}) ([]byte, error)
Logger() model.Logger
NewHTTPRequest(method string, url string, body io.Reader) (*http.Request, error)
ReadAllContext(ctx context.Context, r io.Reader) ([]byte, error)
Scheme() string
UserAgent() string
}
func collect(ctx context.Context, fqdn, authorization string,
results []clientResults, deps collectDeps) error {
data, err := deps.JSONMarshal(results)
if err != nil {
return err
}
deps.Logger().Debugf("dash: body: %s", string(data))
var URL url.URL
URL.Scheme = deps.Scheme()
URL.Host = fqdn
URL.Path = collectPath
req, err := deps.NewHTTPRequest("POST", URL.String(), bytes.NewReader(data))
if err != nil {
return err
}
req.Header.Set("User-Agent", deps.UserAgent())
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", authorization)
resp, err := deps.HTTPClient().Do(req.WithContext(ctx))
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errHTTPRequestFailed
}
defer resp.Body.Close()
data, err = deps.ReadAllContext(ctx, resp.Body)
if err != nil {
return err
}
deps.Logger().Debugf("dash: body: %s", string(data))
var serverResults []serverResults
return json.Unmarshal(data, &serverResults)
}