Compare commits

..

16 Commits

Author SHA1 Message Date
Adphi
76b69b7acd Fix user in doc.go [skip-ci] 2019-07-30 18:52:32 +00:00
90081d6e8f improved comments 2019-07-23 09:52:34 +02:00
Adphi
5d284c1ad8 Merge branch 'v2' into 'master'
V2

See merge request partitio/Nextcloud-Partitio/gonextcloud!4
2019-07-22 14:56:11 +00:00
5a9b0d715c updated README.md, unexported responses types 2019-07-22 16:40:42 +02:00
85ab4b93f0 updated doc.go 2019-07-22 16:22:10 +02:00
3cf8fdec75 code restructuration: private implementation 2019-07-22 16:17:11 +02:00
7022842ce1 fix webdav: moved to gitlab.bertha.cloud/adphi/gowebdav fork 2019-07-21 01:33:59 +02:00
f3a7e601b4 fix webdav tests 2019-07-20 23:37:16 +02:00
535664608a wip: improved walk performances 2019-07-20 22:49:45 +02:00
ba43e1dcbb wip: fix walk, TODO: find a fix for fileinfo's name 2019-07-20 22:27:54 +02:00
Adphi
04fe0dc872 Merge branch '8-see-filepath-implementation' into 'master'
Resolve "Add Walk to WebDav interface"

Closes #8

See merge request partitio/Nextcloud-Partitio/gonextcloud!3
2019-07-16 06:29:38 +00:00
Adphi
061dc12713 Resolve "Add Walk to WebDav interface" 2019-07-16 06:29:38 +00:00
a9c13d5422 updated .gitlab-ci.yml 2019-07-14 16:06:50 +02:00
Adphi
6deeb69b90 Merge branch '6-add-webdav-api-client' into 'master'
fix #6: added gowebdav and webdav interface (TODO: webdav tests)

Closes #6

See merge request partitio/Nextcloud-Partitio/gonextcloud!2
2019-07-14 13:54:02 +00:00
018fc569d3 fix #6: added gowebdav and webdav interface (TODO: webdav tests) 2019-07-14 15:41:43 +02:00
bb0b884521 fix #7: moved to gomodules 2019-07-14 01:18:42 +02:00
455 changed files with 70176 additions and 67610 deletions

View File

@ -1,17 +1,12 @@
image: golang:1.9
image: golang:1.12
stages:
- test
before_script:
- go get -u golang.org/x/lint/golint
- go get -u github.com/kardianos/govendor
- mkdir -p /go/src/gitlab.bertha.cloud/partitio/Nextcloud-Partitio
- cp -r $CI_PROJECT_DIR /go/src/gitlab.bertha.cloud/partitio/Nextcloud-Partitio
- cd /go/src/gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud
#- sed -i -e 's/$NEXTCLOUD_URL/'${NEXTCLOUD_URL//\//\\/}'/g' config.yml
#- sed -i -e 's/$NEXTCLOUD_PASSWORD/'${NEXTCLOUD_PASSWORD}'/g' config.yml
#- sed -i -e 's/$NEXTCLOUD_EMAIL/'${NEXTCLOUD_EMAIL}'/g' config.yml
- make dep
unit_tests:
@ -40,4 +35,5 @@ lint_code:
tags:
- docker
script:
- make lint
- go get -u golang.org/x/lint/golint
- make lint

View File

@ -11,22 +11,21 @@ lint: ## Lint the files
@golint -set_exit_status ${PKG_LIST}
test: ## Run unittests
@go test -v .
@GO111MODULE=on go test -mod=vendor -v .
race: dep ## Run data race detector
@go test -v -race ${PKG_LIST}
@GO111MODULE=on go test -mod=vendor -v -race ${PKG_LIST}
msan: dep ## Run memory sanitizer
@go test -msan -short ${PKG_LIST}
@GO111MODULE=on go test -mod=vendor -msan -short ${PKG_LIST}
coverage: ## Generate global code coverage report
@mkdir -p cover
@touch cover/${PROJECT_NAME}cov
go tool cover -html=cover/${PROJECT_NAME}cov -o coverage.html
@go tool cover -html=cover/${PROJECT_NAME}cov -o coverage.html
dep: ## Get the dependencies
@mkdir -p vendor
@govendor add +external
@GO111MODULE=on go mod vendor
push: dep lint test coverage ## Push to git repository
@git push origin master

1226
README.md

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
package types
package gonextcloud
//App
// App is a nextcloud application (plugin)
type App struct {
ID string `json:"id"`
Ocsid string `json:"ocsid"`

View File

@ -1,29 +1,29 @@
package gonextcloud
import (
req "github.com/levigross/grequests"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
"net/http"
req "github.com/levigross/grequests"
)
//Apps contains all Apps available actions
type Apps struct {
c *Client
//apps contains all apps available actions
type apps struct {
c *client
}
//List return the list of the Nextcloud Apps
func (a *Apps) List() ([]string, error) {
//List return the list of the Nextcloud apps
func (a *apps) List() ([]string, error) {
res, err := a.c.baseRequest(http.MethodGet, routes.apps, nil)
if err != nil {
return nil, err
}
var r types.AppListResponse
var r appListResponse
res.JSON(&r)
return r.Ocs.Data.Apps, nil
}
//ListEnabled lists the enabled apps
func (a *Apps) ListEnabled() ([]string, error) {
func (a *apps) ListEnabled() ([]string, error) {
ro := &req.RequestOptions{
Params: map[string]string{"filter": "enabled"},
}
@ -31,13 +31,13 @@ func (a *Apps) ListEnabled() ([]string, error) {
if err != nil {
return nil, err
}
var r types.AppListResponse
var r appListResponse
res.JSON(&r)
return r.Ocs.Data.Apps, nil
}
//ListDisabled lists the disabled apps
func (a *Apps) ListDisabled() ([]string, error) {
func (a *apps) ListDisabled() ([]string, error) {
ro := &req.RequestOptions{
Params: map[string]string{"filter": "disabled"},
}
@ -45,30 +45,30 @@ func (a *Apps) ListDisabled() ([]string, error) {
if err != nil {
return nil, err
}
var r types.AppListResponse
var r appListResponse
res.JSON(&r)
return r.Ocs.Data.Apps, nil
}
//Infos return the app's details
func (a *Apps) Infos(name string) (types.App, error) {
func (a *apps) Infos(name string) (App, error) {
res, err := a.c.baseRequest(http.MethodGet, routes.apps, nil, name)
if err != nil {
return types.App{}, err
return App{}, err
}
var r types.AppResponse
var r appResponse
res.JSON(&r)
return r.Ocs.Data, nil
}
//Enable enables an app
func (a *Apps) Enable(name string) error {
func (a *apps) Enable(name string) error {
_, err := a.c.baseRequest(http.MethodPost, routes.apps, nil, name)
return err
}
//Disable disables an app
func (a *Apps) Disable(name string) error {
func (a *apps) Disable(name string) error {
_, err := a.c.baseRequest(http.MethodDelete, routes.apps, nil, name)
return err
}

View File

@ -1,52 +1,52 @@
package gonextcloud
import (
req "github.com/levigross/grequests"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
"net/http"
"sync"
req "github.com/levigross/grequests"
)
//AppsConfig contains all Apps Configuration available actions
type AppsConfig struct {
c *Client
//appsConfig contains all apps Configuration available actions
type appsConfig struct {
c *client
}
//List lists all the available apps
func (a *AppsConfig) List() (apps []string, err error) {
func (a *appsConfig) List() (apps []string, err error) {
res, err := a.c.baseRequest(http.MethodGet, routes.appsConfig, nil)
if err != nil {
return nil, err
}
var r types.AppConfigResponse
var r appConfigResponse
res.JSON(&r)
return r.Ocs.Data.Data, nil
}
//Keys returns the app's config keys
func (a *AppsConfig) Keys(id string) (keys []string, err error) {
func (a *appsConfig) Keys(id string) (keys []string, err error) {
res, err := a.c.baseRequest(http.MethodGet, routes.appsConfig, nil, id)
if err != nil {
return nil, err
}
var r types.AppConfigResponse
var r appConfigResponse
res.JSON(&r)
return r.Ocs.Data.Data, nil
}
//Value get the config value for the given app's key
func (a *AppsConfig) Value(id, key string) (string, error) {
func (a *appsConfig) Value(id, key string) (string, error) {
res, err := a.c.baseRequest(http.MethodGet, routes.appsConfig, nil, id, key)
if err != nil {
return "", err
}
var r types.AppcConfigValueResponse
var r appcConfigValueResponse
res.JSON(&r)
return r.Ocs.Data.Data, nil
}
//SetValue set the config value for the given app's key
func (a *AppsConfig) SetValue(id, key, value string) error {
func (a *appsConfig) SetValue(id, key, value string) error {
ro := &req.RequestOptions{
Data: map[string]string{
"value": value,
@ -57,13 +57,13 @@ func (a *AppsConfig) SetValue(id, key, value string) error {
}
//DeleteValue delete the config value and (!! be careful !!) the key
func (a *AppsConfig) DeleteValue(id, key, value string) error {
func (a *appsConfig) DeleteValue(id, key, value string) error {
_, err := a.c.baseRequest(http.MethodDelete, routes.appsConfig, nil, id, key)
return err
}
//Get returns all apps AppConfigDetails
func (a *AppsConfig) Get() (map[string]map[string]string, error) {
func (a *appsConfig) Get() (map[string]map[string]string, error) {
config := map[string]map[string]string{}
m := sync.Mutex{}
appsIDs, err := a.List()
@ -88,7 +88,7 @@ func (a *AppsConfig) Get() (map[string]map[string]string, error) {
}
//Details returns all the config's key, values pair of the app
func (a *AppsConfig) Details(appID string) (map[string]string, error) {
func (a *appsConfig) Details(appID string) (map[string]string, error) {
config := map[string]string{}
m := sync.Mutex{}
var err error

View File

@ -2,14 +2,14 @@ package gonextcloud
import (
"fmt"
req "github.com/levigross/grequests"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
)
var errUnauthorized = fmt.Errorf("login first")
// Login perform login and create a session with the Nextcloud API.
func (c *Client) Login(username string, password string) error {
func (c *client) Login(username string, password string) error {
c.username = username
c.password = password
options := req.RequestOptions{
@ -23,21 +23,23 @@ func (c *Client) Login(username string, password string) error {
if err != nil {
return err
}
var r types.CapabilitiesResponse
var r capabilitiesResponse
res.JSON(&r)
// No need to check for Ocs.Meta.StatusCode as capabilities are always returned
// No need to check for Ocs.meta.StatusCode as capabilities are always returned
c.capabilities = &r.Ocs.Data.Capabilities
c.version = &r.Ocs.Data.Version
// Check if authentication failed
if !c.loggedIn() {
e := types.APIError{Message: "authentication failed"}
e := APIError{Message: "authentication failed"}
return &e
}
// Create webdav client
c.webdav = newWebDav(c.baseURL.String()+"/remote.php/webdav", c.username, c.password)
return nil
}
// Logout logs out from the Nextcloud API, close the session and delete session's cookie
func (c *Client) Logout() error {
func (c *client) Logout() error {
c.session.CloseIdleConnections()
c.session.HTTPClient.Jar = nil
// Clear capabilities as it is used to check for valid authentication
@ -45,7 +47,7 @@ func (c *Client) Logout() error {
return nil
}
func (c *Client) loggedIn() bool {
func (c *client) loggedIn() bool {
// When authentication failed, capabilities doesn't contains core information
if c.capabilities == nil {
return false

View File

@ -1,6 +1,6 @@
package types
package gonextcloud
//Capabilities
// Capabilities is the capabilities provided by the Nextcloud server
type Capabilities struct {
Core struct {
Pollinterval int `json:"pollinterval"`

View File

@ -1,88 +0,0 @@
package gonextcloud
import (
req "github.com/levigross/grequests"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
"net/url"
)
// Client is the API client that performs all operations against a Nextcloud server.
type Client struct {
baseURL *url.URL
username string
password string
session *req.Session
headers map[string]string
capabilities *types.Capabilities
version *types.Version
apps *Apps
appsConfig *AppsConfig
groupFolders *GroupFolders
notifications *Notifications
shares *Shares
users *Users
groups *Groups
}
// NewClient create a new Client from the Nextcloud Instance URL
func NewClient(hostname string) (*Client, error) {
baseURL, err := url.ParseRequestURI(hostname)
if err != nil {
baseURL, err = url.ParseRequestURI("https://" + hostname)
if err != nil {
return nil, err
}
}
c := &Client{
baseURL: baseURL,
headers: map[string]string{
"OCS-APIREQUEST": "true",
"Accept": "application/json",
},
}
c.apps = &Apps{c}
c.appsConfig = &AppsConfig{c}
c.groupFolders = &GroupFolders{c}
c.notifications = &Notifications{c}
c.shares = &Shares{c}
c.users = &Users{c}
c.groups = &Groups{c}
return c, nil
}
//Apps return the Apps client Interface
func (c *Client) Apps() types.Apps {
return c.apps
}
//AppsConfig return the AppsConfig client Interface
func (c *Client) AppsConfig() types.AppsConfig {
return c.appsConfig
}
//GroupFolders return the GroupFolders client Interface
func (c *Client) GroupFolders() types.GroupFolders {
return c.groupFolders
}
//Notifications return the Notifications client Interface
func (c *Client) Notifications() types.Notifications {
return c.notifications
}
//Shares return the Shares client Interface
func (c *Client) Shares() types.Shares {
return c.shares
}
//Users return the Users client Interface
func (c *Client) Users() types.Users {
return c.users
}
//Groups return the Groups client Interface
func (c *Client) Groups() types.Groups {
return c.groups
}

99
client_impl.go Normal file
View File

@ -0,0 +1,99 @@
package gonextcloud
import (
"net/url"
req "github.com/levigross/grequests"
"gitlab.bertha.cloud/adphi/gowebdav"
)
// client is the API client that performs all operations against a Nextcloud server.
type client struct {
baseURL *url.URL
username string
password string
session *req.Session
headers map[string]string
capabilities *Capabilities
version *Version
apps *apps
appsConfig *appsConfig
groupFolders *groupFolders
notifications *notifications
shares *shares
users *users
groups *groups
webdav *webDav
}
// newClient create a new client from the Nextcloud Instance URL
func newClient(hostname string) (*client, error) {
baseURL, err := url.ParseRequestURI(hostname)
if err != nil {
baseURL, err = url.ParseRequestURI("https://" + hostname)
if err != nil {
return nil, err
}
}
c := &client{
baseURL: baseURL,
headers: map[string]string{
"OCS-APIREQUEST": "true",
"Accept": "application/json",
},
}
c.apps = &apps{c}
c.appsConfig = &appsConfig{c}
c.groupFolders = &groupFolders{c}
c.notifications = &notifications{c}
c.shares = &shares{c}
c.users = &users{c}
c.groups = &groups{c}
// Create empty webdav client
// It will be replaced after login
c.webdav = &webDav{Client: &gowebdav.Client{}}
return c, nil
}
// apps return the apps client Interface
func (c *client) Apps() Apps {
return c.apps
}
// appsConfig return the appsConfig client Interface
func (c *client) AppsConfig() AppsConfig {
return c.appsConfig
}
// groupFolders return the groupFolders client Interface
func (c *client) GroupFolders() GroupFolders {
return c.groupFolders
}
// notifications return the notifications client Interface
func (c *client) Notifications() Notifications {
return c.notifications
}
// shares return the shares client Interface
func (c *client) Shares() Shares {
return c.shares
}
// users return the users client Interface
func (c *client) Users() Users {
return c.users
}
// groups return the groups client Interface
func (c *client) Groups() Groups {
return c.groups
}
// WebDav return the WebDav client Interface
func (c *client) WebDav() WebDav {
return c.webdav
}

View File

@ -5,4 +5,5 @@ app-name: testapp
share-folder: /Documents
not-existing-user: this-user-should-not-exist
not-existing-group: this-group-should-not-exist
email: $NEXTCLOUD_EMAIL
not-existing-folder: this-folder-should-not-exist
email: $NEXTCLOUD_EMAIL

4
doc.go
View File

@ -1,5 +1,5 @@
/*
Package gonextcloud is a Go client for the Nextcloud Provisioning API.
Package gonextcloud is a simple Go Client for Nextcloud's API.
For more information about the Provisioning API, see the documentation:
https://docs.nextcloud.com/server/13/admin_manual/configuration_user/user_provisioning_api.html
@ -34,7 +34,7 @@ For example, to list all the Nextcloud's instance users:
if err != nil {
panic(err)
}
fmt.Println("Users :", users)
fmt.Println("users :", users)
}
*/
package gonextcloud

File diff suppressed because it is too large Load Diff

View File

@ -1,36 +1,36 @@
package types
package gonextcloud
import (
"fmt"
"strings"
)
//APIError contains the returned error code and message from the Nextcloud's API
// APIError contains the returned error code and message from the Nextcloud's API
type APIError struct {
Code int
Message string
}
//ErrorFromMeta return a types.APIError from the Response's types.Meta
func ErrorFromMeta(meta Meta) *APIError {
//errorFromMeta return a types.APIError from the Response's types.meta
func errorFromMeta(meta meta) *APIError {
return &APIError{
meta.Statuscode,
meta.Message,
}
}
//Error return the types.APIError string
// Error return the types.APIError string
func (e *APIError) Error() string {
return fmt.Sprintf("%d : %s", e.Code, e.Message)
}
//UpdateError contains the user's field and corresponding error
// UpdateError contains the user's field and corresponding error
type UpdateError struct {
Field string
Error error
}
//UpdateError contains the errors resulting from a UserUpdate or a UserCreateFull call
// UserUpdateError contains the errors resulting from a UserUpdate or a UserCreateFull call
type UserUpdateError struct {
Errors map[string]error
}
@ -43,8 +43,8 @@ func (e *UserUpdateError) Error() string {
return strings.Join(errors, ", ")
}
//NewUpdateError returns an UpdateError based on an UpdateError channel
func NewUpdateError(errors chan *UpdateError) *UserUpdateError {
//newUpdateError returns an UpdateError based on an UpdateError channel
func newUpdateError(errors chan *UpdateError) *UserUpdateError {
ue := UserUpdateError{map[string]error{}}
for e := range errors {
if e != nil {

View File

@ -1,11 +1,12 @@
package types
package gonextcloud
import (
"errors"
"github.com/stretchr/testify/assert"
"strconv"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
func TestUserUpdateErrors(t *testing.T) {
@ -24,7 +25,7 @@ func TestUserUpdateErrors(t *testing.T) {
}
close(errs)
}()
uerrs := NewUpdateError(errs)
uerrs := newUpdateError(errs)
assert.Equal(t, exp, uerrs.Errors)
assert.NotEmpty(t, uerrs.Error())
}
@ -41,6 +42,6 @@ func TestUserUpdateErrorsNil(t *testing.T) {
wg.Wait()
close(errs)
}()
uerrs := NewUpdateError(errs)
uerrs := newUpdateError(errs)
assert.Nil(t, uerrs)
}

View File

@ -5,4 +5,5 @@ app-name: testapp
share-folder: /Documents
not-existing-user: this-user-should-not-exist
not-existing-group: this-group-should-not-exist
email: my@mail.com
not-existing-folder: this-folder-should-not-exist
email: my@mail.com

18
go.mod Normal file
View File

@ -0,0 +1,18 @@
module gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud
go 1.12
require (
github.com/fatih/structs v0.0.0-20180123065059-ebf56d35bba7
github.com/google/go-querystring v0.0.0-20170111101155-53e6ce116135 // indirect
github.com/kr/pretty v0.1.0 // indirect
github.com/levigross/grequests v0.0.0-20171009010347-bf9788368aa0
github.com/pkg/errors v0.0.0-20181023235946-059132a15dd0
github.com/sirupsen/logrus v1.4.2
github.com/stretchr/testify v1.2.2
gitlab.bertha.cloud/adphi/gowebdav v0.0.0-20190720232020-771eec6e76d0
golang.org/x/net v0.0.0-20190628185345-da137c7871d7 // indirect
golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7 // indirect
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
gopkg.in/yaml.v2 v2.2.1
)

42
go.sum Normal file
View File

@ -0,0 +1,42 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/structs v0.0.0-20180123065059-ebf56d35bba7 h1:bGT+Ub6bpzHl7AAYQhBrZ5nYTAH2SF/848WducU0Ao4=
github.com/fatih/structs v0.0.0-20180123065059-ebf56d35bba7/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/google/go-querystring v0.0.0-20170111101155-53e6ce116135 h1:zLTLjkaOFEFIOxY5BWLFLwh+cL8vOBW4XJ2aqLE/Tf0=
github.com/google/go-querystring v0.0.0-20170111101155-53e6ce116135/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/levigross/grequests v0.0.0-20171009010347-bf9788368aa0 h1:QpdhtrR7SX3R7OlEv9dZarsXogM3PM/tl1ibRH/eHbQ=
github.com/levigross/grequests v0.0.0-20171009010347-bf9788368aa0/go.mod h1:uCZIhROSrVmuF/BPYFPwDeiiQ6juSLp0kikFoEcNcEs=
github.com/pkg/errors v0.0.0-20181023235946-059132a15dd0 h1:R+lX9nKwNd1n7UE5SQAyoorREvRn3aLF6ZndXBoIWqY=
github.com/pkg/errors v0.0.0-20181023235946-059132a15dd0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
gitlab.bertha.cloud/adphi/gowebdav v0.0.0-20190720232020-771eec6e76d0 h1:kjJ5Xn+FgD+QvWP670A2hmdMqxWkOuffMukEA1JSGo4=
gitlab.bertha.cloud/adphi/gowebdav v0.0.0-20190720232020-771eec6e76d0/go.mod h1:Nr6YgM/ZBLPOlAAjcER6HSAXF64AAlal6AJ2CEKg2Fc=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20190628185345-da137c7871d7 h1:rTIdg5QFRR7XCaK4LCjBiPbx8j4DQRpdYMnGn/bJUEU=
golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7 h1:LepdCS8Gf/MVejFIt8lsiexZATdoGVyp5bcyS+rYoUI=
golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View File

@ -1,24 +1,49 @@
package types
package gonextcloud
//Client is the main client interface
import (
"io"
"os"
"path/filepath"
)
// NewClient create a new client
func NewClient(hostname string) (Client, error) {
return newClient(hostname)
}
// Client is the main client interface
type Client interface {
// Nextcloud Apps client
Apps() Apps
// Nextcloud App Config client
AppsConfig() AppsConfig
// Nextcloud Group Folders client
GroupFolders() GroupFolders
// Nextcloud Notifications client
Notifications() Notifications
// Nextcloud Shares client
Shares() Shares
// Nextcloud Users client
Users() Users
// Nextcloud Groups client
Groups() Groups
// Nextcloud WebDav (files) client
WebDav() WebDav
// Nextcloud Monitoring client
Monitoring() (*Monitoring, error)
// Login authorize client
Login(username string, password string) error
// Logout clear connetion and session
Logout() error
}
// Auth is the standard auth methods
type Auth interface {
Login(username string, password string) error
Logout() error
}
//Apps available methods
// Apps available methods
type Apps interface {
List() ([]string, error)
ListEnabled() ([]string, error)
@ -28,7 +53,7 @@ type Apps interface {
Disable(name string) error
}
//AppsConfig available methods
// AppsConfig available methods
type AppsConfig interface {
List() (apps []string, err error)
Keys(id string) (keys []string, err error)
@ -39,7 +64,7 @@ type AppsConfig interface {
Details(appID string) (map[string]string, error)
}
//Groups available methods
// Groups available methods
type Groups interface {
List() ([]string, error)
ListDetails(search string) ([]Group, error)
@ -50,7 +75,7 @@ type Groups interface {
SubAdminList(name string) ([]string, error)
}
//GroupFolders available methods
// GroupFolders available methods
type GroupFolders interface {
List() (map[int]GroupFolder, error)
Get(id int) (GroupFolder, error)
@ -62,7 +87,7 @@ type GroupFolders interface {
SetQuota(folderID int, quota int) error
}
//Notifications available methods
// Notifications available methods
type Notifications interface {
List() ([]Notification, error)
Get(id int) (Notification, error)
@ -73,7 +98,7 @@ type Notifications interface {
Available() error
}
//Shares available methods
// Shares available methods
type Shares interface {
List() ([]Share, error)
GetFromPath(path string, reshares bool, subfiles bool) ([]Share, error)
@ -94,7 +119,7 @@ type Shares interface {
UpdatePermissions(shareID int, permissions SharePermission) error
}
//Users available methods
// Users available methods
type Users interface {
List() ([]string, error)
ListDetails() (map[string]UserDetails, error)
@ -123,3 +148,35 @@ type Users interface {
GroupDemote(name string, group string) error
GroupSubAdminList(name string) ([]string, error)
}
// WebDav available methods
type WebDav interface {
// ReadDir reads the contents of a remote directory
ReadDir(path string) ([]os.FileInfo, error)
// Stat returns the file stats for a specified path
Stat(path string) (os.FileInfo, error)
// Remove removes a remote file
Remove(path string) error
// RemoveAll removes remote files
RemoveAll(path string) error
// Mkdir makes a directory
Mkdir(path string, _ os.FileMode) error
// MkdirAll like mkdir -p, but for webdav
MkdirAll(path string, _ os.FileMode) error
// Rename moves a file from A to B
Rename(oldpath, newpath string, overwrite bool) error
// Copy copies a file from A to B
Copy(oldpath, newpath string, overwrite bool) error
// Read reads the contents of a remote file
Read(path string) ([]byte, error)
// ReadStream reads the stream for a given path
ReadStream(path string) (io.ReadCloser, error)
// Write writes data to a given path
Write(path string, data []byte, _ os.FileMode) error
// WriteStream writes a stream
WriteStream(path string, stream io.Reader, _ os.FileMode) error
// Walk walks the file tree rooted at root, calling walkFn for each file or
// directory in the tree, including root.
Walk(path string, walkFunc filepath.WalkFunc) error
}

View File

@ -2,9 +2,6 @@ package gonextcloud
import (
"fmt"
"github.com/stretchr/testify/assert"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
"gopkg.in/yaml.v2"
"io/ioutil"
"math/rand"
"net/http"
@ -15,6 +12,9 @@ import (
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v2"
)
type Config struct {
@ -25,6 +25,7 @@ type Config struct {
ShareFolder string `yaml:"share-folder"`
NotExistingUser string `yaml:"not-existing-user"`
NotExistingGroup string `yaml:"not-existing-group"`
NotExistingFolder string `yaml:"not-existing-folder"`
Email string `yaml:"email"`
}
@ -34,7 +35,7 @@ type test = func(t *testing.T)
var (
config = Config{}
c *Client
c *client
groupID = 37
provisionningTests = []struct {
string
@ -51,7 +52,7 @@ var (
"create client",
func(t *testing.T) {
var err error
c, err = NewClient(config.URL)
c, err = newClient(config.URL)
assert.NoError(t, err, "aie")
},
},
@ -130,7 +131,7 @@ var (
// return
// }
// username := fmt.Sprintf("%s-2", config.NotExistingUser)
// user := &types.Users{
// user := &types.users{
// ID: username,
// Displayname: strings.ToUpper(username),
// Email: "some@address.com",
@ -139,9 +140,9 @@ var (
// Phone: "42 42 242 424",
// Website: "my.site.com",
// }
// err := c.Users().Create(username, password, user)
// err := c.users().Create(username, password, user)
// assert.NoError(t, err)
// u, err := c.Users().Get(username)
// u, err := c.users().Get(username)
// assert.NoError(t, err)
// o := structs.Map(user)
// r := structs.Map(u)
@ -152,7 +153,7 @@ var (
// assert.Equal(t, o[k], r[k])
// }
// // Clean up
// err = c.Users().Delete(u.ID)
// err = c.users().Delete(u.ID)
// assert.NoError(t, err)
// },
//},
@ -282,8 +283,8 @@ var (
quota := int64(1024 * 1024 * 1024)
err := c.Users().UpdateQuota(config.NotExistingUser, quota)
assert.NoError(t, err)
// TODO : Find better verification : A never connected Users does not have quota available
//u, err := c.Users(config.NotExistingUser)
// TODO : Find better verification : A never connected users does not have quota available
//u, err := c.users(config.NotExistingUser)
//assert.NoError(t, err)
//assert.Equal(t, quota, u.Quota.Quota)
},
@ -406,15 +407,15 @@ var (
{
"TestLoggedIn",
func(t *testing.T) {
c := &Client{}
c.capabilities = &types.Capabilities{}
c := &client{}
c.capabilities = &Capabilities{}
assert.False(t, c.loggedIn())
},
},
{
"TestLoginInvalidURL",
func(t *testing.T) {
c, _ = NewClient("")
c, _ = newClient("")
err := c.Login("", "")
assert.Error(t, err)
},
@ -422,7 +423,7 @@ var (
{
"TestBaseRequest",
func(t *testing.T) {
c, _ = NewClient("")
c, _ = newClient("")
_, err := c.baseRequest(http.MethodGet, routes.capabilities, nil, "admin", "invalid")
assert.Error(t, err)
},
@ -462,10 +463,10 @@ func TestUserCreateBatchWithoutPassword(t *testing.T) {
if c.version.Major < 14 {
t.SkipNow()
}
var us []types.User
var us []User
for i := 0; i < 5; i++ {
u := fmt.Sprintf(config.NotExistingUser+"_%d", i)
us = append(us, types.User{
us = append(us, User{
Username: u,
DisplayName: strings.Title(u),
Groups: []string{"admin"},
@ -546,7 +547,7 @@ func initClient() error {
return err
}
var err error
c, err = NewClient(config.URL)
c, err = newClient(config.URL)
if err != nil {
return err
}

View File

@ -1,6 +1,6 @@
package types
package gonextcloud
//Group
// Group is a Nextcloud group
type Group struct {
ID string `json:"id"`
Displayname string `json:"displayname"`

View File

@ -1,140 +1,58 @@
package gonextcloud
import (
"fmt"
req "github.com/levigross/grequests"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
"net/http"
"strconv"
)
import "strconv"
//GroupFolders contains all Groups Folders available actions
type GroupFolders struct {
c *Client
type groupFolderBadFormatIDAndGroups struct {
ID string `json:"id"`
MountPoint string `json:"mount_point"`
Groups map[string]string `json:"groups"`
Quota string `json:"quota"`
Size int `json:"size"`
}
//List returns the groups folders
func (g *GroupFolders) List() (map[int]types.GroupFolder, error) {
res, err := g.c.baseRequest(http.MethodGet, routes.groupfolders, nil)
if err != nil {
return nil, err
}
var r types.GroupFoldersListResponse
res.JSON(&r)
gfs := formatBadIDAndGroups(r.Ocs.Data)
return gfs, nil
type groupFolderBadFormatGroups struct {
ID int `json:"id"`
MountPoint string `json:"mount_point"`
Groups map[string]string `json:"groups"`
Quota string `json:"quota"`
Size int `json:"size"`
}
//Get returns the group folder details
func (g *GroupFolders) Get(id int) (types.GroupFolder, error) {
res, err := g.c.baseRequest(http.MethodGet, routes.groupfolders, nil, strconv.Itoa(id))
if err != nil {
return types.GroupFolder{}, err
}
var r types.GroupFoldersResponse
res.JSON(&r)
if r.Ocs.Data.ID == 0 {
return types.GroupFolder{}, fmt.Errorf("%d is not a valid groupfolder's id", id)
}
return r.Ocs.Data.FormatGroupFolder(), nil
// GroupFolder is group shared folder from groupfolders application
type GroupFolder struct {
ID int `json:"id"`
MountPoint string `json:"mount_point"`
Groups map[string]SharePermission `json:"groups"`
Quota int `json:"quota"`
Size int `json:"size"`
}
//Create creates a group folder
func (g *GroupFolders) Create(name string) (id int, err error) {
// TODO: Validate Folder name
ro := &req.RequestOptions{
Data: map[string]string{
"mountpoint": name,
},
func (gf *groupFolderBadFormatGroups) FormatGroupFolder() GroupFolder {
g := GroupFolder{}
g.ID = gf.ID
g.MountPoint = gf.MountPoint
g.Groups = map[string]SharePermission{}
for k, v := range gf.Groups {
p, _ := strconv.Atoi(v)
g.Groups[k] = SharePermission(p)
}
res, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro)
if err != nil {
return 0, err
}
var r types.GroupFoldersCreateResponse
res.JSON(&r)
id, _ = strconv.Atoi(r.Ocs.Data.ID)
return id, nil
q, _ := strconv.Atoi(gf.Quota)
g.Quota = q
g.Size = gf.Size
return g
}
//Rename renames the group folder
func (g *GroupFolders) Rename(groupID int, name string) error {
ro := &req.RequestOptions{
Data: map[string]string{
"mountpoint": name,
},
func (gf *groupFolderBadFormatIDAndGroups) FormatGroupFolder() GroupFolder {
g := GroupFolder{}
g.ID, _ = strconv.Atoi(gf.ID)
g.MountPoint = gf.MountPoint
g.Groups = map[string]SharePermission{}
for k, v := range gf.Groups {
p, _ := strconv.Atoi(v)
g.Groups[k] = SharePermission(p)
}
// GroupFolders's response does not give any clues about success or failure
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(groupID), "mountpoint")
if err != nil {
return err
}
return nil
}
//TODO func (c *Client) GroupFoldersDelete(id int) error {
//AddGroup adds group to folder
func (g *GroupFolders) AddGroup(folderID int, groupName string) error {
ro := &req.RequestOptions{
Data: map[string]string{
"group": groupName,
},
}
// GroupFolders's response does not give any clues about success or failure
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "groups")
if err != nil {
return err
}
return nil
}
//RemoveGroup remove a group from the group folder
func (g *GroupFolders) RemoveGroup(folderID int, groupName string) error {
// GroupFolders's response does not give any clues about success or failure
_, err := g.c.baseRequest(http.MethodDelete, routes.groupfolders, nil, strconv.Itoa(folderID), "groups", groupName)
if err != nil {
return err
}
return nil
}
//SetGroupPermissions set groups permissions
func (g *GroupFolders) SetGroupPermissions(folderID int, groupName string, permission types.SharePermission) error {
ro := &req.RequestOptions{
Data: map[string]string{
"permissions": strconv.Itoa(int(permission)),
},
}
// GroupFolders's response does not give any clues about success or failure
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "groups", groupName)
if err != nil {
return err
}
return nil
}
//SetQuota set quota on the group folder. quota in bytes, use -3 for unlimited
func (g *GroupFolders) SetQuota(folderID int, quota int) error {
ro := &req.RequestOptions{
Data: map[string]string{
"quota": strconv.Itoa(int(quota)),
},
}
// GroupFolders's response does not give any clues about success or failure
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "quota")
if err != nil {
return err
}
return nil
}
func formatBadIDAndGroups(g map[string]types.GroupFolderBadFormatIDAndGroups) map[int]types.GroupFolder {
var gfs = map[int]types.GroupFolder{}
for k := range g {
i, _ := strconv.Atoi(k)
d := g[k]
gfs[i] = d.FormatGroupFolder()
}
return gfs
q, _ := strconv.Atoi(gf.Quota)
g.Quota = q
g.Size = gf.Size
return g
}

140
groupfolders_impl.go Normal file
View File

@ -0,0 +1,140 @@
package gonextcloud
import (
"fmt"
"net/http"
"strconv"
req "github.com/levigross/grequests"
)
//groupFolders contains all groups Folders available actions
type groupFolders struct {
c *client
}
//List returns the groups folders
func (g *groupFolders) List() (map[int]GroupFolder, error) {
res, err := g.c.baseRequest(http.MethodGet, routes.groupfolders, nil)
if err != nil {
return nil, err
}
var r groupFoldersListResponse
res.JSON(&r)
gfs := formatBadIDAndGroups(r.Ocs.Data)
return gfs, nil
}
//Get returns the group folder details
func (g *groupFolders) Get(id int) (GroupFolder, error) {
res, err := g.c.baseRequest(http.MethodGet, routes.groupfolders, nil, strconv.Itoa(id))
if err != nil {
return GroupFolder{}, err
}
var r groupFoldersResponse
res.JSON(&r)
if r.Ocs.Data.ID == 0 {
return GroupFolder{}, fmt.Errorf("%d is not a valid groupfolder's id", id)
}
return r.Ocs.Data.FormatGroupFolder(), nil
}
//Create creates a group folder
func (g *groupFolders) Create(name string) (id int, err error) {
// TODO: Validate Folder name
ro := &req.RequestOptions{
Data: map[string]string{
"mountpoint": name,
},
}
res, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro)
if err != nil {
return 0, err
}
var r groupFoldersCreateResponse
res.JSON(&r)
id, _ = strconv.Atoi(r.Ocs.Data.ID)
return id, nil
}
//Rename renames the group folder
func (g *groupFolders) Rename(groupID int, name string) error {
ro := &req.RequestOptions{
Data: map[string]string{
"mountpoint": name,
},
}
// groupFolders's response does not give any clues about success or failure
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(groupID), "mountpoint")
if err != nil {
return err
}
return nil
}
//TODO func (c *client) GroupFoldersDelete(id int) error {
//AddGroup adds group to folder
func (g *groupFolders) AddGroup(folderID int, groupName string) error {
ro := &req.RequestOptions{
Data: map[string]string{
"group": groupName,
},
}
// groupFolders's response does not give any clues about success or failure
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "groups")
if err != nil {
return err
}
return nil
}
//RemoveGroup remove a group from the group folder
func (g *groupFolders) RemoveGroup(folderID int, groupName string) error {
// groupFolders's response does not give any clues about success or failure
_, err := g.c.baseRequest(http.MethodDelete, routes.groupfolders, nil, strconv.Itoa(folderID), "groups", groupName)
if err != nil {
return err
}
return nil
}
//SetGroupPermissions set groups permissions
func (g *groupFolders) SetGroupPermissions(folderID int, groupName string, permission SharePermission) error {
ro := &req.RequestOptions{
Data: map[string]string{
"permissions": strconv.Itoa(int(permission)),
},
}
// groupFolders's response does not give any clues about success or failure
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "groups", groupName)
if err != nil {
return err
}
return nil
}
//SetQuota set quota on the group folder. quota in bytes, use -3 for unlimited
func (g *groupFolders) SetQuota(folderID int, quota int) error {
ro := &req.RequestOptions{
Data: map[string]string{
"quota": strconv.Itoa(int(quota)),
},
}
// groupFolders's response does not give any clues about success or failure
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "quota")
if err != nil {
return err
}
return nil
}
func formatBadIDAndGroups(g map[string]groupFolderBadFormatIDAndGroups) map[int]GroupFolder {
var gfs = map[int]GroupFolder{}
for k := range g {
i, _ := strconv.Atoi(k)
d := g[k]
gfs[i] = d.FormatGroupFolder()
}
return gfs
}

View File

@ -1,9 +1,9 @@
package gonextcloud
import (
"github.com/stretchr/testify/assert"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
"testing"
"github.com/stretchr/testify/assert"
)
var (
@ -53,7 +53,7 @@ var (
{
"TestGroupFoldersSetGroupPermissions",
func(t *testing.T) {
err := c.GroupFolders().SetGroupPermissions(groupID, "admin", types.ReadPermission)
err := c.GroupFolders().SetGroupPermissions(groupID, "admin", ReadPermission)
assert.NoError(t, err)
},
},

View File

@ -1,29 +1,29 @@
package gonextcloud
import (
req "github.com/levigross/grequests"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
"net/http"
req "github.com/levigross/grequests"
)
//Groups contains all Groups available actions
type Groups struct {
c *Client
//groups contains all groups available actions
type groups struct {
c *client
}
//List lists the Nextcloud groups
func (g *Groups) List() ([]string, error) {
func (g *groups) List() ([]string, error) {
res, err := g.c.baseRequest(http.MethodGet, routes.groups, nil)
if err != nil {
return nil, err
}
var r types.GroupListResponse
var r groupListResponse
res.JSON(&r)
return r.Ocs.Data.Groups, nil
}
//ListDetails lists the Nextcloud groups
func (g *Groups) ListDetails(search string) ([]types.Group, error) {
func (g *groups) ListDetails(search string) ([]Group, error) {
ro := &req.RequestOptions{
Params: map[string]string{
"search": search,
@ -33,24 +33,24 @@ func (g *Groups) ListDetails(search string) ([]types.Group, error) {
if err != nil {
return nil, err
}
var r types.GroupListDetailsResponse
var r groupListDetailsResponse
res.JSON(&r)
return r.Ocs.Data.Groups, nil
}
//Users list the group's users
func (g *Groups) Users(name string) ([]string, error) {
//users list the group's users
func (g *groups) Users(name string) ([]string, error) {
res, err := g.c.baseRequest(http.MethodGet, routes.groups, nil, name)
if err != nil {
return nil, err
}
var r types.UserListResponse
var r userListResponse
res.JSON(&r)
return r.Ocs.Data.Users, nil
}
//Search return the list of groups matching the search string
func (g *Groups) Search(search string) ([]string, error) {
func (g *groups) Search(search string) ([]string, error) {
ro := &req.RequestOptions{
Params: map[string]string{"search": search},
}
@ -58,13 +58,13 @@ func (g *Groups) Search(search string) ([]string, error) {
if err != nil {
return nil, err
}
var r types.GroupListResponse
var r groupListResponse
res.JSON(&r)
return r.Ocs.Data.Groups, nil
}
//Create creates a group
func (g *Groups) Create(name string) error {
func (g *groups) Create(name string) error {
ro := &req.RequestOptions{
Data: map[string]string{
"groupid": name,
@ -74,22 +74,22 @@ func (g *Groups) Create(name string) error {
}
//Delete deletes the group
func (g *Groups) Delete(name string) error {
func (g *groups) Delete(name string) error {
return g.baseRequest(http.MethodDelete, nil, name)
}
//SubAdminList lists the group's subadmins
func (g *Groups) SubAdminList(name string) ([]string, error) {
func (g *groups) SubAdminList(name string) ([]string, error) {
res, err := g.c.baseRequest(http.MethodGet, routes.groups, nil, name, "subadmins")
if err != nil {
return nil, err
}
var r types.UserListResponse
var r userListResponse
res.JSON(&r)
return r.Ocs.Data.Users, nil
}
func (g *Groups) baseRequest(method string, ro *req.RequestOptions, subRoute ...string) error {
func (g *groups) baseRequest(method string, ro *req.RequestOptions, subRoute ...string) error {
_, err := g.c.baseRequest(method, routes.groups, ro, subRoute...)
return err
}

View File

@ -2,8 +2,11 @@
package mocks
import mock "github.com/stretchr/testify/mock"
import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
import (
"github.com/stretchr/testify/mock"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
)
// Apps is an autogenerated mock type for the Apps type
type Apps struct {
@ -39,14 +42,14 @@ func (_m *Apps) Enable(name string) error {
}
// Infos provides a mock function with given fields: name
func (_m *Apps) Infos(name string) (types.App, error) {
func (_m *Apps) Infos(name string) (gonextcloud.App, error) {
ret := _m.Called(name)
var r0 types.App
if rf, ok := ret.Get(0).(func(string) types.App); ok {
var r0 gonextcloud.App
if rf, ok := ret.Get(0).(func(string) gonextcloud.App); ok {
r0 = rf(name)
} else {
r0 = ret.Get(0).(types.App)
r0 = ret.Get(0).(gonextcloud.App)
}
var r1 error

View File

@ -2,8 +2,11 @@
package mocks
import mock "github.com/stretchr/testify/mock"
import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
import (
"github.com/stretchr/testify/mock"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
)
// Client is an autogenerated mock type for the Client type
type Client struct {
@ -11,15 +14,15 @@ type Client struct {
}
// Apps provides a mock function with given fields:
func (_m *Client) Apps() types.Apps {
func (_m *Client) Apps() gonextcloud.Apps {
ret := _m.Called()
var r0 types.Apps
if rf, ok := ret.Get(0).(func() types.Apps); ok {
var r0 gonextcloud.Apps
if rf, ok := ret.Get(0).(func() gonextcloud.Apps); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(types.Apps)
r0 = ret.Get(0).(gonextcloud.Apps)
}
}
@ -27,15 +30,15 @@ func (_m *Client) Apps() types.Apps {
}
// AppsConfig provides a mock function with given fields:
func (_m *Client) AppsConfig() types.AppsConfig {
func (_m *Client) AppsConfig() gonextcloud.AppsConfig {
ret := _m.Called()
var r0 types.AppsConfig
if rf, ok := ret.Get(0).(func() types.AppsConfig); ok {
var r0 gonextcloud.AppsConfig
if rf, ok := ret.Get(0).(func() gonextcloud.AppsConfig); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(types.AppsConfig)
r0 = ret.Get(0).(gonextcloud.AppsConfig)
}
}
@ -43,15 +46,15 @@ func (_m *Client) AppsConfig() types.AppsConfig {
}
// GroupFolders provides a mock function with given fields:
func (_m *Client) GroupFolders() types.GroupFolders {
func (_m *Client) GroupFolders() gonextcloud.GroupFolders {
ret := _m.Called()
var r0 types.GroupFolders
if rf, ok := ret.Get(0).(func() types.GroupFolders); ok {
var r0 gonextcloud.GroupFolders
if rf, ok := ret.Get(0).(func() gonextcloud.GroupFolders); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(types.GroupFolders)
r0 = ret.Get(0).(gonextcloud.GroupFolders)
}
}
@ -59,15 +62,15 @@ func (_m *Client) GroupFolders() types.GroupFolders {
}
// Groups provides a mock function with given fields:
func (_m *Client) Groups() types.Groups {
func (_m *Client) Groups() gonextcloud.Groups {
ret := _m.Called()
var r0 types.Groups
if rf, ok := ret.Get(0).(func() types.Groups); ok {
var r0 gonextcloud.Groups
if rf, ok := ret.Get(0).(func() gonextcloud.Groups); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(types.Groups)
r0 = ret.Get(0).(gonextcloud.Groups)
}
}
@ -103,15 +106,15 @@ func (_m *Client) Logout() error {
}
// Notifications provides a mock function with given fields:
func (_m *Client) Notifications() types.Notifications {
func (_m *Client) Notifications() gonextcloud.Notifications {
ret := _m.Called()
var r0 types.Notifications
if rf, ok := ret.Get(0).(func() types.Notifications); ok {
var r0 gonextcloud.Notifications
if rf, ok := ret.Get(0).(func() gonextcloud.Notifications); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(types.Notifications)
r0 = ret.Get(0).(gonextcloud.Notifications)
}
}
@ -119,15 +122,15 @@ func (_m *Client) Notifications() types.Notifications {
}
// Shares provides a mock function with given fields:
func (_m *Client) Shares() types.Shares {
func (_m *Client) Shares() gonextcloud.Shares {
ret := _m.Called()
var r0 types.Shares
if rf, ok := ret.Get(0).(func() types.Shares); ok {
var r0 gonextcloud.Shares
if rf, ok := ret.Get(0).(func() gonextcloud.Shares); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(types.Shares)
r0 = ret.Get(0).(gonextcloud.Shares)
}
}
@ -135,15 +138,15 @@ func (_m *Client) Shares() types.Shares {
}
// Users provides a mock function with given fields:
func (_m *Client) Users() types.Users {
func (_m *Client) Users() gonextcloud.Users {
ret := _m.Called()
var r0 types.Users
if rf, ok := ret.Get(0).(func() types.Users); ok {
var r0 gonextcloud.Users
if rf, ok := ret.Get(0).(func() gonextcloud.Users); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(types.Users)
r0 = ret.Get(0).(gonextcloud.Users)
}
}

View File

@ -2,8 +2,11 @@
package mocks
import mock "github.com/stretchr/testify/mock"
import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
import (
"github.com/stretchr/testify/mock"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
)
// GroupFolders is an autogenerated mock type for the GroupFolders type
type GroupFolders struct {
@ -46,14 +49,14 @@ func (_m *GroupFolders) Create(name string) (int, error) {
}
// Get provides a mock function with given fields: id
func (_m *GroupFolders) Get(id int) (types.GroupFolder, error) {
func (_m *GroupFolders) Get(id int) (gonextcloud.GroupFolder, error) {
ret := _m.Called(id)
var r0 types.GroupFolder
if rf, ok := ret.Get(0).(func(int) types.GroupFolder); ok {
var r0 gonextcloud.GroupFolder
if rf, ok := ret.Get(0).(func(int) gonextcloud.GroupFolder); ok {
r0 = rf(id)
} else {
r0 = ret.Get(0).(types.GroupFolder)
r0 = ret.Get(0).(gonextcloud.GroupFolder)
}
var r1 error
@ -67,15 +70,15 @@ func (_m *GroupFolders) Get(id int) (types.GroupFolder, error) {
}
// List provides a mock function with given fields:
func (_m *GroupFolders) List() (map[int]types.GroupFolder, error) {
func (_m *GroupFolders) List() (map[int]gonextcloud.GroupFolder, error) {
ret := _m.Called()
var r0 map[int]types.GroupFolder
if rf, ok := ret.Get(0).(func() map[int]types.GroupFolder); ok {
var r0 map[int]gonextcloud.GroupFolder
if rf, ok := ret.Get(0).(func() map[int]gonextcloud.GroupFolder); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(map[int]types.GroupFolder)
r0 = ret.Get(0).(map[int]gonextcloud.GroupFolder)
}
}
@ -118,11 +121,11 @@ func (_m *GroupFolders) Rename(groupID int, name string) error {
}
// SetGroupPermissions provides a mock function with given fields: folderID, groupName, permission
func (_m *GroupFolders) SetGroupPermissions(folderID int, groupName string, permission types.SharePermission) error {
func (_m *GroupFolders) SetGroupPermissions(folderID int, groupName string, permission gonextcloud.SharePermission) error {
ret := _m.Called(folderID, groupName, permission)
var r0 error
if rf, ok := ret.Get(0).(func(int, string, types.SharePermission) error); ok {
if rf, ok := ret.Get(0).(func(int, string, gonextcloud.SharePermission) error); ok {
r0 = rf(folderID, groupName, permission)
} else {
r0 = ret.Error(0)

View File

@ -2,8 +2,11 @@
package mocks
import mock "github.com/stretchr/testify/mock"
import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
import (
"github.com/stretchr/testify/mock"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
)
// Groups is an autogenerated mock type for the Groups type
type Groups struct {
@ -62,15 +65,15 @@ func (_m *Groups) List() ([]string, error) {
}
// ListDetails provides a mock function with given fields: search
func (_m *Groups) ListDetails(search string) ([]types.Group, error) {
func (_m *Groups) ListDetails(search string) ([]gonextcloud.Group, error) {
ret := _m.Called(search)
var r0 []types.Group
if rf, ok := ret.Get(0).(func(string) []types.Group); ok {
var r0 []gonextcloud.Group
if rf, ok := ret.Get(0).(func(string) []gonextcloud.Group); ok {
r0 = rf(search)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]types.Group)
r0 = ret.Get(0).([]gonextcloud.Group)
}
}

View File

@ -2,8 +2,11 @@
package mocks
import mock "github.com/stretchr/testify/mock"
import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
import (
"github.com/stretchr/testify/mock"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
)
// Notifications is an autogenerated mock type for the Notifications type
type Notifications struct {
@ -81,14 +84,14 @@ func (_m *Notifications) DeleteAll() error {
}
// Get provides a mock function with given fields: id
func (_m *Notifications) Get(id int) (types.Notification, error) {
func (_m *Notifications) Get(id int) (gonextcloud.Notification, error) {
ret := _m.Called(id)
var r0 types.Notification
if rf, ok := ret.Get(0).(func(int) types.Notification); ok {
var r0 gonextcloud.Notification
if rf, ok := ret.Get(0).(func(int) gonextcloud.Notification); ok {
r0 = rf(id)
} else {
r0 = ret.Get(0).(types.Notification)
r0 = ret.Get(0).(gonextcloud.Notification)
}
var r1 error
@ -102,15 +105,15 @@ func (_m *Notifications) Get(id int) (types.Notification, error) {
}
// List provides a mock function with given fields:
func (_m *Notifications) List() ([]types.Notification, error) {
func (_m *Notifications) List() ([]gonextcloud.Notification, error) {
ret := _m.Called()
var r0 []types.Notification
if rf, ok := ret.Get(0).(func() []types.Notification); ok {
var r0 []gonextcloud.Notification
if rf, ok := ret.Get(0).(func() []gonextcloud.Notification); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]types.Notification)
r0 = ret.Get(0).([]gonextcloud.Notification)
}
}

View File

@ -2,8 +2,11 @@
package mocks
import mock "github.com/stretchr/testify/mock"
import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
import (
"github.com/stretchr/testify/mock"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
)
// Shares is an autogenerated mock type for the Shares type
type Shares struct {
@ -11,18 +14,18 @@ type Shares struct {
}
// Create provides a mock function with given fields: path, shareType, permission, shareWith, publicUpload, password
func (_m *Shares) Create(path string, shareType types.ShareType, permission types.SharePermission, shareWith string, publicUpload bool, password string) (types.Share, error) {
func (_m *Shares) Create(path string, shareType gonextcloud.ShareType, permission gonextcloud.SharePermission, shareWith string, publicUpload bool, password string) (gonextcloud.Share, error) {
ret := _m.Called(path, shareType, permission, shareWith, publicUpload, password)
var r0 types.Share
if rf, ok := ret.Get(0).(func(string, types.ShareType, types.SharePermission, string, bool, string) types.Share); ok {
var r0 gonextcloud.Share
if rf, ok := ret.Get(0).(func(string, gonextcloud.ShareType, gonextcloud.SharePermission, string, bool, string) gonextcloud.Share); ok {
r0 = rf(path, shareType, permission, shareWith, publicUpload, password)
} else {
r0 = ret.Get(0).(types.Share)
r0 = ret.Get(0).(gonextcloud.Share)
}
var r1 error
if rf, ok := ret.Get(1).(func(string, types.ShareType, types.SharePermission, string, bool, string) error); ok {
if rf, ok := ret.Get(1).(func(string, gonextcloud.ShareType, gonextcloud.SharePermission, string, bool, string) error); ok {
r1 = rf(path, shareType, permission, shareWith, publicUpload, password)
} else {
r1 = ret.Error(1)
@ -46,14 +49,14 @@ func (_m *Shares) Delete(shareID int) error {
}
// Get provides a mock function with given fields: shareID
func (_m *Shares) Get(shareID string) (types.Share, error) {
func (_m *Shares) Get(shareID string) (gonextcloud.Share, error) {
ret := _m.Called(shareID)
var r0 types.Share
if rf, ok := ret.Get(0).(func(string) types.Share); ok {
var r0 gonextcloud.Share
if rf, ok := ret.Get(0).(func(string) gonextcloud.Share); ok {
r0 = rf(shareID)
} else {
r0 = ret.Get(0).(types.Share)
r0 = ret.Get(0).(gonextcloud.Share)
}
var r1 error
@ -67,15 +70,15 @@ func (_m *Shares) Get(shareID string) (types.Share, error) {
}
// GetFromPath provides a mock function with given fields: path, reshares, subfiles
func (_m *Shares) GetFromPath(path string, reshares bool, subfiles bool) ([]types.Share, error) {
func (_m *Shares) GetFromPath(path string, reshares bool, subfiles bool) ([]gonextcloud.Share, error) {
ret := _m.Called(path, reshares, subfiles)
var r0 []types.Share
if rf, ok := ret.Get(0).(func(string, bool, bool) []types.Share); ok {
var r0 []gonextcloud.Share
if rf, ok := ret.Get(0).(func(string, bool, bool) []gonextcloud.Share); ok {
r0 = rf(path, reshares, subfiles)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]types.Share)
r0 = ret.Get(0).([]gonextcloud.Share)
}
}
@ -90,15 +93,15 @@ func (_m *Shares) GetFromPath(path string, reshares bool, subfiles bool) ([]type
}
// List provides a mock function with given fields:
func (_m *Shares) List() ([]types.Share, error) {
func (_m *Shares) List() ([]gonextcloud.Share, error) {
ret := _m.Called()
var r0 []types.Share
if rf, ok := ret.Get(0).(func() []types.Share); ok {
var r0 []gonextcloud.Share
if rf, ok := ret.Get(0).(func() []gonextcloud.Share); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]types.Share)
r0 = ret.Get(0).([]gonextcloud.Share)
}
}
@ -113,11 +116,11 @@ func (_m *Shares) List() ([]types.Share, error) {
}
// Update provides a mock function with given fields: shareUpdate
func (_m *Shares) Update(shareUpdate types.ShareUpdate) error {
func (_m *Shares) Update(shareUpdate gonextcloud.ShareUpdate) error {
ret := _m.Called(shareUpdate)
var r0 error
if rf, ok := ret.Get(0).(func(types.ShareUpdate) error); ok {
if rf, ok := ret.Get(0).(func(gonextcloud.ShareUpdate) error); ok {
r0 = rf(shareUpdate)
} else {
r0 = ret.Error(0)
@ -155,11 +158,11 @@ func (_m *Shares) UpdatePassword(shareID int, password string) error {
}
// UpdatePermissions provides a mock function with given fields: shareID, permissions
func (_m *Shares) UpdatePermissions(shareID int, permissions types.SharePermission) error {
func (_m *Shares) UpdatePermissions(shareID int, permissions gonextcloud.SharePermission) error {
ret := _m.Called(shareID, permissions)
var r0 error
if rf, ok := ret.Get(0).(func(int, types.SharePermission) error); ok {
if rf, ok := ret.Get(0).(func(int, gonextcloud.SharePermission) error); ok {
r0 = rf(shareID, permissions)
} else {
r0 = ret.Error(0)

View File

@ -2,8 +2,11 @@
package mocks
import mock "github.com/stretchr/testify/mock"
import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
import (
"github.com/stretchr/testify/mock"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
)
// Users is an autogenerated mock type for the Users type
type Users struct {
@ -11,11 +14,11 @@ type Users struct {
}
// Create provides a mock function with given fields: username, password, user
func (_m *Users) Create(username string, password string, user *types.UserDetails) error {
func (_m *Users) Create(username string, password string, user *gonextcloud.UserDetails) error {
ret := _m.Called(username, password, user)
var r0 error
if rf, ok := ret.Get(0).(func(string, string, *types.UserDetails) error); ok {
if rf, ok := ret.Get(0).(func(string, string, *gonextcloud.UserDetails) error); ok {
r0 = rf(username, password, user)
} else {
r0 = ret.Error(0)
@ -25,11 +28,11 @@ func (_m *Users) Create(username string, password string, user *types.UserDetail
}
// CreateBatchWithoutPassword provides a mock function with given fields: users
func (_m *Users) CreateBatchWithoutPassword(users []types.User) error {
func (_m *Users) CreateBatchWithoutPassword(users []gonextcloud.User) error {
ret := _m.Called(users)
var r0 error
if rf, ok := ret.Get(0).(func([]types.User) error); ok {
if rf, ok := ret.Get(0).(func([]gonextcloud.User) error); ok {
r0 = rf(users)
} else {
r0 = ret.Error(0)
@ -102,15 +105,15 @@ func (_m *Users) Enable(name string) error {
}
// Get provides a mock function with given fields: name
func (_m *Users) Get(name string) (*types.UserDetails, error) {
func (_m *Users) Get(name string) (*gonextcloud.UserDetails, error) {
ret := _m.Called(name)
var r0 *types.UserDetails
if rf, ok := ret.Get(0).(func(string) *types.UserDetails); ok {
var r0 *gonextcloud.UserDetails
if rf, ok := ret.Get(0).(func(string) *gonextcloud.UserDetails); ok {
r0 = rf(name)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*types.UserDetails)
r0 = ret.Get(0).(*gonextcloud.UserDetails)
}
}
@ -250,15 +253,15 @@ func (_m *Users) List() ([]string, error) {
}
// ListDetails provides a mock function with given fields:
func (_m *Users) ListDetails() (map[string]types.UserDetails, error) {
func (_m *Users) ListDetails() (map[string]gonextcloud.UserDetails, error) {
ret := _m.Called()
var r0 map[string]types.UserDetails
if rf, ok := ret.Get(0).(func() map[string]types.UserDetails); ok {
var r0 map[string]gonextcloud.UserDetails
if rf, ok := ret.Get(0).(func() map[string]gonextcloud.UserDetails); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(map[string]types.UserDetails)
r0 = ret.Get(0).(map[string]gonextcloud.UserDetails)
}
}
@ -310,11 +313,11 @@ func (_m *Users) SendWelcomeEmail(name string) error {
}
// Update provides a mock function with given fields: user
func (_m *Users) Update(user *types.UserDetails) error {
func (_m *Users) Update(user *gonextcloud.UserDetails) error {
ret := _m.Called(user)
var r0 error
if rf, ok := ret.Get(0).(func(*types.UserDetails) error); ok {
if rf, ok := ret.Get(0).(func(*gonextcloud.UserDetails) error); ok {
r0 = rf(user)
} else {
r0 = ret.Error(0)

View File

@ -1,17 +1,72 @@
package gonextcloud
import (
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
"net/http"
)
//Monitoring return nextcloud monitoring statistics
func (c *Client) Monitoring() (*types.Monitoring, error) {
res, err := c.baseRequest(http.MethodGet, routes.monitor, nil)
if err != nil {
return nil, err
}
var m types.MonitoringResponse
res.JSON(&m)
return &m.Ocs.Data, nil
// System contains the operating system statistics
type System struct {
Version string `json:"version"`
Theme string `json:"theme"`
EnableAvatars string `json:"enable_avatars"`
EnablePreviews string `json:"enable_previews"`
MemcacheLocal string `json:"memcache.local"`
MemcacheDistributed string `json:"memcache.distributed"`
FilelockingEnabled string `json:"filelocking.enabled"`
MemcacheLocking string `json:"memcache.locking"`
Debug string `json:"debug"`
Freespace int64 `json:"freespace"`
Cpuload []float32 `json:"cpuload"`
MemTotal int `json:"mem_total"`
MemFree int `json:"mem_free"`
SwapTotal int `json:"swap_total"`
SwapFree int `json:"swap_free"`
}
// Monitoring contains the nextcloud monitoring statistics
type Monitoring struct {
// Nextcloud Statistics
Nextcloud struct {
System System `json:"system"`
Storage Storage `json:"storage"`
Shares struct {
NumShares int `json:"num_shares"`
NumSharesUser int `json:"num_shares_user"`
NumSharesGroups int `json:"num_shares_groups"`
NumSharesLink int `json:"num_shares_link"`
NumSharesLinkNoPassword int `json:"num_shares_link_no_password"`
NumFedSharesSent int `json:"num_fed_shares_sent"`
NumFedSharesReceived int `json:"num_fed_shares_received"`
} `json:"shares"`
} `json:"nextcloud"`
// Server statistics
Server struct {
Webserver string `json:"webserver"`
Php struct {
Version string `json:"version"`
MemoryLimit int `json:"memory_limit"`
MaxExecutionTime int `json:"max_execution_time"`
UploadMaxFilesize int `json:"upload_max_filesize"`
} `json:"php"`
Database struct {
Type string `json:"type"`
Version string `json:"version"`
Size int `json:"size"`
} `json:"database"`
} `json:"server"`
// Active users statistics
ActiveUsers ActiveUsers `json:"activeUsers"`
}
// ActiveUsers contains the active users statistics
type ActiveUsers struct {
Last5Minutes int `json:"last5minutes"`
Last1Hour int `json:"last1hour"`
Last24Hours int `json:"last24hours"`
}
// Storage contains the storage statistics
type Storage struct {
NumUsers int `json:"num_users"`
NumFiles int `json:"num_files"`
NumStorages int `json:"num_storages"`
NumStoragesLocal int `json:"num_storages_local"`
NumStoragesHome int `json:"num_storages_home"`
NumStoragesOther int `json:"num_storages_other"`
}

16
monitoring_impl.go Normal file
View File

@ -0,0 +1,16 @@
package gonextcloud
import (
"net/http"
)
//Monitoring return nextcloud monitoring statistics
func (c *client) Monitoring() (*Monitoring, error) {
res, err := c.baseRequest(http.MethodGet, routes.monitor, nil)
if err != nil {
return nil, err
}
var m monitoringResponse
res.JSON(&m)
return &m.Ocs.Data, nil
}

View File

@ -1,7 +1,8 @@
package types
package gonextcloud
import "time"
// Notification is a nextcloud notification (from notification app)
type Notification struct {
NotificationID int `json:"notification_id"`
App string `json:"app"`

View File

@ -2,19 +2,19 @@ package gonextcloud
import (
"errors"
req "github.com/levigross/grequests"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
"net/http"
"strconv"
req "github.com/levigross/grequests"
)
//Notifications contains all Notifications available actions
type Notifications struct {
c *Client
//notifications contains all notifications available actions
type notifications struct {
c *client
}
//List returns all the notifications
func (n *Notifications) List() ([]types.Notification, error) {
func (n *notifications) List() ([]Notification, error) {
if err := n.Available(); err != nil {
return nil, err
}
@ -22,27 +22,27 @@ func (n *Notifications) List() ([]types.Notification, error) {
if err != nil {
return nil, err
}
var r types.NotificationsListResponse
var r notificationsListResponse
res.JSON(&r)
return r.Ocs.Data, nil
}
//Get returns the notification corresponding to the id
func (n *Notifications) Get(id int) (types.Notification, error) {
func (n *notifications) Get(id int) (Notification, error) {
if err := n.Available(); err != nil {
return types.Notification{}, err
return Notification{}, err
}
res, err := n.c.baseRequest(http.MethodGet, routes.notifications, nil, strconv.Itoa(id))
if err != nil {
return types.Notification{}, err
return Notification{}, err
}
var r types.NotificationResponse
var r notificationResponse
res.JSON(&r)
return r.Ocs.Data, nil
}
//Delete deletes the notification corresponding to the id
func (n *Notifications) Delete(id int) error {
func (n *notifications) Delete(id int) error {
if err := n.Available(); err != nil {
return err
}
@ -51,7 +51,7 @@ func (n *Notifications) Delete(id int) error {
}
//DeleteAll deletes all notifications
func (n *Notifications) DeleteAll() error {
func (n *notifications) DeleteAll() error {
if err := n.Available(); err != nil {
return err
}
@ -60,7 +60,7 @@ func (n *Notifications) DeleteAll() error {
}
//Create creates a notification (if the user is an admin)
func (n *Notifications) Create(userID, title, message string) error {
func (n *notifications) Create(userID, title, message string) error {
if err := n.AdminAvailable(); err != nil {
return err
}
@ -75,7 +75,7 @@ func (n *Notifications) Create(userID, title, message string) error {
}
//AdminAvailable returns an error if the admin-notifications app is not installed
func (n *Notifications) AdminAvailable() error {
func (n *notifications) AdminAvailable() error {
if len(n.c.capabilities.Notifications.AdminNotifications) == 0 {
return errors.New("'admin notifications' not available on this instance")
}
@ -83,7 +83,7 @@ func (n *Notifications) AdminAvailable() error {
}
//Available returns an error if the notifications app is not installed
func (n *Notifications) Available() error {
func (n *notifications) Available() error {
if len(n.c.capabilities.Notifications.OcsEndpoints) == 0 {
return errors.New("notifications not available on this instance")
}

View File

@ -1,7 +1,7 @@
package types
package gonextcloud
//Meta
type Meta struct {
//meta
type meta struct {
Status string `json:"status"`
Statuscode int `json:"statuscode"`
Message string `json:"message"`
@ -9,109 +9,109 @@ type Meta struct {
Itemsperpage string `json:"itemsperpage"`
}
//ErrorResponse
type ErrorResponse struct {
//errorResponse
type errorResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data []interface{} `json:"data"`
} `json:"ocs"`
}
//UserListResponse
type UserListResponse struct {
//userListResponse
type userListResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data struct {
Users []string `json:"users"`
} `json:"data"`
} `json:"ocs"`
}
type UserListDetailsResponse struct {
type userListDetailsResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data struct {
Users map[string]UserDetails `json:"users"`
} `json:"data"`
} `json:"ocs"`
}
//UserResponse
type UserResponse struct {
//userResponse
type userResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data UserDetails `json:"data"`
} `json:"ocs"`
}
//BaseResponse
type BaseResponse struct {
//baseResponse
type baseResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data []string `json:"data"`
} `json:"ocs"`
}
//GroupListResponse
type GroupListResponse struct {
//groupListResponse
type groupListResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data struct {
Groups []string `json:"groups"`
} `json:"data"`
} `json:"ocs"`
}
//GroupListDetailsResponse
type GroupListDetailsResponse struct {
//groupListDetailsResponse
type groupListDetailsResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data struct {
Groups []Group `json:"groups"`
} `json:"data"`
} `json:"ocs"`
}
//AppListResponse
type AppListResponse struct {
//appListResponse
type appListResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data struct {
Apps []string `json:"apps"`
} `json:"data"`
} `json:"ocs"`
}
//AppResponse
type AppResponse struct {
//appResponse
type appResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data App `json:"data"`
} `json:"ocs"`
}
type AppConfigResponse struct {
type appConfigResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data struct {
Data []string `json:"data"`
} `json:"data"`
} `json:"ocs"`
}
type AppcConfigValueResponse struct {
type appcConfigValueResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data struct {
Data string `json:"data"`
} `json:"data"`
} `json:"ocs"`
}
//CapabilitiesResponse
type CapabilitiesResponse struct {
//capabilitiesResponse
type capabilitiesResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data struct {
Version Version `json:"version"`
Capabilities Capabilities `json:"capabilities"`
@ -119,6 +119,7 @@ type CapabilitiesResponse struct {
} `json:"ocs"`
}
// Version contains the nextcloud version informations
type Version struct {
Major int `json:"major"`
Minor int `json:"minor"`
@ -127,58 +128,58 @@ type Version struct {
Edition string `json:"edition"`
}
type MonitoringResponse struct {
type monitoringResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data Monitoring `json:"data"`
} `json:"ocs"`
}
type SharesListResponse struct {
type sharesListResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data []Share `json:"data"`
} `json:"ocs"`
}
type SharesResponse struct {
type sharesResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data Share `json:"data"`
} `json:"ocs"`
}
type GroupFoldersListResponse struct {
type groupFoldersListResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Data map[string]GroupFolderBadFormatIDAndGroups `json:"data"`
Meta meta `json:"meta"`
Data map[string]groupFolderBadFormatIDAndGroups `json:"data"`
} `json:"ocs"`
}
type GroupFoldersCreateResponse struct {
type groupFoldersCreateResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Data GroupFolderBadFormatIDAndGroups `json:"data"`
Meta meta `json:"meta"`
Data groupFolderBadFormatIDAndGroups `json:"data"`
} `json:"ocs"`
}
type GroupFoldersResponse struct {
type groupFoldersResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Data GroupFolderBadFormatGroups `json:"data"`
Meta meta `json:"meta"`
Data groupFolderBadFormatGroups `json:"data"`
} `json:"ocs"`
}
type NotificationsListResponse struct {
type notificationsListResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data []Notification `json:"data"`
} `json:"ocs"`
}
type NotificationResponse struct {
type notificationResponse struct {
Ocs struct {
Meta Meta `json:"meta"`
Meta meta `json:"meta"`
Data Notification `json:"data"`
} `json:"ocs"`
}

View File

@ -2,8 +2,8 @@ package gonextcloud
import "net/url"
// Routes references the available routes
type Routes struct {
// apiRoutes references the available routes
type apiRoutes struct {
capabilities *url.URL
users *url.URL
groups *url.URL
@ -20,7 +20,7 @@ const badRequest = 998
var (
apiPath = &url.URL{Path: "/ocs/v2.php"}
routes = Routes{
routes = apiRoutes{
capabilities: &url.URL{Path: apiPath.Path + "/cloud/capabilities"},
users: &url.URL{Path: apiPath.Path + "/cloud/users"},
groups: &url.URL{Path: apiPath.Path + "/cloud/groups"},

228
shares.go
View File

@ -1,174 +1,68 @@
package gonextcloud
import (
"fmt"
req "github.com/levigross/grequests"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
"net/http"
"strconv"
"sync"
// ShareType is the nextcloud shares types enum :
type ShareType int
// SharePermission is the nextcloud share permissions enum
type SharePermission int
const (
// UserShare is a file or folder shared with other user(s)
UserShare ShareType = 0
// GroupShare is a file or folder shared with a group
GroupShare ShareType = 1
// PublicLinkShare is a file or folder shared through public link
PublicLinkShare ShareType = 3
// FederatedCloudShare is a file or folder shared through federated cloud
FederatedCloudShare ShareType = 6
// ReadPermission grant read permission
ReadPermission SharePermission = 1
// UpdatePermission grant update permission
UpdatePermission SharePermission = 2
// CreatePermission grant create permission
CreatePermission SharePermission = 4
// DeletePermission grant delete permission
DeletePermission SharePermission = 8
// ReSharePermission grant resharing permission
ReSharePermission SharePermission = 16
// AllPermissions grant all permissions
AllPermissions SharePermission = 31
)
//Shares contains all Shares available actions
type Shares struct {
c *Client
// ShareUpdate contains the data required in order to update a nextcloud share
type ShareUpdate struct {
ShareID int
Permissions SharePermission
Password string
PublicUpload bool
ExpireDate string
}
//List list all shares of the logged in user
func (s *Shares) List() ([]types.Share, error) {
res, err := s.c.baseRequest(http.MethodGet, routes.shares, nil)
if err != nil {
return nil, err
}
var r types.SharesListResponse
res.JSON(&r)
return r.Ocs.Data, nil
}
//GetFromPath return shares from a specific file or folder
func (s *Shares) GetFromPath(path string, reshares bool, subfiles bool) ([]types.Share, error) {
ro := &req.RequestOptions{
Params: map[string]string{
"path": path,
"reshares": strconv.FormatBool(reshares),
"subfiles": strconv.FormatBool(subfiles),
},
}
res, err := s.c.baseRequest(http.MethodGet, routes.shares, ro)
if err != nil {
return nil, err
}
var r types.SharesListResponse
res.JSON(&r)
return r.Ocs.Data, nil
}
//Get information about a known Share
func (s *Shares) Get(shareID string) (types.Share, error) {
res, err := s.c.baseRequest(http.MethodGet, routes.shares, nil, shareID)
if err != nil {
return types.Share{}, err
}
var r types.SharesListResponse
res.JSON(&r)
return r.Ocs.Data[0], nil
}
//Create create a share
func (s *Shares) Create(
path string,
shareType types.ShareType,
permission types.SharePermission,
shareWith string,
publicUpload bool,
password string,
) (types.Share, error) {
if (shareType == types.UserShare || shareType == types.GroupShare) && shareWith == "" {
return types.Share{}, fmt.Errorf("shareWith cannot be empty for ShareType UserShare or GroupShare")
}
ro := &req.RequestOptions{
Data: map[string]string{
"path": path,
"shareType": strconv.Itoa(int(shareType)),
"shareWith": shareWith,
"publicUpload": strconv.FormatBool(publicUpload),
"password": password,
"permissions": strconv.Itoa(int(permission)),
},
}
res, err := s.c.baseRequest(http.MethodPost, routes.shares, ro)
if err != nil {
return types.Share{}, err
}
var r types.SharesResponse
res.JSON(&r)
return r.Ocs.Data, nil
}
//Delete Remove the given share.
func (s *Shares) Delete(shareID int) error {
_, err := s.c.baseRequest(http.MethodDelete, routes.shares, nil, strconv.Itoa(shareID))
return err
}
// Update update share details
// expireDate expireDate expects a well formatted date string, e.g. YYYY-MM-DD
func (s *Shares) Update(shareUpdate types.ShareUpdate) error {
errs := make(chan *types.UpdateError)
var wg sync.WaitGroup
wg.Add(4)
go func() {
defer wg.Done()
if err := s.UpdatePassword(shareUpdate.ShareID, shareUpdate.Password); err != nil {
errs <- &types.UpdateError{
Field: "password",
Error: err,
}
}
}()
go func() {
defer wg.Done()
if err := s.UpdateExpireDate(shareUpdate.ShareID, shareUpdate.ExpireDate); err != nil {
errs <- &types.UpdateError{
Field: "expireDate",
Error: err,
}
}
}()
go func() {
defer wg.Done()
if err := s.UpdatePermissions(shareUpdate.ShareID, shareUpdate.Permissions); err != nil {
errs <- &types.UpdateError{
Field: "permissions",
Error: err,
}
}
}()
go func() {
defer wg.Done()
if err := s.UpdatePublicUpload(shareUpdate.ShareID, shareUpdate.PublicUpload); err != nil {
errs <- &types.UpdateError{
Field: "publicUpload",
Error: err,
}
}
}()
go func() {
wg.Wait()
close(errs)
}()
if err := types.NewUpdateError(errs); err != nil {
return err
}
return nil
}
//UpdateExpireDate updates the share's expire date
// expireDate expects a well formatted date string, e.g. YYYY-MM-DD
func (s *Shares) UpdateExpireDate(shareID int, expireDate string) error {
return s.baseShareUpdate(strconv.Itoa(shareID), "expireDate", expireDate)
}
//UpdatePublicUpload enable or disable public upload
func (s *Shares) UpdatePublicUpload(shareID int, public bool) error {
return s.baseShareUpdate(strconv.Itoa(shareID), "publicUpload", strconv.FormatBool(public))
}
//UpdatePassword updates share password
func (s *Shares) UpdatePassword(shareID int, password string) error {
return s.baseShareUpdate(strconv.Itoa(shareID), "password", password)
}
//UpdatePermissions update permissions
func (s *Shares) UpdatePermissions(shareID int, permissions types.SharePermission) error {
return s.baseShareUpdate(strconv.Itoa(shareID), "permissions", strconv.Itoa(int(permissions)))
}
func (s *Shares) baseShareUpdate(shareID string, key string, value string) error {
ro := &req.RequestOptions{
Data: map[string]string{key: value},
}
_, err := s.c.baseRequest(http.MethodPut, routes.shares, ro, shareID)
return err
// Share is a nextcloud share
type Share struct {
ID string `json:"id"`
ShareType int `json:"share_type"`
UIDOwner string `json:"uid_owner"`
DisplaynameOwner string `json:"displayname_owner"`
Permissions int `json:"permissions"`
Stime int `json:"stime"`
Parent interface{} `json:"parent"`
Expiration string `json:"expiration"`
Token string `json:"token"`
UIDFileOwner string `json:"uid_file_owner"`
DisplaynameFileOwner string `json:"displayname_file_owner"`
Path string `json:"path"`
ItemType string `json:"item_type"`
Mimetype string `json:"mimetype"`
StorageID string `json:"storage_id"`
Storage int `json:"storage"`
ItemSource int `json:"item_source"`
FileSource int `json:"file_source"`
FileParent int `json:"file_parent"`
FileTarget string `json:"file_target"`
ShareWith string `json:"share_with"`
ShareWithDisplayname string `json:"share_with_displayname"`
MailSend int `json:"mail_send"`
Tags []string `json:"tags"`
}

174
shares_impl.go Normal file
View File

@ -0,0 +1,174 @@
package gonextcloud
import (
"fmt"
"net/http"
"strconv"
"sync"
req "github.com/levigross/grequests"
)
//shares contains all shares available actions
type shares struct {
c *client
}
//List list all shares of the logged in user
func (s *shares) List() ([]Share, error) {
res, err := s.c.baseRequest(http.MethodGet, routes.shares, nil)
if err != nil {
return nil, err
}
var r sharesListResponse
res.JSON(&r)
return r.Ocs.Data, nil
}
//GetFromPath return shares from a specific file or folder
func (s *shares) GetFromPath(path string, reshares bool, subfiles bool) ([]Share, error) {
ro := &req.RequestOptions{
Params: map[string]string{
"path": path,
"reshares": strconv.FormatBool(reshares),
"subfiles": strconv.FormatBool(subfiles),
},
}
res, err := s.c.baseRequest(http.MethodGet, routes.shares, ro)
if err != nil {
return nil, err
}
var r sharesListResponse
res.JSON(&r)
return r.Ocs.Data, nil
}
//Get information about a known Share
func (s *shares) Get(shareID string) (Share, error) {
res, err := s.c.baseRequest(http.MethodGet, routes.shares, nil, shareID)
if err != nil {
return Share{}, err
}
var r sharesListResponse
res.JSON(&r)
return r.Ocs.Data[0], nil
}
//Create create a share
func (s *shares) Create(
path string,
shareType ShareType,
permission SharePermission,
shareWith string,
publicUpload bool,
password string,
) (Share, error) {
if (shareType == UserShare || shareType == GroupShare) && shareWith == "" {
return Share{}, fmt.Errorf("shareWith cannot be empty for ShareType UserShare or GroupShare")
}
ro := &req.RequestOptions{
Data: map[string]string{
"path": path,
"shareType": strconv.Itoa(int(shareType)),
"shareWith": shareWith,
"publicUpload": strconv.FormatBool(publicUpload),
"password": password,
"permissions": strconv.Itoa(int(permission)),
},
}
res, err := s.c.baseRequest(http.MethodPost, routes.shares, ro)
if err != nil {
return Share{}, err
}
var r sharesResponse
res.JSON(&r)
return r.Ocs.Data, nil
}
//Delete Remove the given share.
func (s *shares) Delete(shareID int) error {
_, err := s.c.baseRequest(http.MethodDelete, routes.shares, nil, strconv.Itoa(shareID))
return err
}
// Update update share details
// expireDate expireDate expects a well formatted date string, e.g. YYYY-MM-DD
func (s *shares) Update(shareUpdate ShareUpdate) error {
errs := make(chan *UpdateError)
var wg sync.WaitGroup
wg.Add(4)
go func() {
defer wg.Done()
if err := s.UpdatePassword(shareUpdate.ShareID, shareUpdate.Password); err != nil {
errs <- &UpdateError{
Field: "password",
Error: err,
}
}
}()
go func() {
defer wg.Done()
if err := s.UpdateExpireDate(shareUpdate.ShareID, shareUpdate.ExpireDate); err != nil {
errs <- &UpdateError{
Field: "expireDate",
Error: err,
}
}
}()
go func() {
defer wg.Done()
if err := s.UpdatePermissions(shareUpdate.ShareID, shareUpdate.Permissions); err != nil {
errs <- &UpdateError{
Field: "permissions",
Error: err,
}
}
}()
go func() {
defer wg.Done()
if err := s.UpdatePublicUpload(shareUpdate.ShareID, shareUpdate.PublicUpload); err != nil {
errs <- &UpdateError{
Field: "publicUpload",
Error: err,
}
}
}()
go func() {
wg.Wait()
close(errs)
}()
if err := newUpdateError(errs); err != nil {
return err
}
return nil
}
//UpdateExpireDate updates the share's expire date
// expireDate expects a well formatted date string, e.g. YYYY-MM-DD
func (s *shares) UpdateExpireDate(shareID int, expireDate string) error {
return s.baseShareUpdate(strconv.Itoa(shareID), "expireDate", expireDate)
}
//UpdatePublicUpload enable or disable public upload
func (s *shares) UpdatePublicUpload(shareID int, public bool) error {
return s.baseShareUpdate(strconv.Itoa(shareID), "publicUpload", strconv.FormatBool(public))
}
//UpdatePassword updates share password
func (s *shares) UpdatePassword(shareID int, password string) error {
return s.baseShareUpdate(strconv.Itoa(shareID), "password", password)
}
//UpdatePermissions update permissions
func (s *shares) UpdatePermissions(shareID int, permissions SharePermission) error {
return s.baseShareUpdate(strconv.Itoa(shareID), "permissions", strconv.Itoa(int(permissions)))
}
func (s *shares) baseShareUpdate(shareID string, key string, value string) error {
ro := &req.RequestOptions{
Data: map[string]string{key: value},
}
_, err := s.c.baseRequest(http.MethodPut, routes.shares, ro, shareID)
return err
}

View File

@ -1,57 +0,0 @@
package types
import "strconv"
type GroupFolderBadFormatIDAndGroups struct {
ID string `json:"id"`
MountPoint string `json:"mount_point"`
Groups map[string]string `json:"groups"`
Quota string `json:"quota"`
Size int `json:"size"`
}
type GroupFolderBadFormatGroups struct {
ID int `json:"id"`
MountPoint string `json:"mount_point"`
Groups map[string]string `json:"groups"`
Quota string `json:"quota"`
Size int `json:"size"`
}
type GroupFolder struct {
ID int `json:"id"`
MountPoint string `json:"mount_point"`
Groups map[string]SharePermission `json:"groups"`
Quota int `json:"quota"`
Size int `json:"size"`
}
func (gf *GroupFolderBadFormatGroups) FormatGroupFolder() GroupFolder {
g := GroupFolder{}
g.ID = gf.ID
g.MountPoint = gf.MountPoint
g.Groups = map[string]SharePermission{}
for k, v := range gf.Groups {
p, _ := strconv.Atoi(v)
g.Groups[k] = SharePermission(p)
}
q, _ := strconv.Atoi(gf.Quota)
g.Quota = q
g.Size = gf.Size
return g
}
func (gf *GroupFolderBadFormatIDAndGroups) FormatGroupFolder() GroupFolder {
g := GroupFolder{}
g.ID, _ = strconv.Atoi(gf.ID)
g.MountPoint = gf.MountPoint
g.Groups = map[string]SharePermission{}
for k, v := range gf.Groups {
p, _ := strconv.Atoi(v)
g.Groups[k] = SharePermission(p)
}
q, _ := strconv.Atoi(gf.Quota)
g.Quota = q
g.Size = gf.Size
return g
}

View File

@ -1,65 +0,0 @@
package types
type System struct {
Version string `json:"version"`
Theme string `json:"theme"`
EnableAvatars string `json:"enable_avatars"`
EnablePreviews string `json:"enable_previews"`
MemcacheLocal string `json:"memcache.local"`
MemcacheDistributed string `json:"memcache.distributed"`
FilelockingEnabled string `json:"filelocking.enabled"`
MemcacheLocking string `json:"memcache.locking"`
Debug string `json:"debug"`
Freespace int64 `json:"freespace"`
Cpuload []float32 `json:"cpuload"`
MemTotal int `json:"mem_total"`
MemFree int `json:"mem_free"`
SwapTotal int `json:"swap_total"`
SwapFree int `json:"swap_free"`
}
type Monitoring struct {
Nextcloud struct {
System System `json:"system"`
Storage Storage `json:"storage"`
Shares struct {
NumShares int `json:"num_shares"`
NumSharesUser int `json:"num_shares_user"`
NumSharesGroups int `json:"num_shares_groups"`
NumSharesLink int `json:"num_shares_link"`
NumSharesLinkNoPassword int `json:"num_shares_link_no_password"`
NumFedSharesSent int `json:"num_fed_shares_sent"`
NumFedSharesReceived int `json:"num_fed_shares_received"`
} `json:"shares"`
} `json:"nextcloud"`
Server struct {
Webserver string `json:"webserver"`
Php struct {
Version string `json:"version"`
MemoryLimit int `json:"memory_limit"`
MaxExecutionTime int `json:"max_execution_time"`
UploadMaxFilesize int `json:"upload_max_filesize"`
} `json:"php"`
Database struct {
Type string `json:"type"`
Version string `json:"version"`
Size int `json:"size"`
} `json:"database"`
} `json:"server"`
ActiveUsers ActiveUsers `json:"activeUsers"`
}
type ActiveUsers struct {
Last5Minutes int `json:"last5minutes"`
Last1Hour int `json:"last1hour"`
Last24Hours int `json:"last24hours"`
}
type Storage struct {
NumUsers int `json:"num_users"`
NumFiles int `json:"num_files"`
NumStorages int `json:"num_storages"`
NumStoragesLocal int `json:"num_storages_local"`
NumStoragesHome int `json:"num_storages_home"`
NumStoragesOther int `json:"num_storages_other"`
}

View File

@ -1,53 +0,0 @@
package types
type ShareType int
type SharePermission int
const (
UserShare ShareType = 0
GroupShare ShareType = 1
PublicLinkShare ShareType = 3
FederatedCloudShare ShareType = 6
ReadPermission SharePermission = 1
UpdatePermission SharePermission = 2
CreatePermission SharePermission = 4
DeletePermission SharePermission = 8
ReSharePermission SharePermission = 16
AllPermissions SharePermission = 31
)
type ShareUpdate struct {
ShareID int
Permissions SharePermission
Password string
PublicUpload bool
ExpireDate string
}
type Share struct {
ID string `json:"id"`
ShareType int `json:"share_type"`
UIDOwner string `json:"uid_owner"`
DisplaynameOwner string `json:"displayname_owner"`
Permissions int `json:"permissions"`
Stime int `json:"stime"`
Parent interface{} `json:"parent"`
Expiration string `json:"expiration"`
Token string `json:"token"`
UIDFileOwner string `json:"uid_file_owner"`
DisplaynameFileOwner string `json:"displayname_file_owner"`
Path string `json:"path"`
ItemType string `json:"item_type"`
Mimetype string `json:"mimetype"`
StorageID string `json:"storage_id"`
Storage int `json:"storage"`
ItemSource int `json:"item_source"`
FileSource int `json:"file_source"`
FileParent int `json:"file_parent"`
FileTarget string `json:"file_target"`
ShareWith string `json:"share_with"`
ShareWithDisplayname string `json:"share_with_displayname"`
MailSend int `json:"mail_send"`
Tags []string `json:"tags"`
}

View File

@ -2,12 +2,12 @@ package gonextcloud
import (
"fmt"
"github.com/fatih/structs"
"github.com/stretchr/testify/assert"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
"strings"
"testing"
"time"
"github.com/fatih/structs"
"github.com/stretchr/testify/assert"
)
func TestUserUpdate(t *testing.T) {
@ -23,11 +23,11 @@ func TestUserUpdate(t *testing.T) {
if err != nil {
t.FailNow()
}
user := &types.UserDetails{
user := &UserDetails{
ID: username,
Displayname: strings.ToUpper(username),
Email: "some@mail.com",
Quota: types.Quota{
Quota: Quota{
// Unlimited
Quota: -3,
},

View File

@ -1,8 +1,8 @@
package types
package gonextcloud
import "strconv"
//User encapsulate the data needed to create a new Nextcloud's User
// User encapsulate the data needed to create a new Nextcloud's User
type User struct {
Username string
Email string
@ -12,7 +12,7 @@ type User struct {
Groups []string
}
//UserDetails is the raw Nextcloud User response
// UserDetails is the raw Nextcloud User response
type UserDetails struct {
Enabled bool `json:"enabled"`
ID string `json:"id"`
@ -33,6 +33,7 @@ type UserDetails struct {
Locale string `json:"locale,omitempty"`
}
// Quota is a use storage Quota
type Quota struct {
Free int64 `json:"free"`
Used int64 `json:"used"`

View File

@ -2,56 +2,56 @@ package gonextcloud
import (
"encoding/json"
req "github.com/levigross/grequests"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
"net/http"
"net/url"
"path"
"strings"
"sync"
req "github.com/levigross/grequests"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
//Users contains all Users available actions
type Users struct {
c *Client
//users contains all users available actions
type users struct {
c *client
}
// List return the Nextcloud'user list
func (u *Users) List() ([]string, error) {
func (u *users) List() ([]string, error) {
res, err := u.c.baseRequest(http.MethodGet, routes.users, nil)
//res, err := c.session.Get(u.String(), nil)
if err != nil {
return nil, err
}
var r types.UserListResponse
var r userListResponse
res.JSON(&r)
return r.Ocs.Data.Users, nil
}
//ListDetails return a map of user with details
func (u *Users) ListDetails() (map[string]types.UserDetails, error) {
func (u *users) ListDetails() (map[string]UserDetails, error) {
res, err := u.c.baseRequest(http.MethodGet, routes.users, nil, "details")
//res, err := c.session.Get(u.String(), nil)
if err != nil {
return nil, err
}
var r types.UserListDetailsResponse
var r userListDetailsResponse
res.JSON(&r)
return r.Ocs.Data.Users, nil
}
// Get return the details about the specified user
func (u *Users) Get(name string) (*types.UserDetails, error) {
func (u *users) Get(name string) (*UserDetails, error) {
if name == "" {
return nil, &types.APIError{Message: "name cannot be empty"}
return nil, &APIError{Message: "name cannot be empty"}
}
res, err := u.c.baseRequest(http.MethodGet, routes.users, nil, name)
if err != nil {
return nil, err
}
var r types.UserResponse
var r userResponse
js := res.String()
// Nextcloud does not encode JSON properly
js = reformatJSON(js)
@ -62,7 +62,7 @@ func (u *Users) Get(name string) (*types.UserDetails, error) {
}
// Search returns the users whose name match the search string
func (u *Users) Search(search string) ([]string, error) {
func (u *users) Search(search string) ([]string, error) {
ro := &req.RequestOptions{
Params: map[string]string{"search": search},
}
@ -70,14 +70,14 @@ func (u *Users) Search(search string) ([]string, error) {
if err != nil {
return nil, err
}
var r types.UserListResponse
var r userListResponse
res.JSON(&r)
return r.Ocs.Data.Users, nil
}
// Create create a new user
func (u *Users) Create(username string, password string, user *types.UserDetails) error {
// Create base Users
func (u *users) Create(username string, password string, user *UserDetails) error {
// Create base users
ro := &req.RequestOptions{
Data: map[string]string{
"userid": username,
@ -97,7 +97,7 @@ func (u *Users) Create(username string, password string, user *types.UserDetails
// CreateWithoutPassword create a user without provisioning a password, the email address must be provided to send
// an init password email
func (u *Users) CreateWithoutPassword(username, email, displayName, quota, language string, groups ...string) error {
func (u *users) CreateWithoutPassword(username, email, displayName, quota, language string, groups ...string) error {
if u.c.version.Major < 14 {
return errors.New("unsupported method: requires Nextcloud 14+")
}
@ -132,12 +132,12 @@ func (u *Users) CreateWithoutPassword(username, email, displayName, quota, langu
}
//CreateBatchWithoutPassword create multiple users and send them the init password email
func (u *Users) CreateBatchWithoutPassword(users []types.User) error {
func (u *users) CreateBatchWithoutPassword(users []User) error {
var wg sync.WaitGroup
errs := make(chan error)
for _, us := range users {
wg.Add(1)
go func(user types.User) {
go func(user User) {
logrus.Debugf("creating user %s", user.Username)
defer wg.Done()
if err := u.CreateWithoutPassword(
@ -162,12 +162,12 @@ func (u *Users) CreateBatchWithoutPassword(users []types.User) error {
}
//Delete delete the user
func (u *Users) Delete(name string) error {
func (u *users) Delete(name string) error {
return u.baseRequest(http.MethodDelete, nil, name)
}
//Enable enables the user
func (u *Users) Enable(name string) error {
func (u *users) Enable(name string) error {
ro := &req.RequestOptions{
Data: map[string]string{},
}
@ -175,7 +175,7 @@ func (u *Users) Enable(name string) error {
}
//Disable disables the user
func (u *Users) Disable(name string) error {
func (u *users) Disable(name string) error {
ro := &req.RequestOptions{
Data: map[string]string{},
}
@ -183,25 +183,25 @@ func (u *Users) Disable(name string) error {
}
//SendWelcomeEmail (re)send the welcome mail to the user (return an error if the user has not configured his email)
func (u *Users) SendWelcomeEmail(name string) error {
func (u *users) SendWelcomeEmail(name string) error {
return u.baseRequest(http.MethodPost, nil, name, "welcome")
}
//Update takes a *types.Users struct to update the user's information
// Updatable fields: Email, Displayname, Phone, Address, Website, Twitter, Quota, Groups
func (u *Users) Update(user *types.UserDetails) error {
//Update takes a *types.users struct to update the user's information
// Updatable fields: Email, Displayname, Phone, Address, Website, Twitter, Quota, groups
func (u *users) Update(user *UserDetails) error {
// Get user to update only modified fields
original, err := u.Get(user.ID)
if err != nil {
return err
}
errs := make(chan *types.UpdateError)
errs := make(chan *UpdateError)
var wg sync.WaitGroup
update := func(key string, value string) {
defer wg.Done()
if err := u.updateAttribute(user.ID, strings.ToLower(key), value); err != nil {
errs <- &types.UpdateError{
errs <- &UpdateError{
Field: key,
Error: err,
}
@ -242,7 +242,7 @@ func (u *Users) Update(user *types.UserDetails) error {
if user.Quota.Quota != original.Quota.Quota {
var value string
// If empty
if user.Quota == (types.Quota{}) {
if user.Quota == (Quota{}) {
value = "default"
} else {
value = user.Quota.String()
@ -250,7 +250,7 @@ func (u *Users) Update(user *types.UserDetails) error {
wg.Add(1)
go update("Quota", value)
}
// Groups
// groups
// Group removed
for _, g := range original.Groups {
if !contains(user.Groups, g) {
@ -258,8 +258,8 @@ func (u *Users) Update(user *types.UserDetails) error {
go func(gr string) {
defer wg.Done()
if err := u.GroupRemove(user.ID, gr); err != nil {
errs <- &types.UpdateError{
Field: "Groups/" + gr,
errs <- &UpdateError{
Field: "groups/" + gr,
Error: err,
}
}
@ -275,8 +275,8 @@ func (u *Users) Update(user *types.UserDetails) error {
go func(gr string) {
defer wg.Done()
if err := u.GroupAdd(user.ID, gr); err != nil {
errs <- &types.UpdateError{
Field: "Groups/" + gr,
errs <- &UpdateError{
Field: "groups/" + gr,
Error: err,
}
}
@ -290,66 +290,66 @@ func (u *Users) Update(user *types.UserDetails) error {
close(errs)
}()
// Warning : we actually need to check the *err
if err := types.NewUpdateError(errs); err != nil {
if err := newUpdateError(errs); err != nil {
return err
}
return nil
}
//UpdateEmail update the user's email
func (u *Users) UpdateEmail(name string, email string) error {
func (u *users) UpdateEmail(name string, email string) error {
return u.updateAttribute(name, "email", email)
}
//UpdateDisplayName update the user's display name
func (u *Users) UpdateDisplayName(name string, displayName string) error {
func (u *users) UpdateDisplayName(name string, displayName string) error {
return u.updateAttribute(name, "displayname", displayName)
}
//UpdatePhone update the user's phone
func (u *Users) UpdatePhone(name string, phone string) error {
func (u *users) UpdatePhone(name string, phone string) error {
return u.updateAttribute(name, "phone", phone)
}
//UpdateAddress update the user's address
func (u *Users) UpdateAddress(name string, address string) error {
func (u *users) UpdateAddress(name string, address string) error {
return u.updateAttribute(name, "address", address)
}
//UpdateWebSite update the user's website
func (u *Users) UpdateWebSite(name string, website string) error {
func (u *users) UpdateWebSite(name string, website string) error {
return u.updateAttribute(name, "website", website)
}
//UpdateTwitter update the user's twitter
func (u *Users) UpdateTwitter(name string, twitter string) error {
func (u *users) UpdateTwitter(name string, twitter string) error {
return u.updateAttribute(name, "twitter", twitter)
}
//UpdatePassword update the user's password
func (u *Users) UpdatePassword(name string, password string) error {
func (u *users) UpdatePassword(name string, password string) error {
return u.updateAttribute(name, "password", password)
}
//UpdateQuota update the user's quota (bytes). Set negative quota for unlimited
func (u *Users) UpdateQuota(name string, quota int64) error {
q := types.Quota{Quota: quota}
func (u *users) UpdateQuota(name string, quota int64) error {
q := Quota{Quota: quota}
return u.updateAttribute(name, "quota", q.String())
}
//GroupList lists the user's groups
func (u *Users) GroupList(name string) ([]string, error) {
func (u *users) GroupList(name string) ([]string, error) {
res, err := u.c.baseRequest(http.MethodGet, routes.users, nil, name, "groups")
if err != nil {
return nil, err
}
var r types.GroupListResponse
var r groupListResponse
res.JSON(&r)
return r.Ocs.Data.Groups, nil
}
//GroupAdd adds a the user to the group
func (u *Users) GroupAdd(name string, group string) error {
func (u *users) GroupAdd(name string, group string) error {
ro := &req.RequestOptions{
Data: map[string]string{
"groupid": group,
@ -359,7 +359,7 @@ func (u *Users) GroupAdd(name string, group string) error {
}
//GroupRemove removes the user from the group
func (u *Users) GroupRemove(name string, group string) error {
func (u *users) GroupRemove(name string, group string) error {
ro := &req.RequestOptions{
Data: map[string]string{
"groupid": group,
@ -369,7 +369,7 @@ func (u *Users) GroupRemove(name string, group string) error {
}
//GroupPromote promotes the user as group admin
func (u *Users) GroupPromote(name string, group string) error {
func (u *users) GroupPromote(name string, group string) error {
ro := &req.RequestOptions{
Data: map[string]string{
"groupid": group,
@ -379,7 +379,7 @@ func (u *Users) GroupPromote(name string, group string) error {
}
//GroupDemote demotes the user
func (u *Users) GroupDemote(name string, group string) error {
func (u *users) GroupDemote(name string, group string) error {
ro := &req.RequestOptions{
Data: map[string]string{
"groupid": group,
@ -389,7 +389,7 @@ func (u *Users) GroupDemote(name string, group string) error {
}
//GroupSubAdminList lists the groups where he is subadmin
func (u *Users) GroupSubAdminList(name string) ([]string, error) {
func (u *users) GroupSubAdminList(name string) ([]string, error) {
if !u.c.loggedIn() {
return nil, errUnauthorized
}
@ -399,12 +399,12 @@ func (u *Users) GroupSubAdminList(name string) ([]string, error) {
if err != nil {
return nil, err
}
var r types.BaseResponse
var r baseResponse
res.JSON(&r)
return r.Ocs.Data, nil
}
func (u *Users) updateAttribute(name string, key string, value string) error {
func (u *users) updateAttribute(name string, key string, value string) error {
ro := &req.RequestOptions{
Data: map[string]string{
"key": key,
@ -414,13 +414,13 @@ func (u *Users) updateAttribute(name string, key string, value string) error {
return u.baseRequest(http.MethodPut, ro, name)
}
func (u *Users) baseRequest(method string, ro *req.RequestOptions, subRoutes ...string) error {
func (u *users) baseRequest(method string, ro *req.RequestOptions, subRoutes ...string) error {
_, err := u.c.baseRequest(method, routes.users, ro, subRoutes...)
return err
}
func ignoredUserField(key string) bool {
keys := []string{"Email", "Displayname", "Phone", "Address", "Website", "Twitter", "Quota", "Groups"}
keys := []string{"Email", "Displayname", "Phone", "Address", "Website", "Twitter", "Quota", "groups"}
for _, k := range keys {
if key == k {
return false

View File

@ -2,15 +2,15 @@ package gonextcloud
import (
"encoding/json"
req "github.com/levigross/grequests"
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
"net/http"
"net/url"
"path"
"strings"
req "github.com/levigross/grequests"
)
func (c *Client) baseRequest(method string, route *url.URL, ro *req.RequestOptions, subRoutes ...string) (*req.Response, error) {
func (c *client) baseRequest(method string, route *url.URL, ro *req.RequestOptions, subRoutes ...string) (*req.Response, error) {
if !c.loggedIn() {
return nil, errUnauthorized
}
@ -40,12 +40,12 @@ func (c *Client) baseRequest(method string, route *url.URL, ro *req.RequestOptio
}
// As we cannot read the ReaderCloser twice, we use the string content
js := res.String()
var r types.BaseResponse
var r baseResponse
json.Unmarshal([]byte(js), &r)
if r.Ocs.Meta.Statuscode == 200 || r.Ocs.Meta.Statuscode == 100 {
return res, nil
}
err = types.ErrorFromMeta(r.Ocs.Meta)
err = errorFromMeta(r.Ocs.Meta)
return nil, err
}

View File

@ -2,7 +2,7 @@ ISC License
Copyright (c) 2012-2016 Dave Collins <dave@davec.name>
Permission to use, copy, modify, and distribute this software for any
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

View File

@ -16,7 +16,9 @@
// when the code is not running on Google App Engine, compiled by GopherJS, and
// "-tags safe" is not added to the go build command line. The "disableunsafe"
// tag is deprecated and thus should not be used.
// +build !js,!appengine,!safe,!disableunsafe
// Go versions prior to 1.4 are disabled because they use a different layout
// for interfaces which make the implementation of unsafeReflectValue more complex.
// +build !js,!appengine,!safe,!disableunsafe,go1.4
package spew
@ -34,80 +36,49 @@ const (
ptrSize = unsafe.Sizeof((*byte)(nil))
)
var (
// offsetPtr, offsetScalar, and offsetFlag are the offsets for the
// internal reflect.Value fields. These values are valid before golang
// commit ecccf07e7f9d which changed the format. The are also valid
// after commit 82f48826c6c7 which changed the format again to mirror
// the original format. Code in the init function updates these offsets
// as necessary.
offsetPtr = uintptr(ptrSize)
offsetScalar = uintptr(0)
offsetFlag = uintptr(ptrSize * 2)
type flag uintptr
// flagKindWidth and flagKindShift indicate various bits that the
// reflect package uses internally to track kind information.
//
// flagRO indicates whether or not the value field of a reflect.Value is
// read-only.
//
// flagIndir indicates whether the value field of a reflect.Value is
// the actual data or a pointer to the data.
//
// These values are valid before golang commit 90a7c3c86944 which
// changed their positions. Code in the init function updates these
// flags as necessary.
flagKindWidth = uintptr(5)
flagKindShift = uintptr(flagKindWidth - 1)
flagRO = uintptr(1 << 0)
flagIndir = uintptr(1 << 1)
var (
// flagRO indicates whether the value field of a reflect.Value
// is read-only.
flagRO flag
// flagAddr indicates whether the address of the reflect.Value's
// value may be taken.
flagAddr flag
)
func init() {
// Older versions of reflect.Value stored small integers directly in the
// ptr field (which is named val in the older versions). Versions
// between commits ecccf07e7f9d and 82f48826c6c7 added a new field named
// scalar for this purpose which unfortunately came before the flag
// field, so the offset of the flag field is different for those
// versions.
//
// This code constructs a new reflect.Value from a known small integer
// and checks if the size of the reflect.Value struct indicates it has
// the scalar field. When it does, the offsets are updated accordingly.
vv := reflect.ValueOf(0xf00)
if unsafe.Sizeof(vv) == (ptrSize * 4) {
offsetScalar = ptrSize * 2
offsetFlag = ptrSize * 3
}
// flagKindMask holds the bits that make up the kind
// part of the flags field. In all the supported versions,
// it is in the lower 5 bits.
const flagKindMask = flag(0x1f)
// Commit 90a7c3c86944 changed the flag positions such that the low
// order bits are the kind. This code extracts the kind from the flags
// field and ensures it's the correct type. When it's not, the flag
// order has been changed to the newer format, so the flags are updated
// accordingly.
upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag)
upfv := *(*uintptr)(upf)
flagKindMask := uintptr((1<<flagKindWidth - 1) << flagKindShift)
if (upfv&flagKindMask)>>flagKindShift != uintptr(reflect.Int) {
flagKindShift = 0
flagRO = 1 << 5
flagIndir = 1 << 6
// Different versions of Go have used different
// bit layouts for the flags type. This table
// records the known combinations.
var okFlags = []struct {
ro, addr flag
}{{
// From Go 1.4 to 1.5
ro: 1 << 5,
addr: 1 << 7,
}, {
// Up to Go tip.
ro: 1<<5 | 1<<6,
addr: 1 << 8,
}}
// Commit adf9b30e5594 modified the flags to separate the
// flagRO flag into two bits which specifies whether or not the
// field is embedded. This causes flagIndir to move over a bit
// and means that flagRO is the combination of either of the
// original flagRO bit and the new bit.
//
// This code detects the change by extracting what used to be
// the indirect bit to ensure it's set. When it's not, the flag
// order has been changed to the newer format, so the flags are
// updated accordingly.
if upfv&flagIndir == 0 {
flagRO = 3 << 5
flagIndir = 1 << 7
}
var flagValOffset = func() uintptr {
field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag")
if !ok {
panic("reflect.Value has no flag field")
}
return field.Offset
}()
// flagField returns a pointer to the flag field of a reflect.Value.
func flagField(v *reflect.Value) *flag {
return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset))
}
// unsafeReflectValue converts the passed reflect.Value into a one that bypasses
@ -119,34 +90,56 @@ func init() {
// This allows us to check for implementations of the Stringer and error
// interfaces to be used for pretty printing ordinarily unaddressable and
// inaccessible values such as unexported struct fields.
func unsafeReflectValue(v reflect.Value) (rv reflect.Value) {
indirects := 1
vt := v.Type()
upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr)
rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag))
if rvf&flagIndir != 0 {
vt = reflect.PtrTo(v.Type())
indirects++
} else if offsetScalar != 0 {
// The value is in the scalar field when it's not one of the
// reference types.
switch vt.Kind() {
case reflect.Uintptr:
case reflect.Chan:
case reflect.Func:
case reflect.Map:
case reflect.Ptr:
case reflect.UnsafePointer:
default:
upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) +
offsetScalar)
func unsafeReflectValue(v reflect.Value) reflect.Value {
if !v.IsValid() || (v.CanInterface() && v.CanAddr()) {
return v
}
flagFieldPtr := flagField(&v)
*flagFieldPtr &^= flagRO
*flagFieldPtr |= flagAddr
return v
}
// Sanity checks against future reflect package changes
// to the type or semantics of the Value.flag field.
func init() {
field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag")
if !ok {
panic("reflect.Value has no flag field")
}
if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() {
panic("reflect.Value flag field has changed kind")
}
type t0 int
var t struct {
A t0
// t0 will have flagEmbedRO set.
t0
// a will have flagStickyRO set
a t0
}
vA := reflect.ValueOf(t).FieldByName("A")
va := reflect.ValueOf(t).FieldByName("a")
vt0 := reflect.ValueOf(t).FieldByName("t0")
// Infer flagRO from the difference between the flags
// for the (otherwise identical) fields in t.
flagPublic := *flagField(&vA)
flagWithRO := *flagField(&va) | *flagField(&vt0)
flagRO = flagPublic ^ flagWithRO
// Infer flagAddr from the difference between a value
// taken from a pointer and not.
vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A")
flagNoPtr := *flagField(&vA)
flagPtr := *flagField(&vPtrA)
flagAddr = flagNoPtr ^ flagPtr
// Check that the inferred flags tally with one of the known versions.
for _, f := range okFlags {
if flagRO == f.ro && flagAddr == f.addr {
return
}
}
pv := reflect.NewAt(vt, upv)
rv = pv
for i := 0; i < indirects; i++ {
rv = rv.Elem()
}
return rv
panic("reflect.Value read-only flag has changed semantics")
}

View File

@ -16,7 +16,7 @@
// when the code is running on Google App Engine, compiled by GopherJS, or
// "-tags safe" is added to the go build command line. The "disableunsafe"
// tag is deprecated and thus should not be used.
// +build js appengine safe disableunsafe
// +build js appengine safe disableunsafe !go1.4
package spew

View File

@ -180,7 +180,7 @@ func printComplex(w io.Writer, c complex128, floatPrecision int) {
w.Write(closeParenBytes)
}
// printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x'
// printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x'
// prefix to Writer w.
func printHexPtr(w io.Writer, p uintptr) {
// Null pointer.

View File

@ -35,16 +35,16 @@ var (
// cCharRE is a regular expression that matches a cgo char.
// It is used to detect character arrays to hexdump them.
cCharRE = regexp.MustCompile("^.*\\._Ctype_char$")
cCharRE = regexp.MustCompile(`^.*\._Ctype_char$`)
// cUnsignedCharRE is a regular expression that matches a cgo unsigned
// char. It is used to detect unsigned character arrays to hexdump
// them.
cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$")
cUnsignedCharRE = regexp.MustCompile(`^.*\._Ctype_unsignedchar$`)
// cUint8tCharRE is a regular expression that matches a cgo uint8_t.
// It is used to detect uint8_t arrays to hexdump them.
cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$")
cUint8tCharRE = regexp.MustCompile(`^.*\._Ctype_uint8_t$`)
)
// dumpState contains information about the state of a dump operation.
@ -143,10 +143,10 @@ func (d *dumpState) dumpPtr(v reflect.Value) {
// Display dereferenced value.
d.w.Write(openParenBytes)
switch {
case nilFound == true:
case nilFound:
d.w.Write(nilAngleBytes)
case cycleFound == true:
case cycleFound:
d.w.Write(circularBytes)
default:

View File

@ -182,10 +182,10 @@ func (f *formatState) formatPtr(v reflect.Value) {
// Display dereferenced value.
switch {
case nilFound == true:
case nilFound:
f.fs.Write(nilAngleBytes)
case cycleFound == true:
case cycleFound:
f.fs.Write(circularShortBytes)
default:

23
vendor/github.com/fatih/structs/.gitignore generated vendored Normal file
View File

@ -0,0 +1,23 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test

13
vendor/github.com/fatih/structs/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,13 @@
language: go
go:
- 1.7.x
- 1.8.x
- 1.9.x
- tip
sudo: false
before_install:
- go get github.com/axw/gocov/gocov
- go get github.com/mattn/goveralls
- if ! go get github.com/golang/tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi
script:
- $HOME/gopath/bin/goveralls -service=travis-ci

View File

@ -1,397 +0,0 @@
package structs
import (
"reflect"
"testing"
)
// A test struct that defines all cases
type Foo struct {
A string
B int `structs:"y"`
C bool `json:"c"`
d string // not exported
E *Baz
x string `xml:"x"` // not exported, with tag
Y []string
Z map[string]interface{}
*Bar // embedded
}
type Baz struct {
A string
B int
}
type Bar struct {
E string
F int
g []string
}
func newStruct() *Struct {
b := &Bar{
E: "example",
F: 2,
g: []string{"zeynep", "fatih"},
}
// B and x is not initialized for testing
f := &Foo{
A: "gopher",
C: true,
d: "small",
E: nil,
Y: []string{"example"},
Z: nil,
}
f.Bar = b
return New(f)
}
func TestField_Set(t *testing.T) {
s := newStruct()
f := s.Field("A")
err := f.Set("fatih")
if err != nil {
t.Error(err)
}
if f.Value().(string) != "fatih" {
t.Errorf("Setted value is wrong: %s want: %s", f.Value().(string), "fatih")
}
f = s.Field("Y")
err = f.Set([]string{"override", "with", "this"})
if err != nil {
t.Error(err)
}
sliceLen := len(f.Value().([]string))
if sliceLen != 3 {
t.Errorf("Setted values slice length is wrong: %d, want: %d", sliceLen, 3)
}
f = s.Field("C")
err = f.Set(false)
if err != nil {
t.Error(err)
}
if f.Value().(bool) {
t.Errorf("Setted value is wrong: %t want: %t", f.Value().(bool), false)
}
// let's pass a different type
f = s.Field("A")
err = f.Set(123) // Field A is of type string, but we are going to pass an integer
if err == nil {
t.Error("Setting a field's value with a different type than the field's type should return an error")
}
// old value should be still there :)
if f.Value().(string) != "fatih" {
t.Errorf("Setted value is wrong: %s want: %s", f.Value().(string), "fatih")
}
// let's access an unexported field, which should give an error
f = s.Field("d")
err = f.Set("large")
if err != errNotExported {
t.Error(err)
}
// let's set a pointer to struct
b := &Bar{
E: "gopher",
F: 2,
}
f = s.Field("Bar")
err = f.Set(b)
if err != nil {
t.Error(err)
}
baz := &Baz{
A: "helloWorld",
B: 42,
}
f = s.Field("E")
err = f.Set(baz)
if err != nil {
t.Error(err)
}
ba := s.Field("E").Value().(*Baz)
if ba.A != "helloWorld" {
t.Errorf("could not set baz. Got: %s Want: helloWorld", ba.A)
}
}
func TestField_NotSettable(t *testing.T) {
a := map[int]Baz{
4: {
A: "value",
},
}
s := New(a[4])
if err := s.Field("A").Set("newValue"); err != errNotSettable {
t.Errorf("Trying to set non-settable field should error with %q. Got %q instead.", errNotSettable, err)
}
}
func TestField_Zero(t *testing.T) {
s := newStruct()
f := s.Field("A")
err := f.Zero()
if err != nil {
t.Error(err)
}
if f.Value().(string) != "" {
t.Errorf("Zeroed value is wrong: %s want: %s", f.Value().(string), "")
}
f = s.Field("Y")
err = f.Zero()
if err != nil {
t.Error(err)
}
sliceLen := len(f.Value().([]string))
if sliceLen != 0 {
t.Errorf("Zeroed values slice length is wrong: %d, want: %d", sliceLen, 0)
}
f = s.Field("C")
err = f.Zero()
if err != nil {
t.Error(err)
}
if f.Value().(bool) {
t.Errorf("Zeroed value is wrong: %t want: %t", f.Value().(bool), false)
}
// let's access an unexported field, which should give an error
f = s.Field("d")
err = f.Zero()
if err != errNotExported {
t.Error(err)
}
f = s.Field("Bar")
err = f.Zero()
if err != nil {
t.Error(err)
}
f = s.Field("E")
err = f.Zero()
if err != nil {
t.Error(err)
}
v := s.Field("E").value
if !v.IsNil() {
t.Errorf("could not set baz. Got: %s Want: <nil>", v.Interface())
}
}
func TestField(t *testing.T) {
s := newStruct()
defer func() {
err := recover()
if err == nil {
t.Error("Retrieveing a non existing field from the struct should panic")
}
}()
_ = s.Field("no-field")
}
func TestField_Kind(t *testing.T) {
s := newStruct()
f := s.Field("A")
if f.Kind() != reflect.String {
t.Errorf("Field A has wrong kind: %s want: %s", f.Kind(), reflect.String)
}
f = s.Field("B")
if f.Kind() != reflect.Int {
t.Errorf("Field B has wrong kind: %s want: %s", f.Kind(), reflect.Int)
}
// unexported
f = s.Field("d")
if f.Kind() != reflect.String {
t.Errorf("Field d has wrong kind: %s want: %s", f.Kind(), reflect.String)
}
}
func TestField_Tag(t *testing.T) {
s := newStruct()
v := s.Field("B").Tag("json")
if v != "" {
t.Errorf("Field's tag value of a non existing tag should return empty, got: %s", v)
}
v = s.Field("C").Tag("json")
if v != "c" {
t.Errorf("Field's tag value of the existing field C should return 'c', got: %s", v)
}
v = s.Field("d").Tag("json")
if v != "" {
t.Errorf("Field's tag value of a non exported field should return empty, got: %s", v)
}
v = s.Field("x").Tag("xml")
if v != "x" {
t.Errorf("Field's tag value of a non exported field with a tag should return 'x', got: %s", v)
}
v = s.Field("A").Tag("json")
if v != "" {
t.Errorf("Field's tag value of a existing field without a tag should return empty, got: %s", v)
}
}
func TestField_Value(t *testing.T) {
s := newStruct()
v := s.Field("A").Value()
val, ok := v.(string)
if !ok {
t.Errorf("Field's value of a A should be string")
}
if val != "gopher" {
t.Errorf("Field's value of a existing tag should return 'gopher', got: %s", val)
}
defer func() {
err := recover()
if err == nil {
t.Error("Value of a non exported field from the field should panic")
}
}()
// should panic
_ = s.Field("d").Value()
}
func TestField_IsEmbedded(t *testing.T) {
s := newStruct()
if !s.Field("Bar").IsEmbedded() {
t.Errorf("Fields 'Bar' field is an embedded field")
}
if s.Field("d").IsEmbedded() {
t.Errorf("Fields 'd' field is not an embedded field")
}
}
func TestField_IsExported(t *testing.T) {
s := newStruct()
if !s.Field("Bar").IsExported() {
t.Errorf("Fields 'Bar' field is an exported field")
}
if !s.Field("A").IsExported() {
t.Errorf("Fields 'A' field is an exported field")
}
if s.Field("d").IsExported() {
t.Errorf("Fields 'd' field is not an exported field")
}
}
func TestField_IsZero(t *testing.T) {
s := newStruct()
if s.Field("A").IsZero() {
t.Errorf("Fields 'A' field is an initialized field")
}
if !s.Field("B").IsZero() {
t.Errorf("Fields 'B' field is not an initialized field")
}
}
func TestField_Name(t *testing.T) {
s := newStruct()
if s.Field("A").Name() != "A" {
t.Errorf("Fields 'A' field should have the name 'A'")
}
}
func TestField_Field(t *testing.T) {
s := newStruct()
e := s.Field("Bar").Field("E")
val, ok := e.Value().(string)
if !ok {
t.Error("The value of the field 'e' inside 'Bar' struct should be string")
}
if val != "example" {
t.Errorf("The value of 'e' should be 'example, got: %s", val)
}
defer func() {
err := recover()
if err == nil {
t.Error("Field of a non existing nested struct should panic")
}
}()
_ = s.Field("Bar").Field("e")
}
func TestField_Fields(t *testing.T) {
s := newStruct()
fields := s.Field("Bar").Fields()
if len(fields) != 3 {
t.Errorf("We expect 3 fields in embedded struct, was: %d", len(fields))
}
}
func TestField_FieldOk(t *testing.T) {
s := newStruct()
b, ok := s.FieldOk("Bar")
if !ok {
t.Error("The field 'Bar' should exists.")
}
e, ok := b.FieldOk("E")
if !ok {
t.Error("The field 'E' should exists.")
}
val, ok := e.Value().(string)
if !ok {
t.Error("The value of the field 'e' inside 'Bar' struct should be string")
}
if val != "example" {
t.Errorf("The value of 'e' should be 'example, got: %s", val)
}
}

View File

@ -1,351 +0,0 @@
package structs
import (
"fmt"
"time"
)
func ExampleNew() {
type Server struct {
Name string
ID int32
Enabled bool
}
server := &Server{
Name: "Arslan",
ID: 123456,
Enabled: true,
}
s := New(server)
fmt.Printf("Name : %v\n", s.Name())
fmt.Printf("Values : %v\n", s.Values())
fmt.Printf("Value of ID : %v\n", s.Field("ID").Value())
// Output:
// Name : Server
// Values : [Arslan 123456 true]
// Value of ID : 123456
}
func ExampleMap() {
type Server struct {
Name string
ID int32
Enabled bool
}
s := &Server{
Name: "Arslan",
ID: 123456,
Enabled: true,
}
m := Map(s)
fmt.Printf("%#v\n", m["Name"])
fmt.Printf("%#v\n", m["ID"])
fmt.Printf("%#v\n", m["Enabled"])
// Output:
// "Arslan"
// 123456
// true
}
func ExampleMap_tags() {
// Custom tags can change the map keys instead of using the fields name
type Server struct {
Name string `structs:"server_name"`
ID int32 `structs:"server_id"`
Enabled bool `structs:"enabled"`
}
s := &Server{
Name: "Zeynep",
ID: 789012,
}
m := Map(s)
// access them by the custom tags defined above
fmt.Printf("%#v\n", m["server_name"])
fmt.Printf("%#v\n", m["server_id"])
fmt.Printf("%#v\n", m["enabled"])
// Output:
// "Zeynep"
// 789012
// false
}
func ExampleMap_omitNested() {
// By default field with struct types are processed too. We can stop
// processing them via "omitnested" tag option.
type Server struct {
Name string `structs:"server_name"`
ID int32 `structs:"server_id"`
Time time.Time `structs:"time,omitnested"` // do not convert to map[string]interface{}
}
const shortForm = "2006-Jan-02"
t, _ := time.Parse("2006-Jan-02", "2013-Feb-03")
s := &Server{
Name: "Zeynep",
ID: 789012,
Time: t,
}
m := Map(s)
// access them by the custom tags defined above
fmt.Printf("%v\n", m["server_name"])
fmt.Printf("%v\n", m["server_id"])
fmt.Printf("%v\n", m["time"].(time.Time))
// Output:
// Zeynep
// 789012
// 2013-02-03 00:00:00 +0000 UTC
}
func ExampleMap_omitEmpty() {
// By default field with struct types of zero values are processed too. We
// can stop processing them via "omitempty" tag option.
type Server struct {
Name string `structs:",omitempty"`
ID int32 `structs:"server_id,omitempty"`
Location string
}
// Only add location
s := &Server{
Location: "Tokyo",
}
m := Map(s)
// map contains only the Location field
fmt.Printf("%v\n", m)
// Output:
// map[Location:Tokyo]
}
func ExampleValues() {
type Server struct {
Name string
ID int32
Enabled bool
}
s := &Server{
Name: "Fatih",
ID: 135790,
Enabled: false,
}
m := Values(s)
fmt.Printf("Values: %+v\n", m)
// Output:
// Values: [Fatih 135790 false]
}
func ExampleValues_omitEmpty() {
// By default field with struct types of zero values are processed too. We
// can stop processing them via "omitempty" tag option.
type Server struct {
Name string `structs:",omitempty"`
ID int32 `structs:"server_id,omitempty"`
Location string
}
// Only add location
s := &Server{
Location: "Ankara",
}
m := Values(s)
// values contains only the Location field
fmt.Printf("Values: %+v\n", m)
// Output:
// Values: [Ankara]
}
func ExampleValues_tags() {
type Location struct {
City string
Country string
}
type Server struct {
Name string
ID int32
Enabled bool
Location Location `structs:"-"` // values from location are not included anymore
}
s := &Server{
Name: "Fatih",
ID: 135790,
Enabled: false,
Location: Location{City: "Ankara", Country: "Turkey"},
}
// Let get all values from the struct s. Note that we don't include values
// from the Location field
m := Values(s)
fmt.Printf("Values: %+v\n", m)
// Output:
// Values: [Fatih 135790 false]
}
func ExampleFields() {
type Access struct {
Name string
LastAccessed time.Time
Number int
}
s := &Access{
Name: "Fatih",
LastAccessed: time.Now(),
Number: 1234567,
}
fields := Fields(s)
for i, field := range fields {
fmt.Printf("[%d] %+v\n", i, field.Name())
}
// Output:
// [0] Name
// [1] LastAccessed
// [2] Number
}
func ExampleFields_nested() {
type Person struct {
Name string
Number int
}
type Access struct {
Person Person
HasPermission bool
LastAccessed time.Time
}
s := &Access{
Person: Person{Name: "fatih", Number: 1234567},
LastAccessed: time.Now(),
HasPermission: true,
}
// Let's get all fields from the struct s.
fields := Fields(s)
for _, field := range fields {
if field.Name() == "Person" {
fmt.Printf("Access.Person.Name: %+v\n", field.Field("Name").Value())
}
}
// Output:
// Access.Person.Name: fatih
}
func ExampleField() {
type Person struct {
Name string
Number int
}
type Access struct {
Person Person
HasPermission bool
LastAccessed time.Time
}
access := &Access{
Person: Person{Name: "fatih", Number: 1234567},
LastAccessed: time.Now(),
HasPermission: true,
}
// Create a new Struct type
s := New(access)
// Get the Field type for "Person" field
p := s.Field("Person")
// Get the underlying "Name field" and print the value of it
name := p.Field("Name")
fmt.Printf("Value of Person.Access.Name: %+v\n", name.Value())
// Output:
// Value of Person.Access.Name: fatih
}
func ExampleIsZero() {
type Server struct {
Name string
ID int32
Enabled bool
}
// Nothing is initialized
a := &Server{}
isZeroA := IsZero(a)
// Name and Enabled is initialized, but not ID
b := &Server{
Name: "Golang",
Enabled: true,
}
isZeroB := IsZero(b)
fmt.Printf("%#v\n", isZeroA)
fmt.Printf("%#v\n", isZeroB)
// Output:
// true
// false
}
func ExampleHasZero() {
// Let's define an Access struct. Note that the "Enabled" field is not
// going to be checked because we added the "structs" tag to the field.
type Access struct {
Name string
LastAccessed time.Time
Number int
Enabled bool `structs:"-"`
}
// Name and Number is not initialized.
a := &Access{
LastAccessed: time.Now(),
}
hasZeroA := HasZero(a)
// Name and Number is initialized.
b := &Access{
Name: "Fatih",
LastAccessed: time.Now(),
Number: 12345,
}
hasZeroB := HasZero(b)
fmt.Printf("%#v\n", hasZeroA)
fmt.Printf("%#v\n", hasZeroB)
// Output:
// true
// false
}

File diff suppressed because it is too large Load Diff

View File

@ -1,46 +0,0 @@
package structs
import "testing"
func TestParseTag_Name(t *testing.T) {
tags := []struct {
tag string
has bool
}{
{"", false},
{"name", true},
{"name,opt", true},
{"name , opt, opt2", false}, // has a single whitespace
{", opt, opt2", false},
}
for _, tag := range tags {
name, _ := parseTag(tag.tag)
if (name != "name") && tag.has {
t.Errorf("Parse tag should return name: %#v", tag)
}
}
}
func TestParseTag_Opts(t *testing.T) {
tags := []struct {
opts string
has bool
}{
{"name", false},
{"name,opt", true},
{"name , opt, opt2", false}, // has a single whitespace
{",opt, opt2", true},
{", opt3, opt4", false},
}
// search for "opt"
for _, tag := range tags {
_, opts := parseTag(tag.opts)
if opts.Has("opt") != tag.has {
t.Errorf("Tag opts should have opt: %#v", tag)
}
}
}

View File

@ -1,328 +0,0 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package query
import (
"fmt"
"net/url"
"reflect"
"testing"
"time"
)
type Nested struct {
A SubNested `url:"a"`
B *SubNested `url:"b"`
Ptr *SubNested `url:"ptr,omitempty"`
}
type SubNested struct {
Value string `url:"value"`
}
func TestValues_types(t *testing.T) {
str := "string"
strPtr := &str
timeVal := time.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC)
tests := []struct {
in interface{}
want url.Values
}{
{
// basic primitives
struct {
A string
B int
C uint
D float32
E bool
}{},
url.Values{
"A": {""},
"B": {"0"},
"C": {"0"},
"D": {"0"},
"E": {"false"},
},
},
{
// pointers
struct {
A *string
B *int
C **string
D *time.Time
}{
A: strPtr,
C: &strPtr,
D: &timeVal,
},
url.Values{
"A": {str},
"B": {""},
"C": {str},
"D": {"2000-01-01T12:34:56Z"},
},
},
{
// slices and arrays
struct {
A []string
B []string `url:",comma"`
C []string `url:",space"`
D [2]string
E [2]string `url:",comma"`
F [2]string `url:",space"`
G []*string `url:",space"`
H []bool `url:",int,space"`
I []string `url:",brackets"`
J []string `url:",semicolon"`
K []string `url:",numbered"`
}{
A: []string{"a", "b"},
B: []string{"a", "b"},
C: []string{"a", "b"},
D: [2]string{"a", "b"},
E: [2]string{"a", "b"},
F: [2]string{"a", "b"},
G: []*string{&str, &str},
H: []bool{true, false},
I: []string{"a", "b"},
J: []string{"a", "b"},
K: []string{"a", "b"},
},
url.Values{
"A": {"a", "b"},
"B": {"a,b"},
"C": {"a b"},
"D": {"a", "b"},
"E": {"a,b"},
"F": {"a b"},
"G": {"string string"},
"H": {"1 0"},
"I[]": {"a", "b"},
"J": {"a;b"},
"K0": {"a"},
"K1": {"b"},
},
},
{
// other types
struct {
A time.Time
B time.Time `url:",unix"`
C bool `url:",int"`
D bool `url:",int"`
}{
A: time.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC),
B: time.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC),
C: true,
D: false,
},
url.Values{
"A": {"2000-01-01T12:34:56Z"},
"B": {"946730096"},
"C": {"1"},
"D": {"0"},
},
},
{
struct {
Nest Nested `url:"nest"`
}{
Nested{
A: SubNested{
Value: "that",
},
},
},
url.Values{
"nest[a][value]": {"that"},
"nest[b]": {""},
},
},
{
struct {
Nest Nested `url:"nest"`
}{
Nested{
Ptr: &SubNested{
Value: "that",
},
},
},
url.Values{
"nest[a][value]": {""},
"nest[b]": {""},
"nest[ptr][value]": {"that"},
},
},
{
nil,
url.Values{},
},
}
for i, tt := range tests {
v, err := Values(tt.in)
if err != nil {
t.Errorf("%d. Values(%q) returned error: %v", i, tt.in, err)
}
if !reflect.DeepEqual(tt.want, v) {
t.Errorf("%d. Values(%q) returned %v, want %v", i, tt.in, v, tt.want)
}
}
}
func TestValues_omitEmpty(t *testing.T) {
str := ""
s := struct {
a string
A string
B string `url:",omitempty"`
C string `url:"-"`
D string `url:"omitempty"` // actually named omitempty, not an option
E *string `url:",omitempty"`
}{E: &str}
v, err := Values(s)
if err != nil {
t.Errorf("Values(%q) returned error: %v", s, err)
}
want := url.Values{
"A": {""},
"omitempty": {""},
"E": {""}, // E is included because the pointer is not empty, even though the string being pointed to is
}
if !reflect.DeepEqual(want, v) {
t.Errorf("Values(%q) returned %v, want %v", s, v, want)
}
}
type A struct {
B
}
type B struct {
C string
}
type D struct {
B
C string
}
type e struct {
B
C string
}
type F struct {
e
}
func TestValues_embeddedStructs(t *testing.T) {
tests := []struct {
in interface{}
want url.Values
}{
{
A{B{C: "foo"}},
url.Values{"C": {"foo"}},
},
{
D{B: B{C: "bar"}, C: "foo"},
url.Values{"C": {"foo", "bar"}},
},
{
F{e{B: B{C: "bar"}, C: "foo"}}, // With unexported embed
url.Values{"C": {"foo", "bar"}},
},
}
for i, tt := range tests {
v, err := Values(tt.in)
if err != nil {
t.Errorf("%d. Values(%q) returned error: %v", i, tt.in, err)
}
if !reflect.DeepEqual(tt.want, v) {
t.Errorf("%d. Values(%q) returned %v, want %v", i, tt.in, v, tt.want)
}
}
}
func TestValues_invalidInput(t *testing.T) {
_, err := Values("")
if err == nil {
t.Errorf("expected Values() to return an error on invalid input")
}
}
type EncodedArgs []string
func (m EncodedArgs) EncodeValues(key string, v *url.Values) error {
for i, arg := range m {
v.Set(fmt.Sprintf("%s.%d", key, i), arg)
}
return nil
}
func TestValues_Marshaler(t *testing.T) {
s := struct {
Args EncodedArgs `url:"arg"`
}{[]string{"a", "b", "c"}}
v, err := Values(s)
if err != nil {
t.Errorf("Values(%q) returned error: %v", s, err)
}
want := url.Values{
"arg.0": {"a"},
"arg.1": {"b"},
"arg.2": {"c"},
}
if !reflect.DeepEqual(want, v) {
t.Errorf("Values(%q) returned %v, want %v", s, v, want)
}
}
func TestValues_MarshalerWithNilPointer(t *testing.T) {
s := struct {
Args *EncodedArgs `url:"arg"`
}{}
v, err := Values(s)
if err != nil {
t.Errorf("Values(%q) returned error: %v", s, err)
}
want := url.Values{}
if !reflect.DeepEqual(want, v) {
t.Errorf("Values(%q) returned %v, want %v", s, v, want)
}
}
func TestTagParsing(t *testing.T) {
name, opts := parseTag("field,foobar,foo")
if name != "field" {
t.Fatalf("name = %q, want field", name)
}
for _, tt := range []struct {
opt string
want bool
}{
{"foobar", true},
{"foo", true},
{"bar", false},
{"field", false},
} {
if opts.Contains(tt.opt) != tt.want {
t.Errorf("Contains(%q) = %v", tt.opt, !tt.want)
}
}
}

View File

@ -0,0 +1,9 @@
(The MIT License)
Copyright (c) 2017 marvin + konsorten GmbH (open-source@konsorten.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,40 @@
# Windows Terminal Sequences
This library allow for enabling Windows terminal color support for Go.
See [Console Virtual Terminal Sequences](https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences) for details.
## Usage
```go
import (
"syscall"
sequences "github.com/konsorten/go-windows-terminal-sequences"
)
func main() {
sequences.EnableVirtualTerminalProcessing(syscall.Stdout, true)
}
```
## Authors
The tool is sponsored by the [marvin + konsorten GmbH](http://www.konsorten.de).
We thank all the authors who provided code to this library:
* Felix Kollmann
## License
(The MIT License)
Copyright (c) 2018 marvin + konsorten GmbH (open-source@konsorten.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1 @@
module github.com/konsorten/go-windows-terminal-sequences

View File

@ -0,0 +1,36 @@
// +build windows
package sequences
import (
"syscall"
"unsafe"
)
var (
kernel32Dll *syscall.LazyDLL = syscall.NewLazyDLL("Kernel32.dll")
setConsoleMode *syscall.LazyProc = kernel32Dll.NewProc("SetConsoleMode")
)
func EnableVirtualTerminalProcessing(stream syscall.Handle, enable bool) error {
const ENABLE_VIRTUAL_TERMINAL_PROCESSING uint32 = 0x4
var mode uint32
err := syscall.GetConsoleMode(syscall.Stdout, &mode)
if err != nil {
return err
}
if enable {
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING
} else {
mode &^= ENABLE_VIRTUAL_TERMINAL_PROCESSING
}
ret, _, err := setConsoleMode.Call(uintptr(unsafe.Pointer(stream)), uintptr(mode))
if ret == 0 {
return err
}
return nil
}

27
vendor/github.com/levigross/grequests/.gitignore generated vendored Normal file
View File

@ -0,0 +1,27 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
.idea/
*.iml

23
vendor/github.com/levigross/grequests/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,23 @@
language: go
matrix:
fast_finish: true
include:
- go: 1.7
- go: 1.8
- go: master
allow_failures:
- go: master
before_install:
- go get -u -v github.com/axw/gocov/gocov
- go get -u -v github.com/mattn/goveralls
- go get -u -v github.com/golang/lint/golint
script:
- diff -u <(echo -n) <(gofmt -s -d ./)
- diff -u <(echo -n) <(go vet ./...)
- diff -u <(echo -n) <(golint ./...)
- go test -v -race -covermode=atomic -coverprofile=coverage.out
after_success:
- goveralls -coverprofile=coverage.out -service=travis-ci -repotoken $COVERALLS_TOKEN

View File

@ -1,99 +0,0 @@
package grequests
import (
"net/url"
"testing"
)
func TestBasicDeleteRequest(t *testing.T) {
resp, err := Delete("http://httpbin.org/delete", nil)
if err != nil {
t.Error("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
}
func TestDeleteSession(t *testing.T) {
session := NewSession(nil)
resp, err := session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"one": "two"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"two": "three"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"three": "four"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Delete("http://httpbin.org/delete", nil)
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
cookieURL, err := url.Parse("http://httpbin.org")
if err != nil {
t.Error("We (for some reason) cannot parse the cookie URL")
}
if len(session.HTTPClient.Jar.Cookies(cookieURL)) != 3 {
t.Error("Invalid number of cookies provided: ", resp.RawResponse.Cookies())
}
for _, cookie := range session.HTTPClient.Jar.Cookies(cookieURL) {
switch cookie.Name {
case "one":
if cookie.Value != "two" {
t.Error("Cookie value is not valid", cookie)
}
case "two":
if cookie.Value != "three" {
t.Error("Cookie value is not valid", cookie)
}
case "three":
if cookie.Value != "four" {
t.Error("Cookie value is not valid", cookie)
}
default:
t.Error("We should not have any other cookies: ", cookie)
}
}
}
func TestDeleteInvalidURLSession(t *testing.T) {
session := NewSession(nil)
if _, err := session.Delete("%../dir/", nil); err == nil {
t.Error("Some how the request was valid to make request ", err)
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,115 +0,0 @@
package grequests
import (
"net/url"
"testing"
)
func TestBasicHeadRequest(t *testing.T) {
resp, err := Head("http://httpbin.org/get", nil)
if err != nil {
t.Error("Unable to make HEAD request: ", resp.Error)
}
if resp.Ok != true {
t.Error("HEAD request did not return success: ", resp.StatusCode)
}
if resp.Header.Get("Content-Type") != "application/json" {
t.Error("Content Type Header is unexpected: ", resp.Header.Get("Content-Type"))
}
}
func TestBasicHeadRequestNoContent(t *testing.T) {
resp, err := Head("http://httpbin.org/bytes/0", nil)
if err != nil {
t.Error("Unable to make HEAD request: ", resp.Error)
}
if resp.Ok != true {
t.Error("HEAD request did not return success: ", resp.StatusCode)
}
if resp.Header.Get("Content-Type") != "application/octet-stream" {
t.Error("Content Type Header is unexpected: ", resp.Header.Get("Content-Type"))
}
if resp.Bytes() != nil {
t.Error("Somehow byte buffer is working now (bytes)", resp.Bytes())
}
if resp.String() != "" {
t.Error("Somehow byte buffer is working now (bytes)", resp.String())
}
}
func TestHeadSession(t *testing.T) {
session := NewSession(nil)
resp, err := session.Head("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"one": "two"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Head("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"two": "three"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Head("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"three": "four"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
cookieURL, err := url.Parse("http://httpbin.org")
if err != nil {
t.Error("We (for some reason) cannot parse the cookie URL")
}
if len(session.HTTPClient.Jar.Cookies(cookieURL)) != 3 {
t.Error("Invalid number of cookies provided: ", session.HTTPClient.Jar.Cookies(cookieURL))
}
for _, cookie := range session.HTTPClient.Jar.Cookies(cookieURL) {
switch cookie.Name {
case "one":
if cookie.Value != "two" {
t.Error("Cookie value is not valid", cookie)
}
case "two":
if cookie.Value != "three" {
t.Error("Cookie value is not valid", cookie)
}
case "three":
if cookie.Value != "four" {
t.Error("Cookie value is not valid", cookie)
}
default:
t.Error("We should not have any other cookies: ", cookie)
}
}
}
func TestHeadInvalidURLSession(t *testing.T) {
session := NewSession(nil)
if _, err := session.Head("%../dir/", nil); err == nil {
t.Error("Some how the request was valid to make request ", err)
}
}

View File

@ -1,88 +0,0 @@
package grequests
import (
"net/url"
"testing"
)
func TestBasicOPTIONSRequest(t *testing.T) {
resp, err := Options("http://httpbin.org/get", nil)
if err != nil {
t.Error("Unable to make OPTIONS request: ", resp.Error)
}
if resp.Ok != true {
t.Error("Options request did not return success: ", resp.StatusCode)
}
if resp.Header.Get("Access-Control-Allow-Methods") != "GET, POST, PUT, DELETE, PATCH, OPTIONS" {
t.Error("Access-Control-Allow-Methods Type Header is unexpected: ", resp.Header)
}
}
func TestOptionsSession(t *testing.T) {
session := NewSession(nil)
resp, err := session.Options("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"one": "two"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Options("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"two": "three"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Options("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"three": "four"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
cookieURL, err := url.Parse("http://httpbin.org")
if err != nil {
t.Error("We (for some reason) cannot parse the cookie URL")
}
for _, cookie := range session.HTTPClient.Jar.Cookies(cookieURL) {
switch cookie.Name {
case "one":
if cookie.Value != "two" {
t.Error("Cookie value is not valid", cookie)
}
case "two":
if cookie.Value != "three" {
t.Error("Cookie value is not valid", cookie)
}
case "three":
if cookie.Value != "four" {
t.Error("Cookie value is not valid", cookie)
}
default:
t.Error("We should not have any other cookies: ", cookie)
}
}
}
func TestOptionsInvalidURLSession(t *testing.T) {
session := NewSession(nil)
if _, err := session.Options("%../dir/", nil); err == nil {
t.Error("Some how the request was valid to make request ", err)
}
}

View File

@ -1,99 +0,0 @@
package grequests
import (
"net/url"
"testing"
)
func TestBasicPatchRequest(t *testing.T) {
resp, err := Patch("http://httpbin.org/patch", nil)
if err != nil {
t.Error("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
}
func TestPatchSession(t *testing.T) {
session := NewSession(nil)
resp, err := session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"one": "two"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"two": "three"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"three": "four"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Patch("http://httpbin.org/patch", &RequestOptions{Params: map[string]string{"one": "two"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK: ", resp.String())
}
cookieURL, err := url.Parse("http://httpbin.org")
if err != nil {
t.Error("We (for some reason) cannot parse the cookie URL")
}
if len(session.HTTPClient.Jar.Cookies(cookieURL)) != 3 {
t.Error("Invalid number of cookies provided: ", session.HTTPClient.Jar.Cookies(cookieURL))
}
for _, cookie := range session.HTTPClient.Jar.Cookies(cookieURL) {
switch cookie.Name {
case "one":
if cookie.Value != "two" {
t.Error("Cookie value is not valid", cookie)
}
case "two":
if cookie.Value != "three" {
t.Error("Cookie value is not valid", cookie)
}
case "three":
if cookie.Value != "four" {
t.Error("Cookie value is not valid", cookie)
}
default:
t.Error("We should not have any other cookies: ", cookie)
}
}
}
func TestPatchInvalidURLSession(t *testing.T) {
session := NewSession(nil)
if _, err := session.Patch("%../dir/", nil); err == nil {
t.Error("Some how the request was valid to make request ", err)
}
}

View File

@ -1,948 +0,0 @@
package grequests
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"math"
"net/url"
"os"
"strings"
"testing"
)
type BasicPostResponse struct {
Args struct{} `json:"args"`
Data string `json:"data"`
Files struct{} `json:"files"`
Form struct {
One string `json:"one"`
} `json:"form"`
Headers struct {
Accept string `json:"Accept"`
ContentLength string `json:"Content-Length"`
ContentType string `json:"Content-Type"`
Host string `json:"Host"`
UserAgent string `json:"User-Agent"`
} `json:"headers"`
JSON interface{} `json:"json"`
Origin string `json:"origin"`
URL string `json:"url"`
}
type BasicPostJSONResponse struct {
Args struct{} `json:"args"`
Data string `json:"data"`
Files struct{} `json:"files"`
Form struct{} `json:"form"`
Headers struct {
AcceptEncoding string `json:"Accept-Encoding"`
ContentLength string `json:"Content-Length"`
ContentType string `json:"Content-Type"`
Host string `json:"Host"`
UserAgent string `json:"User-Agent"`
XRequestedWith string `json:"X-Requested-With"`
} `json:"headers"`
JSON struct {
One string `json:"One"`
} `json:"json"`
Origin string `json:"origin"`
URL string `json:"url"`
}
type BasicMultiFileUploadResponse struct {
Args struct{} `json:"args"`
Data string `json:"data"`
Files struct {
File1 string `json:"file1"`
File2 string `json:"file2"`
} `json:"files"`
Form struct {
One string `json:"One"`
} `json:"form"`
Headers struct {
AcceptEncoding string `json:"Accept-Encoding"`
ContentLength string `json:"Content-Length"`
ContentType string `json:"Content-Type"`
Host string `json:"Host"`
UserAgent string `json:"User-Agent"`
} `json:"headers"`
JSON interface{} `json:"json"`
Origin string `json:"origin"`
URL string `json:"url"`
}
type BasicPostFileUpload struct {
Args struct{} `json:"args"`
Data string `json:"data"`
Files struct {
File string `json:"file"`
} `json:"files"`
Form struct {
One string `json:"one"`
} `json:"form"`
Headers struct {
AcceptEncoding string `json:"Accept-Encoding"`
ContentLength string `json:"Content-Length"`
ContentType string `json:"Content-Type"`
Host string `json:"Host"`
UserAgent string `json:"User-Agent"`
} `json:"headers"`
JSON interface{} `json:"json"`
Origin string `json:"origin"`
URL string `json:"url"`
}
type XMLPostMessage struct {
Name string
Age int
Height int
}
type dataAndErrorBuffer struct {
err error
bytes.Buffer
}
func (dataAndErrorBuffer) Close() error { return nil }
func (r dataAndErrorBuffer) Read(p []byte) (n int, err error) {
return 0, r.err
}
func TestBasicPostRequest(t *testing.T) {
resp, _ := Post("http://httpbin.org/post",
&RequestOptions{Data: map[string]string{"One": "Two"}})
verifyOkPostResponse(resp, t)
}
func TestBasicRegularPostRequest(t *testing.T) {
resp, err := Post("http://httpbin.org/post",
&RequestOptions{Data: map[string]string{"One": "Two"}})
if err != nil {
t.Error("Cannot post: ", err)
}
verifyOkPostResponse(resp, t)
}
func TestBasicPostRequestInvalidURL(t *testing.T) {
resp, _ := Post("%../dir/",
&RequestOptions{Data: map[string]string{"One": "Two"},
Params: map[string]string{"1": "2"}})
if resp.Error == nil {
t.Error("Somehow the request went through")
}
}
func TestBasicPostRequestInvalidURLNoParams(t *testing.T) {
resp, _ := Post("%../dir/", &RequestOptions{Data: map[string]string{"One": "Two"}})
if resp.Error == nil {
t.Error("Somehow the request went through")
}
}
func TestSessionPostRequestInvalidURLNoParams(t *testing.T) {
session := NewSession(nil)
if _, err := session.Post("%../dir/", &RequestOptions{Data: map[string]string{"One": "Two"}}); err == nil {
t.Error("Somehow the request went through")
}
}
func TestXMLPostRequestInvalidURL(t *testing.T) {
resp, _ := Post("%../dir/",
&RequestOptions{XML: XMLPostMessage{Name: "Human", Age: 1, Height: 1}})
if resp.Error == nil {
t.Error("Somehow the request went through")
}
}
func TestXMLSessionPostRequestInvalidURL(t *testing.T) {
session := NewSession(nil)
_, err := session.Post("%../dir/",
&RequestOptions{XML: XMLPostMessage{Name: "Human", Age: 1, Height: 1}})
if err == nil {
t.Error("Somehow the request went through")
}
}
func TestBasicPostJsonRequestInvalidURL(t *testing.T) {
_, err := Post("%../dir/",
&RequestOptions{JSON: map[string]string{"One": "Two"}, IsAjax: true})
if err == nil {
t.Error("Somehow the request went through")
}
}
func TestSessionPostJsonRequestInvalidURL(t *testing.T) {
session := NewSession(nil)
_, err := session.Post("%../dir/",
&RequestOptions{JSON: map[string]string{"One": "Two"}, IsAjax: true})
if err == nil {
t.Error("Somehow the request went through")
}
}
func TestBasicPostJsonRequestInvalidJSON(t *testing.T) {
resp, err := Post("http://httpbin.org/post",
&RequestOptions{JSON: math.NaN(), IsAjax: true})
if err == nil {
t.Error("Somehow the request went through")
}
if resp.Ok == true {
t.Error("Somehow the request is OK")
}
}
func TestSessionPostJsonRequestInvalidJSON(t *testing.T) {
session := NewSession(nil)
resp, err := session.Post("http://httpbin.org/post",
&RequestOptions{JSON: math.NaN(), IsAjax: true})
if err == nil {
t.Error("Somehow the request went through")
}
if resp.Ok == true {
t.Error("Somehow the request is OK")
}
}
func TestBasicPostJsonRequestInvalidXML(t *testing.T) {
resp, err := Post("http://httpbin.org/post",
&RequestOptions{XML: map[string]string{"One": "two"}, IsAjax: true})
if err == nil {
t.Error("Somehow the request went through")
}
if resp.Ok == true {
t.Error("Somehow the request is OK")
}
}
func TestSessionPostJsonRequestInvalidXML(t *testing.T) {
session := NewSession(nil)
resp, err := session.Post("http://httpbin.org/post",
&RequestOptions{XML: map[string]string{"One": "two"}, IsAjax: true})
if err == nil {
t.Error("Somehow the request went through")
}
if resp.Ok == true {
t.Error("Somehow the request is OK")
}
}
func TestBasicPostRequestUploadInvalidURL(t *testing.T) {
fd, err := FileUploadFromDisk("testdata/mypassword")
if err != nil {
t.Error("Unable to open file: ", err)
}
defer fd[0].FileContents.Close()
resp, _ := Post("%../dir/",
&RequestOptions{
Files: fd,
Data: map[string]string{"One": "Two"},
})
if resp.Error == nil {
t.Fatal("Somehow able to make the request")
}
}
func TestSessionPostRequestUploadInvalidURL(t *testing.T) {
session := NewSession(nil)
fd, err := FileUploadFromDisk("testdata/mypassword")
if err != nil {
t.Error("Unable to open file: ", err)
}
defer fd[0].FileContents.Close()
_, err = session.Post("%../dir/",
&RequestOptions{
Files: fd,
Data: map[string]string{"One": "Two"},
})
if err == nil {
t.Fatal("Somehow able to make the request")
}
}
func TestBasicPostRequestUploadInvalidFileUpload(t *testing.T) {
resp, _ := Post("%../dir/",
&RequestOptions{
Files: []FileUpload{{FileName: `\x00%'"üfdsufhid\Ä\"D\\\"JS%25//'"H•\\\\'"¶•ªç∂\uf8\x8AKÔÓÔ`, FileContents: nil}},
Data: map[string]string{"One": "Two"},
})
if resp.Error == nil {
t.Fatal("Somehow able to make the request")
}
}
func TestSessionPostRequestUploadInvalidFileUpload(t *testing.T) {
session := NewSession(nil)
_, err := session.Post("%../dir/",
&RequestOptions{
Files: []FileUpload{{FileName: "üfdsufhidÄDJSHAKÔÓÔ", FileContents: nil}},
Data: map[string]string{"One": "Two"},
})
if err == nil {
t.Fatal("Somehow able to make the request")
}
}
func TestXMLPostRequest(t *testing.T) {
resp, _ := Post("http://httpbin.org/post",
&RequestOptions{XML: XMLPostMessage{Name: "Human", Age: 1, Height: 1}})
if resp.Error != nil {
t.Fatal("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicPostJSONResponse{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Unable to coerce to JSON", err)
}
myXMLStruct := &XMLPostMessage{}
xml.Unmarshal([]byte(myJSONStruct.Data), myXMLStruct)
if myXMLStruct.Age != 1 {
t.Errorf("Unable to serialize XML response from within JSON %#v ", myXMLStruct)
}
}
func TestXMLPostRequestReaderBody(t *testing.T) {
msg := XMLPostMessage{Name: "Human", Age: 1, Height: 1}
derBytes, err := xml.Marshal(msg)
if err != nil {
t.Fatal("Unable to marshal XML", err)
}
resp, _ := Post("http://httpbin.org/post",
&RequestOptions{RequestBody: bytes.NewReader(derBytes)})
if resp.Error != nil {
t.Fatal("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicPostJSONResponse{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Unable to coerce to JSON", err)
}
myXMLStruct := &XMLPostMessage{}
xml.Unmarshal([]byte(myJSONStruct.Data), myXMLStruct)
if myXMLStruct.Age != 1 {
t.Errorf("Unable to serialize XML response from within JSON %#v ", myXMLStruct)
}
}
func TestXMLMarshaledStringPostRequest(t *testing.T) {
xmlStruct := XMLPostMessage{Name: "Human", Age: 1, Height: 1}
encoded, _ := xml.Marshal(xmlStruct)
resp, _ := Post("http://httpbin.org/post",
&RequestOptions{XML: string(encoded)})
if resp.Error != nil {
t.Fatal("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicPostJSONResponse{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Unable to response to JSON", err)
}
if myJSONStruct.Data != string(encoded) {
t.Error("Response is not valid", myJSONStruct.Data, string(encoded))
}
}
func TestXMLMarshaledBytesPostRequest(t *testing.T) {
xmlStruct := XMLPostMessage{Name: "Human", Age: 1, Height: 1}
encoded, _ := xml.Marshal(xmlStruct)
resp, _ := Post("http://httpbin.org/post",
&RequestOptions{XML: encoded})
if resp.Error != nil {
t.Fatal("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicPostJSONResponse{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Unable to response to JSON", err)
}
if myJSONStruct.Data != string(encoded) {
t.Error("Response is not valid", myJSONStruct.Data, string(encoded))
}
}
func TestXMLNilPostRequest(t *testing.T) {
resp, _ := Post("http://httpbin.org/post", &RequestOptions{XML: nil})
if resp.Error != nil {
t.Fatal("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicPostJSONResponse{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Unable to response to JSON", err)
}
if myJSONStruct.Data != "" {
t.Error("Response is not valid", myJSONStruct.Data)
}
}
func TestBasicPostRequestUploadErrorReader(t *testing.T) {
var rd dataAndErrorBuffer
rd.err = fmt.Errorf("Random Error")
_, err := Post("http://httpbin.org/post",
&RequestOptions{
Files: []FileUpload{{FileName: "Random.test", FileContents: rd}},
Data: map[string]string{"One": "Two"},
})
if err == nil {
t.Error("Somehow our test didn't fail...")
}
}
func TestBasicPostRequestUploadErrorEOFReader(t *testing.T) {
var rd dataAndErrorBuffer
rd.err = io.EOF
_, err := Post("http://httpbin.org/post",
&RequestOptions{
Files: []FileUpload{{FileName: "Random.test", FileContents: rd}},
Data: map[string]string{"One": "Two"},
})
if err != nil {
t.Error("Somehow our test didn't fail... ", err)
}
}
func TestBasicPostRequestUpload(t *testing.T) {
fd, err := FileUploadFromDisk("testdata/mypassword")
if err != nil {
t.Error("Unable to open file: ", err)
}
resp, _ := Post("http://httpbin.org/post",
&RequestOptions{
Files: fd,
Data: map[string]string{"One": "Two"},
})
if resp.Error != nil {
t.Fatal("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicPostFileUpload{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Unable to coerce to JSON", err)
}
if myJSONStruct.URL != "http://httpbin.org/post" {
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
}
if myJSONStruct.Headers.Host != "httpbin.org" {
t.Error("The host header is invalid")
}
if myJSONStruct.Files.File != "saucy sauce" {
t.Error("File upload contents have been modified: ", myJSONStruct.Files.File)
}
if resp.Bytes() != nil {
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
}
if resp.String() != "" {
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
}
if resp.StatusCode != 200 {
t.Error("Response returned a non-200 code")
}
if myJSONStruct.Form.One != "Two" {
t.Error("Unable to parse form properly", myJSONStruct.Form)
}
}
func TestBasicPostRequestUploadWithMime(t *testing.T) {
fd, err := os.Open("testdata/mypassword")
if err != nil {
t.Error("Unable to open file: ", err)
}
resp, _ := Post("http://httpbin.org/post",
&RequestOptions{
Files: []FileUpload{{FileContents: fd, FileMime: "text/plain"}},
Data: map[string]string{"One": "Two"},
})
if resp.Error != nil {
t.Fatal("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicPostFileUpload{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Unable to coerce to JSON", err)
}
if myJSONStruct.URL != "http://httpbin.org/post" {
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
}
if myJSONStruct.Headers.Host != "httpbin.org" {
t.Error("The host header is invalid")
}
if myJSONStruct.Files.File != "saucy sauce" {
t.Error("File upload contents have been modified: ", myJSONStruct.Files.File)
}
if resp.Bytes() != nil {
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
}
if resp.String() != "" {
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
}
if resp.StatusCode != 200 {
t.Error("Response returned a non-200 code")
}
if myJSONStruct.Form.One != "Two" {
t.Error("Unable to parse form properly", myJSONStruct.Form)
}
// TODO: Ensure file field contains correct content-type, field, and
// filename information as soon as
// https://github.com/kennethreitz/httpbin/pull/388 gets merged
// (Or figure out a way to test this case the PR is rejected)
}
func TestBasicPostRequestUploadMultipleFiles(t *testing.T) {
fd, err := FileUploadFromGlob("testdata/*")
if err != nil {
t.Error("Unable to glob file: ", err)
}
resp, _ := Post("http://httpbin.org/post",
&RequestOptions{
Files: fd,
Data: map[string]string{"One": "Two"},
})
if resp.Error != nil {
t.Fatal("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicMultiFileUploadResponse{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Unable to coerce to JSON", err)
}
if myJSONStruct.URL != "http://httpbin.org/post" {
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
}
if myJSONStruct.Headers.Host != "httpbin.org" {
t.Error("The host header is invalid")
}
if myJSONStruct.Files.File2 != "saucy sauce" {
t.Error("File upload contents have been modified: ", myJSONStruct.Files.File2)
}
if myJSONStruct.Files.File1 != "I am just here to test the glob" {
t.Error("File upload contents have been modified: ", myJSONStruct.Files.File1)
}
if resp.Bytes() != nil {
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
}
if resp.String() != "" {
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
}
if resp.StatusCode != 200 {
t.Error("Response returned a non-200 code")
}
if myJSONStruct.Form.One != "Two" {
t.Error("Unable to parse form properly", myJSONStruct.Form)
}
}
func TestBasicPostJsonBytesRequest(t *testing.T) {
resp, _ := Post("http://httpbin.org/post",
&RequestOptions{JSON: []byte(`{"One":"Two"}`), IsAjax: true})
if resp.Error != nil {
t.Fatal("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicPostJSONResponse{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Unable to coerce to JSON", err)
}
if myJSONStruct.URL != "http://httpbin.org/post" {
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
}
if myJSONStruct.Headers.Host != "httpbin.org" {
t.Error("The host header is invalid")
}
if myJSONStruct.JSON.One != "Two" {
t.Error("Invalid post response: ", myJSONStruct.JSON.One)
}
if strings.TrimSpace(myJSONStruct.Data) != `{"One":"Two"}` {
t.Error("JSON not properly returned: ", myJSONStruct.Data)
}
if resp.Bytes() != nil {
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
}
if resp.String() != "" {
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
}
if resp.StatusCode != 200 {
t.Error("Response returned a non-200 code")
}
if myJSONStruct.Headers.XRequestedWith != "XMLHttpRequest" {
t.Error("Invalid requested header: ", myJSONStruct.Headers.XRequestedWith)
}
}
func TestBasicPostJsonStringRequest(t *testing.T) {
resp, _ := Post("http://httpbin.org/post",
&RequestOptions{JSON: `{"One":"Two"}`, IsAjax: true})
if resp.Error != nil {
t.Fatal("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicPostJSONResponse{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Unable to coerce to JSON", err)
}
if myJSONStruct.URL != "http://httpbin.org/post" {
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
}
if myJSONStruct.Headers.Host != "httpbin.org" {
t.Error("The host header is invalid")
}
if myJSONStruct.JSON.One != "Two" {
t.Error("Invalid post response: ", myJSONStruct.JSON.One)
}
if strings.TrimSpace(myJSONStruct.Data) != `{"One":"Two"}` {
t.Error("JSON not properly returned: ", myJSONStruct.Data)
}
if resp.Bytes() != nil {
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
}
if resp.String() != "" {
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
}
if resp.StatusCode != 200 {
t.Error("Response returned a non-200 code")
}
if myJSONStruct.Headers.XRequestedWith != "XMLHttpRequest" {
t.Error("Invalid requested header: ", myJSONStruct.Headers.XRequestedWith)
}
}
func TestBasicPostJsonRequest(t *testing.T) {
resp, _ := Post("http://httpbin.org/post",
&RequestOptions{JSON: map[string]string{"One": "Two"}, IsAjax: true})
if resp.Error != nil {
t.Fatal("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicPostJSONResponse{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Unable to coerce to JSON", err)
}
if myJSONStruct.URL != "http://httpbin.org/post" {
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
}
if myJSONStruct.Headers.Host != "httpbin.org" {
t.Error("The host header is invalid")
}
if myJSONStruct.JSON.One != "Two" {
t.Error("Invalid post response: ", myJSONStruct.JSON.One)
}
if strings.TrimSpace(myJSONStruct.Data) != `{"One":"Two"}` {
t.Error("JSON not properly returned: ", myJSONStruct.Data)
}
if resp.Bytes() != nil {
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
}
if resp.String() != "" {
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
}
if resp.StatusCode != 200 {
t.Error("Response returned a non-200 code")
}
if myJSONStruct.Headers.XRequestedWith != "XMLHttpRequest" {
t.Error("Invalid requested header: ", myJSONStruct.Headers.XRequestedWith)
}
}
func TestPostSession(t *testing.T) {
session := NewSession(nil)
resp, err := session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"one": "two"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"two": "three"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"three": "four"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Post("http://httpbin.org/post", &RequestOptions{Data: map[string]string{"one": "two"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
cookieURL, err := url.Parse("http://httpbin.org")
if err != nil {
t.Error("We (for some reason) cannot parse the cookie URL")
}
if len(session.HTTPClient.Jar.Cookies(cookieURL)) != 3 {
t.Error("Invalid number of cookies provided: ", session.HTTPClient.Jar.Cookies(cookieURL))
}
for _, cookie := range session.HTTPClient.Jar.Cookies(cookieURL) {
switch cookie.Name {
case "one":
if cookie.Value != "two" {
t.Error("Cookie value is not valid", cookie)
}
case "two":
if cookie.Value != "three" {
t.Error("Cookie value is not valid", cookie)
}
case "three":
if cookie.Value != "four" {
t.Error("Cookie value is not valid", cookie)
}
default:
t.Error("We should not have any other cookies: ", cookie)
}
}
}
// verifyResponse will verify the following conditions
// 1. The request didn't return an error
// 2. The response returned an OK (a status code within the 200 range)
// 3. The output can be coerced to JSON (this may change later)
// It should only be run when testing GET request to http://httpbin.org/post expecting JSON
func verifyOkPostResponse(resp *Response, t *testing.T) *BasicPostResponse {
if resp.Error != nil {
t.Fatal("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
myJSONStruct := &BasicPostResponse{}
if err := resp.JSON(myJSONStruct); err != nil {
t.Error("Unable to coerce to JSON", err)
}
if myJSONStruct.URL != "http://httpbin.org/post" {
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
}
if myJSONStruct.Headers.Host != "httpbin.org" {
t.Error("The host header is invalid")
}
if myJSONStruct.Form.One != "Two" {
t.Errorf("Invalid post response: %#v", myJSONStruct.Form)
}
if resp.Bytes() != nil {
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
}
if resp.String() != "" {
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
}
if resp.StatusCode != 200 {
t.Error("Response returned a non-200 code")
}
return myJSONStruct
}
func TestPostInvalidURLSession(t *testing.T) {
session := NewSession(nil)
if _, err := session.Post("%../dir/", nil); err == nil {
t.Error("Some how the request was valid to make request ", err)
}
}

View File

@ -1,163 +0,0 @@
package grequests
import (
"net/url"
"testing"
)
func TestBasicPutRequest(t *testing.T) {
resp, err := Put("http://httpbin.org/put", nil)
if err != nil {
t.Error("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
}
func TestBasicPutUploadRequest(t *testing.T) {
t.Skip("httpbin.org is broken, as of https://github.com/kennethreitz/httpbin/issues/340#issuecomment-330176449")
fd, err := FileUploadFromDisk("testdata/mypassword")
if err != nil {
t.Error("Unable to open file: ", err)
}
resp, _ := Put("http://httpbin.org/put",
&RequestOptions{
Files: fd,
Data: map[string]string{"One": "Two"},
})
if resp.Error != nil {
t.Error("Unable to make request", resp.Error)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
}
func TestBasicPutUploadRequestInvalidURL(t *testing.T) {
fd, err := FileUploadFromDisk("testdata/mypassword")
if err != nil {
t.Error("Unable to open file: ", err)
}
_, err = Put("%../dir/",
&RequestOptions{
Files: fd,
Data: map[string]string{"One": "Two"},
})
if err == nil {
t.Fatal("Somehow able to make the request")
}
}
func TestSessionPutUploadRequestInvalidURL(t *testing.T) {
fd, err := FileUploadFromDisk("testdata/mypassword")
if err != nil {
t.Error("Unable to open file: ", err)
}
session := NewSession(nil)
_, err = session.Put("%../dir/",
&RequestOptions{
Files: fd,
Data: map[string]string{"One": "Two"},
})
if err == nil {
t.Fatal("Somehow able to make the request")
}
}
func TestPutSession(t *testing.T) {
session := NewSession(nil)
resp, err := session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"one": "two"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"two": "three"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"three": "four"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
resp, err = session.Put("http://httpbin.org/put", &RequestOptions{Data: map[string]string{"one": "two"}})
if err != nil {
t.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
t.Error("Request did not return OK")
}
cookieURL, err := url.Parse("http://httpbin.org")
if err != nil {
t.Error("We (for some reason) cannot parse the cookie URL")
}
if len(session.HTTPClient.Jar.Cookies(cookieURL)) != 3 {
t.Error("Invalid number of cookies provided: ", session.HTTPClient.Jar.Cookies(cookieURL))
}
for _, cookie := range session.HTTPClient.Jar.Cookies(cookieURL) {
switch cookie.Name {
case "one":
if cookie.Value != "two" {
t.Error("Cookie value is not valid", cookie)
}
case "two":
if cookie.Value != "three" {
t.Error("Cookie value is not valid", cookie)
}
case "three":
if cookie.Value != "four" {
t.Error("Cookie value is not valid", cookie)
}
default:
t.Error("We should not have any other cookies: ", cookie)
}
}
}
func TestPutInvalidURLSession(t *testing.T) {
session := NewSession(nil)
if _, err := session.Put("%../dir/", nil); err == nil {
t.Error("Some how the request was valid to make request ", err)
}
}

View File

@ -1,323 +0,0 @@
package grequests_test
import (
"encoding/xml"
"io"
"log"
"net/http"
"net/url"
"github.com/levigross/grequests"
)
func Example_basicGet() {
// This is a very basic GET request
resp, err := grequests.Get("http://httpbin.org/get", nil)
if err != nil {
log.Println(err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
log.Println(resp.String())
}
func Example_basicGetCustomHTTPClient() {
// This is a very basic GET request
resp, err := grequests.Get("http://httpbin.org/get", &grequests.RequestOptions{HTTPClient: http.DefaultClient})
if err != nil {
log.Println(err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
log.Println(resp.String())
}
func Example_proxy() {
proxyURL, err := url.Parse("http://127.0.0.1:8080") // Proxy URL
if err != nil {
log.Panicln(err)
}
resp, err := grequests.Get("http://www.levigross.com/",
&grequests.RequestOptions{Proxies: map[string]*url.URL{proxyURL.Scheme: proxyURL}})
if err != nil {
log.Println(err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
log.Println(resp)
}
func Example_cookies() {
resp, err := grequests.Get("http://httpbin.org/cookies",
&grequests.RequestOptions{
Cookies: []*http.Cookie{
{
Name: "TestCookie",
Value: "Random Value",
HttpOnly: true,
Secure: false,
}, {
Name: "AnotherCookie",
Value: "Some Value",
HttpOnly: true,
Secure: false,
},
},
})
if err != nil {
log.Println("Unable to make request", err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
log.Println(resp.String())
}
func Example_session() {
session := grequests.NewSession(nil)
resp, err := session.Get("http://httpbin.org/cookies/set", &grequests.RequestOptions{Params: map[string]string{"one": "two"}})
if err != nil {
log.Fatal("Cannot set cookie: ", err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
log.Println(resp.String())
}
func Example_parse_XML() {
type GetXMLSample struct {
XMLName xml.Name `xml:"slideshow"`
Title string `xml:"title,attr"`
Date string `xml:"date,attr"`
Author string `xml:"author,attr"`
Slide []struct {
Type string `xml:"type,attr"`
Title string `xml:"title"`
} `xml:"slide"`
}
resp, err := grequests.Get("http://httpbin.org/xml", nil)
if err != nil {
log.Println("Unable to make request", err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
userXML := &GetXMLSample{}
// func xmlASCIIDecoder(charset string, input io.Reader) (io.Reader, error) {
// return input, nil
// }
// If the server returns XML encoded in another charset (not UTF-8) you
// must provide an encoder function that looks like the one I wrote above.
// If you an consuming UTF-8 just pass `nil` into the second arg
if err := resp.XML(userXML, xmlASCIIDecoder); err != nil {
log.Println("Unable to consume the response as XML: ", err)
}
if userXML.Title != "Sample Slide Show" {
log.Printf("Invalid XML serialization %#v", userXML)
}
}
func Example_customUserAgent() {
ro := &grequests.RequestOptions{UserAgent: "LeviBot 0.1"}
resp, err := grequests.Get("http://httpbin.org/get", ro)
if err != nil {
log.Fatal("Oops something went wrong: ", err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
log.Println(resp.String())
}
func Example_basicAuth() {
ro := &grequests.RequestOptions{Auth: []string{"Levi", "Bot"}}
resp, err := grequests.Get("http://httpbin.org/get", ro)
// Not the usual JSON so copy and paste from below
if err != nil {
log.Println("Unable to make request", err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
}
func Example_customHTTPHeader() {
ro := &grequests.RequestOptions{UserAgent: "LeviBot 0.1",
Headers: map[string]string{"X-Wonderful-Header": "1"}}
resp, err := grequests.Get("http://httpbin.org/get", ro)
// Not the usual JSON so copy and paste from below
if err != nil {
log.Println("Unable to make request", err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
}
func Example_acceptInvalidTLSCert() {
ro := &grequests.RequestOptions{InsecureSkipVerify: true}
resp, err := grequests.Get("https://www.pcwebshop.co.uk/", ro)
if err != nil {
log.Println("Unable to make request", err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
}
func Example_urlQueryParams() {
ro := &grequests.RequestOptions{
Params: map[string]string{"Hello": "World", "Goodbye": "World"},
}
resp, err := grequests.Get("http://httpbin.org/get", ro)
// url will now be http://httpbin.org/get?hello=world&goodbye=world
if err != nil {
log.Println("Unable to make request", err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
}
func Example_downloadFile() {
resp, err := grequests.Get("http://httpbin.org/get", nil)
if err != nil {
log.Println("Unable to make request", err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
if err := resp.DownloadToFile("randomFile"); err != nil {
log.Println("Unable to download to file: ", err)
}
if err != nil {
log.Println("Unable to download file", err)
}
}
func Example_postForm() {
resp, err := grequests.Post("http://httpbin.org/post",
&grequests.RequestOptions{Data: map[string]string{"One": "Two"}})
// This is the basic form POST. The request body will be `one=two`
if err != nil {
log.Println("Cannot post: ", err)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
}
func Example_postXML() {
type XMLPostMessage struct {
Name string
Age int
Height int
}
resp, err := grequests.Post("http://httpbin.org/post",
&grequests.RequestOptions{XML: XMLPostMessage{Name: "Human", Age: 1, Height: 1}})
// The request body will contain the XML generated by the `XMLPostMessage` struct
if err != nil {
log.Println("Unable to make request", resp.Error)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
}
func Example_postFileUpload() {
fd, err := grequests.FileUploadFromDisk("test_files/mypassword")
if err != nil {
log.Println("Unable to open file: ", err)
}
// This will upload the file as a multipart mime request
resp, err := grequests.Post("http://httpbin.org/post",
&grequests.RequestOptions{
Files: fd,
Data: map[string]string{"One": "Two"},
})
if err != nil {
log.Println("Unable to make request", resp.Error)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
}
func Example_postJSONAJAX() {
resp, err := grequests.Post("http://httpbin.org/post",
&grequests.RequestOptions{
JSON: map[string]string{"One": "Two"},
IsAjax: true, // this adds the X-Requested-With: XMLHttpRequest header
})
if err != nil {
log.Println("Unable to make request", resp.Error)
}
if resp.Ok != true {
log.Println("Request did not return OK")
}
}
func xmlASCIIDecoder(charset string, input io.Reader) (io.Reader, error) {
return input, nil
}

View File

@ -1,53 +0,0 @@
package grequests
import "testing"
func TestErrorOpenFile(t *testing.T) {
fd, err := FileUploadFromDisk("I am Not A File")
if err == nil {
t.Error("We are not getting an error back from our non existent file: ")
}
if fd != nil {
t.Error("We actually got back a pointer: ", fd)
}
}
func TestGLOBFiles(t *testing.T) {
fd, err := FileUploadFromGlob("testdata/*")
if err != nil {
t.Error("Got an invalid GLOB: ", err)
}
if len(fd) != 2 {
t.Error("Some how we have more than two files in our glob", len(fd), fd)
}
}
func TestInvalidGlob(t *testing.T) {
if _, err := FileUploadFromGlob("[-]"); err == nil {
t.Error("Somehow the glob worked")
}
}
func TestNoGlobFiles(t *testing.T) {
if _, err := FileUploadFromGlob("notapath"); err == nil {
t.Error("Somehow got a valid GLOB")
}
}
func TestGlobWithDir(t *testing.T) {
fd, err := FileUploadFromGlob("*test*")
if err != nil {
t.Error("Glob failed", err)
}
for _, f := range fd {
if f.FileName == "test_files" {
t.Error(f, "is a dir (which cannot be uploaded)")
}
}
}

View File

@ -1,39 +0,0 @@
package grequests
import "testing"
func TestAddQueryStringParams(t *testing.T) {
userURL, err := buildURLParams("https://www.google.com/", map[string]string{"1": "2", "3": "4"})
if err != nil {
t.Error("URL Parse Error: ", err)
}
if userURL != "https://www.google.com/?1=2&3=4" {
t.Error("URL params not properly built", userURL)
}
}
func TestSortAddQueryStringParams(t *testing.T) {
userURL, err := buildURLParams("https://www.google.com/", map[string]string{"3": "4", "1": "2"})
if err != nil {
t.Error("URL Parse Error: ", err)
}
if userURL != "https://www.google.com/?1=2&3=4" {
t.Error("URL params not properly built and sorted", userURL)
}
}
func TestAddQueryStringParamsExistingParam(t *testing.T) {
userURL, err := buildURLParams("https://www.google.com/?5=6", map[string]string{"3": "4", "1": "2"})
if err != nil {
t.Error("URL Parse Error: ", err)
}
if userURL != "https://www.google.com/?1=2&3=4&5=6" {
t.Error("URL params not properly built and sorted", userURL)
}
}

View File

@ -1,26 +0,0 @@
package grequests
import (
"strconv"
"testing"
)
func TestResponseOk(t *testing.T) {
status := []int{200, 201, 202, 203, 204, 205, 206, 207, 208, 226}
for _, status := range status {
verifyResponseOkForStatus(status, t)
}
}
func verifyResponseOkForStatus(status int, t *testing.T) {
url := "http://httpbin.org/status/" + strconv.Itoa(status)
resp, err := Get(url, nil)
if err != nil {
t.Error("Unable to make request", err)
}
if resp.Ok != true {
t.Errorf("Request did not return OK. Received status code %d rather a 2xx.", resp.StatusCode)
}
}

View File

@ -1 +0,0 @@
I am just here to test the glob

View File

@ -1 +0,0 @@
saucy sauce

View File

@ -1 +0,0 @@
package grequests

24
vendor/github.com/pkg/errors/.gitignore generated vendored Normal file
View File

@ -0,0 +1,24 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof

15
vendor/github.com/pkg/errors/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,15 @@
language: go
go_import_path: github.com/pkg/errors
go:
- 1.4.x
- 1.5.x
- 1.6.x
- 1.7.x
- 1.8.x
- 1.9.x
- 1.10.x
- 1.11.x
- tip
script:
- go test -v ./...

View File

@ -1,63 +0,0 @@
// +build go1.7
package errors
import (
"fmt"
"testing"
stderrors "errors"
)
func noErrors(at, depth int) error {
if at >= depth {
return stderrors.New("no error")
}
return noErrors(at+1, depth)
}
func yesErrors(at, depth int) error {
if at >= depth {
return New("ye error")
}
return yesErrors(at+1, depth)
}
// GlobalE is an exported global to store the result of benchmark results,
// preventing the compiler from optimising the benchmark functions away.
var GlobalE error
func BenchmarkErrors(b *testing.B) {
type run struct {
stack int
std bool
}
runs := []run{
{10, false},
{10, true},
{100, false},
{100, true},
{1000, false},
{1000, true},
}
for _, r := range runs {
part := "pkg/errors"
if r.std {
part = "errors"
}
name := fmt.Sprintf("%s-stack-%d", part, r.stack)
b.Run(name, func(b *testing.B) {
var err error
f := yesErrors
if r.std {
f = noErrors
}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
err = f(0, r.stack)
}
b.StopTimer()
GlobalE = err
})
}
}

View File

@ -1,251 +0,0 @@
package errors
import (
"errors"
"fmt"
"io"
"reflect"
"testing"
)
func TestNew(t *testing.T) {
tests := []struct {
err string
want error
}{
{"", fmt.Errorf("")},
{"foo", fmt.Errorf("foo")},
{"foo", New("foo")},
{"string with format specifiers: %v", errors.New("string with format specifiers: %v")},
}
for _, tt := range tests {
got := New(tt.err)
if got.Error() != tt.want.Error() {
t.Errorf("New.Error(): got: %q, want %q", got, tt.want)
}
}
}
func TestWrapNil(t *testing.T) {
got := Wrap(nil, "no error")
if got != nil {
t.Errorf("Wrap(nil, \"no error\"): got %#v, expected nil", got)
}
}
func TestWrap(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{Wrap(io.EOF, "read error"), "client error", "client error: read error: EOF"},
}
for _, tt := range tests {
got := Wrap(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("Wrap(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want)
}
}
}
type nilError struct{}
func (nilError) Error() string { return "nil error" }
func TestCause(t *testing.T) {
x := New("error")
tests := []struct {
err error
want error
}{{
// nil error is nil
err: nil,
want: nil,
}, {
// explicit nil error is nil
err: (error)(nil),
want: nil,
}, {
// typed nil is nil
err: (*nilError)(nil),
want: (*nilError)(nil),
}, {
// uncaused error is unaffected
err: io.EOF,
want: io.EOF,
}, {
// caused error returns cause
err: Wrap(io.EOF, "ignored"),
want: io.EOF,
}, {
err: x, // return from errors.New
want: x,
}, {
WithMessage(nil, "whoops"),
nil,
}, {
WithMessage(io.EOF, "whoops"),
io.EOF,
}, {
WithStack(nil),
nil,
}, {
WithStack(io.EOF),
io.EOF,
}}
for i, tt := range tests {
got := Cause(tt.err)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want)
}
}
}
func TestWrapfNil(t *testing.T) {
got := Wrapf(nil, "no error")
if got != nil {
t.Errorf("Wrapf(nil, \"no error\"): got %#v, expected nil", got)
}
}
func TestWrapf(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"},
{Wrapf(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"},
}
for _, tt := range tests {
got := Wrapf(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want)
}
}
}
func TestErrorf(t *testing.T) {
tests := []struct {
err error
want string
}{
{Errorf("read error without format specifiers"), "read error without format specifiers"},
{Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"},
}
for _, tt := range tests {
got := tt.err.Error()
if got != tt.want {
t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want)
}
}
}
func TestWithStackNil(t *testing.T) {
got := WithStack(nil)
if got != nil {
t.Errorf("WithStack(nil): got %#v, expected nil", got)
}
}
func TestWithStack(t *testing.T) {
tests := []struct {
err error
want string
}{
{io.EOF, "EOF"},
{WithStack(io.EOF), "EOF"},
}
for _, tt := range tests {
got := WithStack(tt.err).Error()
if got != tt.want {
t.Errorf("WithStack(%v): got: %v, want %v", tt.err, got, tt.want)
}
}
}
func TestWithMessageNil(t *testing.T) {
got := WithMessage(nil, "no error")
if got != nil {
t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got)
}
}
func TestWithMessage(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{WithMessage(io.EOF, "read error"), "client error", "client error: read error: EOF"},
}
for _, tt := range tests {
got := WithMessage(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want)
}
}
}
func TestWithMessagefNil(t *testing.T) {
got := WithMessagef(nil, "no error")
if got != nil {
t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got)
}
}
func TestWithMessagef(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{WithMessagef(io.EOF, "read error without format specifier"), "client error", "client error: read error without format specifier: EOF"},
{WithMessagef(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"},
}
for _, tt := range tests {
got := WithMessagef(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want)
}
}
}
// errors.New, etc values are not expected to be compared by value
// but the change in errors#27 made them incomparable. Assert that
// various kinds of errors have a functional equality operator, even
// if the result of that equality is always false.
func TestErrorEquality(t *testing.T) {
vals := []error{
nil,
io.EOF,
errors.New("EOF"),
New("EOF"),
Errorf("EOF"),
Wrap(io.EOF, "EOF"),
Wrapf(io.EOF, "EOF%d", 2),
WithMessage(nil, "whoops"),
WithMessage(io.EOF, "whoops"),
WithStack(io.EOF),
WithStack(nil),
}
for i := range vals {
for j := range vals {
_ = vals[i] == vals[j] // mustn't panic
}
}
}

View File

@ -1,205 +0,0 @@
package errors_test
import (
"fmt"
"github.com/pkg/errors"
)
func ExampleNew() {
err := errors.New("whoops")
fmt.Println(err)
// Output: whoops
}
func ExampleNew_printf() {
err := errors.New("whoops")
fmt.Printf("%+v", err)
// Example output:
// whoops
// github.com/pkg/errors_test.ExampleNew_printf
// /home/dfc/src/github.com/pkg/errors/example_test.go:17
// testing.runExample
// /home/dfc/go/src/testing/example.go:114
// testing.RunExamples
// /home/dfc/go/src/testing/example.go:38
// testing.(*M).Run
// /home/dfc/go/src/testing/testing.go:744
// main.main
// /github.com/pkg/errors/_test/_testmain.go:106
// runtime.main
// /home/dfc/go/src/runtime/proc.go:183
// runtime.goexit
// /home/dfc/go/src/runtime/asm_amd64.s:2059
}
func ExampleWithMessage() {
cause := errors.New("whoops")
err := errors.WithMessage(cause, "oh noes")
fmt.Println(err)
// Output: oh noes: whoops
}
func ExampleWithStack() {
cause := errors.New("whoops")
err := errors.WithStack(cause)
fmt.Println(err)
// Output: whoops
}
func ExampleWithStack_printf() {
cause := errors.New("whoops")
err := errors.WithStack(cause)
fmt.Printf("%+v", err)
// Example Output:
// whoops
// github.com/pkg/errors_test.ExampleWithStack_printf
// /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55
// testing.runExample
// /usr/lib/go/src/testing/example.go:114
// testing.RunExamples
// /usr/lib/go/src/testing/example.go:38
// testing.(*M).Run
// /usr/lib/go/src/testing/testing.go:744
// main.main
// github.com/pkg/errors/_test/_testmain.go:106
// runtime.main
// /usr/lib/go/src/runtime/proc.go:183
// runtime.goexit
// /usr/lib/go/src/runtime/asm_amd64.s:2086
// github.com/pkg/errors_test.ExampleWithStack_printf
// /home/fabstu/go/src/github.com/pkg/errors/example_test.go:56
// testing.runExample
// /usr/lib/go/src/testing/example.go:114
// testing.RunExamples
// /usr/lib/go/src/testing/example.go:38
// testing.(*M).Run
// /usr/lib/go/src/testing/testing.go:744
// main.main
// github.com/pkg/errors/_test/_testmain.go:106
// runtime.main
// /usr/lib/go/src/runtime/proc.go:183
// runtime.goexit
// /usr/lib/go/src/runtime/asm_amd64.s:2086
}
func ExampleWrap() {
cause := errors.New("whoops")
err := errors.Wrap(cause, "oh noes")
fmt.Println(err)
// Output: oh noes: whoops
}
func fn() error {
e1 := errors.New("error")
e2 := errors.Wrap(e1, "inner")
e3 := errors.Wrap(e2, "middle")
return errors.Wrap(e3, "outer")
}
func ExampleCause() {
err := fn()
fmt.Println(err)
fmt.Println(errors.Cause(err))
// Output: outer: middle: inner: error
// error
}
func ExampleWrap_extended() {
err := fn()
fmt.Printf("%+v\n", err)
// Example output:
// error
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:47
// github.com/pkg/errors_test.ExampleCause_printf
// /home/dfc/src/github.com/pkg/errors/example_test.go:63
// testing.runExample
// /home/dfc/go/src/testing/example.go:114
// testing.RunExamples
// /home/dfc/go/src/testing/example.go:38
// testing.(*M).Run
// /home/dfc/go/src/testing/testing.go:744
// main.main
// /github.com/pkg/errors/_test/_testmain.go:104
// runtime.main
// /home/dfc/go/src/runtime/proc.go:183
// runtime.goexit
// /home/dfc/go/src/runtime/asm_amd64.s:2059
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer
}
func ExampleWrapf() {
cause := errors.New("whoops")
err := errors.Wrapf(cause, "oh noes #%d", 2)
fmt.Println(err)
// Output: oh noes #2: whoops
}
func ExampleErrorf_extended() {
err := errors.Errorf("whoops: %s", "foo")
fmt.Printf("%+v", err)
// Example output:
// whoops: foo
// github.com/pkg/errors_test.ExampleErrorf
// /home/dfc/src/github.com/pkg/errors/example_test.go:101
// testing.runExample
// /home/dfc/go/src/testing/example.go:114
// testing.RunExamples
// /home/dfc/go/src/testing/example.go:38
// testing.(*M).Run
// /home/dfc/go/src/testing/testing.go:744
// main.main
// /github.com/pkg/errors/_test/_testmain.go:102
// runtime.main
// /home/dfc/go/src/runtime/proc.go:183
// runtime.goexit
// /home/dfc/go/src/runtime/asm_amd64.s:2059
}
func Example_stackTrace() {
type stackTracer interface {
StackTrace() errors.StackTrace
}
err, ok := errors.Cause(fn()).(stackTracer)
if !ok {
panic("oops, err does not implement stackTracer")
}
st := err.StackTrace()
fmt.Printf("%+v", st[0:2]) // top two frames
// Example output:
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:47
// github.com/pkg/errors_test.Example_stackTrace
// /home/dfc/src/github.com/pkg/errors/example_test.go:127
}
func ExampleCause_printf() {
err := errors.Wrap(func() error {
return func() error {
return errors.Errorf("hello %s", fmt.Sprintf("world"))
}()
}(), "failed")
fmt.Printf("%v", err)
// Output: failed: hello world
}

View File

@ -1,535 +0,0 @@
package errors
import (
"errors"
"fmt"
"io"
"regexp"
"strings"
"testing"
)
func TestFormatNew(t *testing.T) {
tests := []struct {
error
format string
want string
}{{
New("error"),
"%s",
"error",
}, {
New("error"),
"%v",
"error",
}, {
New("error"),
"%+v",
"error\n" +
"github.com/pkg/errors.TestFormatNew\n" +
"\t.+/github.com/pkg/errors/format_test.go:26",
}, {
New("error"),
"%q",
`"error"`,
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
}
}
func TestFormatErrorf(t *testing.T) {
tests := []struct {
error
format string
want string
}{{
Errorf("%s", "error"),
"%s",
"error",
}, {
Errorf("%s", "error"),
"%v",
"error",
}, {
Errorf("%s", "error"),
"%+v",
"error\n" +
"github.com/pkg/errors.TestFormatErrorf\n" +
"\t.+/github.com/pkg/errors/format_test.go:56",
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
}
}
func TestFormatWrap(t *testing.T) {
tests := []struct {
error
format string
want string
}{{
Wrap(New("error"), "error2"),
"%s",
"error2: error",
}, {
Wrap(New("error"), "error2"),
"%v",
"error2: error",
}, {
Wrap(New("error"), "error2"),
"%+v",
"error\n" +
"github.com/pkg/errors.TestFormatWrap\n" +
"\t.+/github.com/pkg/errors/format_test.go:82",
}, {
Wrap(io.EOF, "error"),
"%s",
"error: EOF",
}, {
Wrap(io.EOF, "error"),
"%v",
"error: EOF",
}, {
Wrap(io.EOF, "error"),
"%+v",
"EOF\n" +
"error\n" +
"github.com/pkg/errors.TestFormatWrap\n" +
"\t.+/github.com/pkg/errors/format_test.go:96",
}, {
Wrap(Wrap(io.EOF, "error1"), "error2"),
"%+v",
"EOF\n" +
"error1\n" +
"github.com/pkg/errors.TestFormatWrap\n" +
"\t.+/github.com/pkg/errors/format_test.go:103\n",
}, {
Wrap(New("error with space"), "context"),
"%q",
`"context: error with space"`,
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
}
}
func TestFormatWrapf(t *testing.T) {
tests := []struct {
error
format string
want string
}{{
Wrapf(io.EOF, "error%d", 2),
"%s",
"error2: EOF",
}, {
Wrapf(io.EOF, "error%d", 2),
"%v",
"error2: EOF",
}, {
Wrapf(io.EOF, "error%d", 2),
"%+v",
"EOF\n" +
"error2\n" +
"github.com/pkg/errors.TestFormatWrapf\n" +
"\t.+/github.com/pkg/errors/format_test.go:134",
}, {
Wrapf(New("error"), "error%d", 2),
"%s",
"error2: error",
}, {
Wrapf(New("error"), "error%d", 2),
"%v",
"error2: error",
}, {
Wrapf(New("error"), "error%d", 2),
"%+v",
"error\n" +
"github.com/pkg/errors.TestFormatWrapf\n" +
"\t.+/github.com/pkg/errors/format_test.go:149",
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
}
}
func TestFormatWithStack(t *testing.T) {
tests := []struct {
error
format string
want []string
}{{
WithStack(io.EOF),
"%s",
[]string{"EOF"},
}, {
WithStack(io.EOF),
"%v",
[]string{"EOF"},
}, {
WithStack(io.EOF),
"%+v",
[]string{"EOF",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:175"},
}, {
WithStack(New("error")),
"%s",
[]string{"error"},
}, {
WithStack(New("error")),
"%v",
[]string{"error"},
}, {
WithStack(New("error")),
"%+v",
[]string{"error",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:189",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:189"},
}, {
WithStack(WithStack(io.EOF)),
"%+v",
[]string{"EOF",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:197",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:197"},
}, {
WithStack(WithStack(Wrapf(io.EOF, "message"))),
"%+v",
[]string{"EOF",
"message",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:205",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:205",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:205"},
}, {
WithStack(Errorf("error%d", 1)),
"%+v",
[]string{"error1",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:216",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:216"},
}}
for i, tt := range tests {
testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true)
}
}
func TestFormatWithMessage(t *testing.T) {
tests := []struct {
error
format string
want []string
}{{
WithMessage(New("error"), "error2"),
"%s",
[]string{"error2: error"},
}, {
WithMessage(New("error"), "error2"),
"%v",
[]string{"error2: error"},
}, {
WithMessage(New("error"), "error2"),
"%+v",
[]string{
"error",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:244",
"error2"},
}, {
WithMessage(io.EOF, "addition1"),
"%s",
[]string{"addition1: EOF"},
}, {
WithMessage(io.EOF, "addition1"),
"%v",
[]string{"addition1: EOF"},
}, {
WithMessage(io.EOF, "addition1"),
"%+v",
[]string{"EOF", "addition1"},
}, {
WithMessage(WithMessage(io.EOF, "addition1"), "addition2"),
"%v",
[]string{"addition2: addition1: EOF"},
}, {
WithMessage(WithMessage(io.EOF, "addition1"), "addition2"),
"%+v",
[]string{"EOF", "addition1", "addition2"},
}, {
Wrap(WithMessage(io.EOF, "error1"), "error2"),
"%+v",
[]string{"EOF", "error1", "error2",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:272"},
}, {
WithMessage(Errorf("error%d", 1), "error2"),
"%+v",
[]string{"error1",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:278",
"error2"},
}, {
WithMessage(WithStack(io.EOF), "error"),
"%+v",
[]string{
"EOF",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:285",
"error"},
}, {
WithMessage(Wrap(WithStack(io.EOF), "inside-error"), "outside-error"),
"%+v",
[]string{
"EOF",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:293",
"inside-error",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:293",
"outside-error"},
}}
for i, tt := range tests {
testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true)
}
}
func TestFormatGeneric(t *testing.T) {
starts := []struct {
err error
want []string
}{
{New("new-error"), []string{
"new-error",
"github.com/pkg/errors.TestFormatGeneric\n" +
"\t.+/github.com/pkg/errors/format_test.go:315"},
}, {Errorf("errorf-error"), []string{
"errorf-error",
"github.com/pkg/errors.TestFormatGeneric\n" +
"\t.+/github.com/pkg/errors/format_test.go:319"},
}, {errors.New("errors-new-error"), []string{
"errors-new-error"},
},
}
wrappers := []wrapper{
{
func(err error) error { return WithMessage(err, "with-message") },
[]string{"with-message"},
}, {
func(err error) error { return WithStack(err) },
[]string{
"github.com/pkg/errors.(func·002|TestFormatGeneric.func2)\n\t" +
".+/github.com/pkg/errors/format_test.go:333",
},
}, {
func(err error) error { return Wrap(err, "wrap-error") },
[]string{
"wrap-error",
"github.com/pkg/errors.(func·003|TestFormatGeneric.func3)\n\t" +
".+/github.com/pkg/errors/format_test.go:339",
},
}, {
func(err error) error { return Wrapf(err, "wrapf-error%d", 1) },
[]string{
"wrapf-error1",
"github.com/pkg/errors.(func·004|TestFormatGeneric.func4)\n\t" +
".+/github.com/pkg/errors/format_test.go:346",
},
},
}
for s := range starts {
err := starts[s].err
want := starts[s].want
testFormatCompleteCompare(t, s, err, "%+v", want, false)
testGenericRecursive(t, err, want, wrappers, 3)
}
}
func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) {
got := fmt.Sprintf(format, arg)
gotLines := strings.SplitN(got, "\n", -1)
wantLines := strings.SplitN(want, "\n", -1)
if len(wantLines) > len(gotLines) {
t.Errorf("test %d: wantLines(%d) > gotLines(%d):\n got: %q\nwant: %q", n+1, len(wantLines), len(gotLines), got, want)
return
}
for i, w := range wantLines {
match, err := regexp.MatchString(w, gotLines[i])
if err != nil {
t.Fatal(err)
}
if !match {
t.Errorf("test %d: line %d: fmt.Sprintf(%q, err):\n got: %q\nwant: %q", n+1, i+1, format, got, want)
}
}
}
var stackLineR = regexp.MustCompile(`\.`)
// parseBlocks parses input into a slice, where:
// - incase entry contains a newline, its a stacktrace
// - incase entry contains no newline, its a solo line.
//
// Detecting stack boundaries only works incase the WithStack-calls are
// to be found on the same line, thats why it is optionally here.
//
// Example use:
//
// for _, e := range blocks {
// if strings.ContainsAny(e, "\n") {
// // Match as stack
// } else {
// // Match as line
// }
// }
//
func parseBlocks(input string, detectStackboundaries bool) ([]string, error) {
var blocks []string
stack := ""
wasStack := false
lines := map[string]bool{} // already found lines
for _, l := range strings.Split(input, "\n") {
isStackLine := stackLineR.MatchString(l)
switch {
case !isStackLine && wasStack:
blocks = append(blocks, stack, l)
stack = ""
lines = map[string]bool{}
case isStackLine:
if wasStack {
// Detecting two stacks after another, possible cause lines match in
// our tests due to WithStack(WithStack(io.EOF)) on same line.
if detectStackboundaries {
if lines[l] {
if len(stack) == 0 {
return nil, errors.New("len of block must not be zero here")
}
blocks = append(blocks, stack)
stack = l
lines = map[string]bool{l: true}
continue
}
}
stack = stack + "\n" + l
} else {
stack = l
}
lines[l] = true
case !isStackLine && !wasStack:
blocks = append(blocks, l)
default:
return nil, errors.New("must not happen")
}
wasStack = isStackLine
}
// Use up stack
if stack != "" {
blocks = append(blocks, stack)
}
return blocks, nil
}
func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format string, want []string, detectStackBoundaries bool) {
gotStr := fmt.Sprintf(format, arg)
got, err := parseBlocks(gotStr, detectStackBoundaries)
if err != nil {
t.Fatal(err)
}
if len(got) != len(want) {
t.Fatalf("test %d: fmt.Sprintf(%s, err) -> wrong number of blocks: got(%d) want(%d)\n got: %s\nwant: %s\ngotStr: %q",
n+1, format, len(got), len(want), prettyBlocks(got), prettyBlocks(want), gotStr)
}
for i := range got {
if strings.ContainsAny(want[i], "\n") {
// Match as stack
match, err := regexp.MatchString(want[i], got[i])
if err != nil {
t.Fatal(err)
}
if !match {
t.Fatalf("test %d: block %d: fmt.Sprintf(%q, err):\ngot:\n%q\nwant:\n%q\nall-got:\n%s\nall-want:\n%s\n",
n+1, i+1, format, got[i], want[i], prettyBlocks(got), prettyBlocks(want))
}
} else {
// Match as message
if got[i] != want[i] {
t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i])
}
}
}
}
type wrapper struct {
wrap func(err error) error
want []string
}
func prettyBlocks(blocks []string) string {
var out []string
for _, b := range blocks {
out = append(out, fmt.Sprintf("%v", b))
}
return " " + strings.Join(out, "\n ")
}
func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, list []wrapper, maxDepth int) {
if len(beforeWant) == 0 {
panic("beforeWant must not be empty")
}
for _, w := range list {
if len(w.want) == 0 {
panic("want must not be empty")
}
err := w.wrap(beforeErr)
// Copy required cause append(beforeWant, ..) modified beforeWant subtly.
beforeCopy := make([]string, len(beforeWant))
copy(beforeCopy, beforeWant)
beforeWant := beforeCopy
last := len(beforeWant) - 1
var want []string
// Merge two stacks behind each other.
if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") {
want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...)
} else {
want = append(beforeWant, w.want...)
}
testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false)
if maxDepth > 0 {
testGenericRecursive(t, err, want, list, maxDepth-1)
}
}
}

View File

@ -1,274 +0,0 @@
package errors
import (
"fmt"
"runtime"
"testing"
)
var initpc, _, _, _ = runtime.Caller(0)
func TestFrameLine(t *testing.T) {
var tests = []struct {
Frame
want int
}{{
Frame(initpc),
9,
}, {
func() Frame {
var pc, _, _, _ = runtime.Caller(0)
return Frame(pc)
}(),
20,
}, {
func() Frame {
var pc, _, _, _ = runtime.Caller(1)
return Frame(pc)
}(),
28,
}, {
Frame(0), // invalid PC
0,
}}
for _, tt := range tests {
got := tt.Frame.line()
want := tt.want
if want != got {
t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got)
}
}
}
type X struct{}
func (x X) val() Frame {
var pc, _, _, _ = runtime.Caller(0)
return Frame(pc)
}
func (x *X) ptr() Frame {
var pc, _, _, _ = runtime.Caller(0)
return Frame(pc)
}
func TestFrameFormat(t *testing.T) {
var tests = []struct {
Frame
format string
want string
}{{
Frame(initpc),
"%s",
"stack_test.go",
}, {
Frame(initpc),
"%+s",
"github.com/pkg/errors.init\n" +
"\t.+/github.com/pkg/errors/stack_test.go",
}, {
Frame(0),
"%s",
"unknown",
}, {
Frame(0),
"%+s",
"unknown",
}, {
Frame(initpc),
"%d",
"9",
}, {
Frame(0),
"%d",
"0",
}, {
Frame(initpc),
"%n",
"init",
}, {
func() Frame {
var x X
return x.ptr()
}(),
"%n",
`\(\*X\).ptr`,
}, {
func() Frame {
var x X
return x.val()
}(),
"%n",
"X.val",
}, {
Frame(0),
"%n",
"",
}, {
Frame(initpc),
"%v",
"stack_test.go:9",
}, {
Frame(initpc),
"%+v",
"github.com/pkg/errors.init\n" +
"\t.+/github.com/pkg/errors/stack_test.go:9",
}, {
Frame(0),
"%v",
"unknown:0",
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.Frame, tt.format, tt.want)
}
}
func TestFuncname(t *testing.T) {
tests := []struct {
name, want string
}{
{"", ""},
{"runtime.main", "main"},
{"github.com/pkg/errors.funcname", "funcname"},
{"funcname", "funcname"},
{"io.copyBuffer", "copyBuffer"},
{"main.(*R).Write", "(*R).Write"},
}
for _, tt := range tests {
got := funcname(tt.name)
want := tt.want
if got != want {
t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got)
}
}
}
func TestStackTrace(t *testing.T) {
tests := []struct {
err error
want []string
}{{
New("ooh"), []string{
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:154",
},
}, {
Wrap(New("ooh"), "ahh"), []string{
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:159", // this is the stack of Wrap, not New
},
}, {
Cause(Wrap(New("ooh"), "ahh")), []string{
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:164", // this is the stack of New
},
}, {
func() error { return New("ooh") }(), []string{
`github.com/pkg/errors.(func·009|TestStackTrace.func1)` +
"\n\t.+/github.com/pkg/errors/stack_test.go:169", // this is the stack of New
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:169", // this is the stack of New's caller
},
}, {
Cause(func() error {
return func() error {
return Errorf("hello %s", fmt.Sprintf("world"))
}()
}()), []string{
`github.com/pkg/errors.(func·010|TestStackTrace.func2.1)` +
"\n\t.+/github.com/pkg/errors/stack_test.go:178", // this is the stack of Errorf
`github.com/pkg/errors.(func·011|TestStackTrace.func2)` +
"\n\t.+/github.com/pkg/errors/stack_test.go:179", // this is the stack of Errorf's caller
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:180", // this is the stack of Errorf's caller's caller
},
}}
for i, tt := range tests {
x, ok := tt.err.(interface {
StackTrace() StackTrace
})
if !ok {
t.Errorf("expected %#v to implement StackTrace() StackTrace", tt.err)
continue
}
st := x.StackTrace()
for j, want := range tt.want {
testFormatRegexp(t, i, st[j], "%+v", want)
}
}
}
func stackTrace() StackTrace {
const depth = 8
var pcs [depth]uintptr
n := runtime.Callers(1, pcs[:])
var st stack = pcs[0:n]
return st.StackTrace()
}
func TestStackTraceFormat(t *testing.T) {
tests := []struct {
StackTrace
format string
want string
}{{
nil,
"%s",
`\[\]`,
}, {
nil,
"%v",
`\[\]`,
}, {
nil,
"%+v",
"",
}, {
nil,
"%#v",
`\[\]errors.Frame\(nil\)`,
}, {
make(StackTrace, 0),
"%s",
`\[\]`,
}, {
make(StackTrace, 0),
"%v",
`\[\]`,
}, {
make(StackTrace, 0),
"%+v",
"",
}, {
make(StackTrace, 0),
"%#v",
`\[\]errors.Frame{}`,
}, {
stackTrace()[:2],
"%s",
`\[stack_test.go stack_test.go\]`,
}, {
stackTrace()[:2],
"%v",
`\[stack_test.go:207 stack_test.go:254\]`,
}, {
stackTrace()[:2],
"%+v",
"\n" +
"github.com/pkg/errors.stackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:207\n" +
"github.com/pkg/errors.TestStackTraceFormat\n" +
"\t.+/github.com/pkg/errors/stack_test.go:258",
}, {
stackTrace()[:2],
"%#v",
`\[\]errors.Frame{stack_test.go:207, stack_test.go:266}`,
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.StackTrace, tt.format, tt.want)
}
}

2
vendor/github.com/sirupsen/logrus/.gitignore generated vendored Normal file
View File

@ -0,0 +1,2 @@
logrus
vendor

25
vendor/github.com/sirupsen/logrus/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,25 @@
language: go
go_import_path: github.com/sirupsen/logrus
git:
depth: 1
env:
- GO111MODULE=on
- GO111MODULE=off
go: [ 1.11.x, 1.12.x ]
os: [ linux, osx ]
matrix:
exclude:
- go: 1.12.x
env: GO111MODULE=off
- go: 1.11.x
os: osx
install:
- ./travis/install.sh
- if [[ "$GO111MODULE" == "on" ]]; then go mod download; fi
- if [[ "$GO111MODULE" == "off" ]]; then go get github.com/stretchr/testify/assert golang.org/x/sys/unix github.com/konsorten/go-windows-terminal-sequences; fi
script:
- ./travis/cross_build.sh
- export GOMAXPROCS=4
- export GORACE=halt_on_error=1
- go test -race -v ./...
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then go test -race -v -tags appengine ./... ; fi

View File

@ -1,3 +1,38 @@
# 1.4.2
* Fixes build break for plan9, nacl, solaris
# 1.4.1
This new release introduces:
* Enhance TextFormatter to not print caller information when they are empty (#944)
* Remove dependency on golang.org/x/crypto (#932, #943)
Fixes:
* Fix Entry.WithContext method to return a copy of the initial entry (#941)
# 1.4.0
This new release introduces:
* Add `DeferExitHandler`, similar to `RegisterExitHandler` but prepending the handler to the list of handlers (semantically like `defer`) (#848).
* Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter (#909, #911)
* Add `Entry.WithContext()` and `Entry.Context`, to set a context on entries to be used e.g. in hooks (#919).
Fixes:
* Fix wrong method calls `Logger.Print` and `Logger.Warningln` (#893).
* Update `Entry.Logf` to not do string formatting unless the log level is enabled (#903)
* Fix infinite recursion on unknown `Level.String()` (#907)
* Fix race condition in `getCaller` (#916).
# 1.3.0
This new release introduces:
* Log, Logf, Logln functions for Logger and Entry that take a Level
Fixes:
* Building prometheus node_exporter on AIX (#840)
* Race condition in TextFormatter (#468)
* Travis CI import path (#868)
* Remove coloured output on Windows (#862)
* Pointer to func as field in JSONFormatter (#870)
* Properly marshal Levels (#873)
# 1.2.0
This new release introduces:
* A new method `SetReportCaller` in the `Logger` to enable the file, line and calling function from which the trace has been issued

View File

@ -365,6 +365,7 @@ Third party logging formatters:
* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦.
* [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure.
You can define your formatter by implementing the `Formatter` interface,
requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a

View File

@ -51,9 +51,9 @@ func Exit(code int) {
os.Exit(code)
}
// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke
// all handlers. The handlers will also be invoked when any Fatal log entry is
// made.
// RegisterExitHandler appends a Logrus Exit handler to the list of handlers,
// call logrus.Exit to invoke all handlers. The handlers will also be invoked when
// any Fatal log entry is made.
//
// This method is useful when a caller wishes to use logrus to log a fatal
// message but also needs to gracefully shutdown. An example usecase could be
@ -62,3 +62,15 @@ func Exit(code int) {
func RegisterExitHandler(handler func()) {
handlers = append(handlers, handler)
}
// DeferExitHandler prepends a Logrus Exit handler to the list of handlers,
// call logrus.Exit to invoke all handlers. The handlers will also be invoked when
// any Fatal log entry is made.
//
// This method is useful when a caller wishes to use logrus to log a fatal
// message but also needs to gracefully shutdown. An example usecase could be
// closing database connections, or sending a alert that the application is
// closing.
func DeferExitHandler(handler func()) {
handlers = append([]func(){handler}, handlers...)
}

View File

@ -1,99 +0,0 @@
package logrus
import (
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
func TestRegister(t *testing.T) {
current := len(handlers)
RegisterExitHandler(func() {})
if len(handlers) != current+1 {
t.Fatalf("expected %d handlers, got %d", current+1, len(handlers))
}
}
func TestHandler(t *testing.T) {
testprog := testprogleader
testprog = append(testprog, getPackage()...)
testprog = append(testprog, testprogtrailer...)
tempDir, err := ioutil.TempDir("", "test_handler")
if err != nil {
log.Fatalf("can't create temp dir. %q", err)
}
defer os.RemoveAll(tempDir)
gofile := filepath.Join(tempDir, "gofile.go")
if err := ioutil.WriteFile(gofile, testprog, 0666); err != nil {
t.Fatalf("can't create go file. %q", err)
}
outfile := filepath.Join(tempDir, "outfile.out")
arg := time.Now().UTC().String()
err = exec.Command("go", "run", gofile, outfile, arg).Run()
if err == nil {
t.Fatalf("completed normally, should have failed")
}
data, err := ioutil.ReadFile(outfile)
if err != nil {
t.Fatalf("can't read output file %s. %q", outfile, err)
}
if string(data) != arg {
t.Fatalf("bad data. Expected %q, got %q", data, arg)
}
}
// getPackage returns the name of the current package, which makes running this
// test in a fork simpler
func getPackage() []byte {
pc, _, _, _ := runtime.Caller(0)
fullFuncName := runtime.FuncForPC(pc).Name()
idx := strings.LastIndex(fullFuncName, ".")
return []byte(fullFuncName[:idx]) // trim off function details
}
var testprogleader = []byte(`
// Test program for atexit, gets output file and data as arguments and writes
// data to output file in atexit handler.
package main
import (
"`)
var testprogtrailer = []byte(
`"
"flag"
"fmt"
"io/ioutil"
)
var outfile = ""
var data = ""
func handler() {
ioutil.WriteFile(outfile, []byte(data), 0666)
}
func badHandler() {
n := 0
fmt.Println(1/n)
}
func main() {
flag.Parse()
outfile = flag.Arg(0)
data = flag.Arg(1)
logrus.RegisterExitHandler(handler)
logrus.RegisterExitHandler(badHandler)
logrus.Fatal("Bye bye")
}
`)

View File

@ -2,6 +2,7 @@ package logrus
import (
"bytes"
"context"
"fmt"
"os"
"reflect"
@ -69,6 +70,9 @@ type Entry struct {
// When formatter is called in entry.log(), a Buffer may be set to entry
Buffer *bytes.Buffer
// Contains the context set by the user. Useful for hook processing etc.
Context context.Context
// err may contain a field formatting error
err string
}
@ -97,6 +101,11 @@ func (entry *Entry) WithError(err error) *Entry {
return entry.WithField(ErrorKey, err)
}
// Add a context to the Entry.
func (entry *Entry) WithContext(ctx context.Context) *Entry {
return &Entry{Logger: entry.Logger, Data: entry.Data, Time: entry.Time, err: entry.err, Context: ctx}
}
// Add a single field to the Entry.
func (entry *Entry) WithField(key string, value interface{}) *Entry {
return entry.WithFields(Fields{key: value})
@ -130,12 +139,12 @@ func (entry *Entry) WithFields(fields Fields) *Entry {
data[k] = v
}
}
return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr}
return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context}
}
// Overrides the time of the Entry.
func (entry *Entry) WithTime(t time.Time) *Entry {
return &Entry{Logger: entry.Logger, Data: entry.Data, Time: t, err: entry.err}
return &Entry{Logger: entry.Logger, Data: entry.Data, Time: t, err: entry.err, Context: entry.Context}
}
// getPackageName reduces a fully qualified function name to the package name
@ -156,20 +165,23 @@ func getPackageName(f string) string {
// getCaller retrieves the name of the first non-logrus calling function
func getCaller() *runtime.Frame {
// cache this package's fully-qualified name
callerInitOnce.Do(func() {
pcs := make([]uintptr, 2)
_ = runtime.Callers(0, pcs)
logrusPackage = getPackageName(runtime.FuncForPC(pcs[1]).Name())
// now that we have the cache, we can skip a minimum count of known-logrus functions
// XXX this is dubious, the number of frames may vary
minimumCallerDepth = knownLogrusFrames
})
// Restrict the lookback frames to avoid runaway lookups
pcs := make([]uintptr, maximumCallerDepth)
depth := runtime.Callers(minimumCallerDepth, pcs)
frames := runtime.CallersFrames(pcs[:depth])
// cache this package's fully-qualified name
callerInitOnce.Do(func() {
logrusPackage = getPackageName(runtime.FuncForPC(pcs[0]).Name())
// now that we have the cache, we can skip a minimum count of known-logrus functions
// XXX this is dubious, the number of frames may vary store an entry in a logger interface
minimumCallerDepth = knownLogrusFrames
})
for f, again := frames.Next(); again; f, again = frames.Next() {
pkg := getPackageName(f.Function)
@ -251,16 +263,18 @@ func (entry *Entry) write() {
}
}
func (entry *Entry) Trace(args ...interface{}) {
if entry.Logger.IsLevelEnabled(TraceLevel) {
entry.log(TraceLevel, fmt.Sprint(args...))
func (entry *Entry) Log(level Level, args ...interface{}) {
if entry.Logger.IsLevelEnabled(level) {
entry.log(level, fmt.Sprint(args...))
}
}
func (entry *Entry) Trace(args ...interface{}) {
entry.Log(TraceLevel, args...)
}
func (entry *Entry) Debug(args ...interface{}) {
if entry.Logger.IsLevelEnabled(DebugLevel) {
entry.log(DebugLevel, fmt.Sprint(args...))
}
entry.Log(DebugLevel, args...)
}
func (entry *Entry) Print(args ...interface{}) {
@ -268,15 +282,11 @@ func (entry *Entry) Print(args ...interface{}) {
}
func (entry *Entry) Info(args ...interface{}) {
if entry.Logger.IsLevelEnabled(InfoLevel) {
entry.log(InfoLevel, fmt.Sprint(args...))
}
entry.Log(InfoLevel, args...)
}
func (entry *Entry) Warn(args ...interface{}) {
if entry.Logger.IsLevelEnabled(WarnLevel) {
entry.log(WarnLevel, fmt.Sprint(args...))
}
entry.Log(WarnLevel, args...)
}
func (entry *Entry) Warning(args ...interface{}) {
@ -284,43 +294,37 @@ func (entry *Entry) Warning(args ...interface{}) {
}
func (entry *Entry) Error(args ...interface{}) {
if entry.Logger.IsLevelEnabled(ErrorLevel) {
entry.log(ErrorLevel, fmt.Sprint(args...))
}
entry.Log(ErrorLevel, args...)
}
func (entry *Entry) Fatal(args ...interface{}) {
if entry.Logger.IsLevelEnabled(FatalLevel) {
entry.log(FatalLevel, fmt.Sprint(args...))
}
entry.Log(FatalLevel, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panic(args ...interface{}) {
if entry.Logger.IsLevelEnabled(PanicLevel) {
entry.log(PanicLevel, fmt.Sprint(args...))
}
entry.Log(PanicLevel, args...)
panic(fmt.Sprint(args...))
}
// Entry Printf family functions
func (entry *Entry) Tracef(format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(TraceLevel) {
entry.Trace(fmt.Sprintf(format, args...))
func (entry *Entry) Logf(level Level, format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(level) {
entry.Log(level, fmt.Sprintf(format, args...))
}
}
func (entry *Entry) Tracef(format string, args ...interface{}) {
entry.Logf(TraceLevel, format, args...)
}
func (entry *Entry) Debugf(format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(DebugLevel) {
entry.Debug(fmt.Sprintf(format, args...))
}
entry.Logf(DebugLevel, format, args...)
}
func (entry *Entry) Infof(format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(InfoLevel) {
entry.Info(fmt.Sprintf(format, args...))
}
entry.Logf(InfoLevel, format, args...)
}
func (entry *Entry) Printf(format string, args ...interface{}) {
@ -328,9 +332,7 @@ func (entry *Entry) Printf(format string, args ...interface{}) {
}
func (entry *Entry) Warnf(format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(WarnLevel) {
entry.Warn(fmt.Sprintf(format, args...))
}
entry.Logf(WarnLevel, format, args...)
}
func (entry *Entry) Warningf(format string, args ...interface{}) {
@ -338,42 +340,36 @@ func (entry *Entry) Warningf(format string, args ...interface{}) {
}
func (entry *Entry) Errorf(format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(ErrorLevel) {
entry.Error(fmt.Sprintf(format, args...))
}
entry.Logf(ErrorLevel, format, args...)
}
func (entry *Entry) Fatalf(format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(FatalLevel) {
entry.Fatal(fmt.Sprintf(format, args...))
}
entry.Logf(FatalLevel, format, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panicf(format string, args ...interface{}) {
if entry.Logger.IsLevelEnabled(PanicLevel) {
entry.Panic(fmt.Sprintf(format, args...))
}
entry.Logf(PanicLevel, format, args...)
}
// Entry Println family functions
func (entry *Entry) Traceln(args ...interface{}) {
if entry.Logger.IsLevelEnabled(TraceLevel) {
entry.Trace(entry.sprintlnn(args...))
func (entry *Entry) Logln(level Level, args ...interface{}) {
if entry.Logger.IsLevelEnabled(level) {
entry.Log(level, entry.sprintlnn(args...))
}
}
func (entry *Entry) Traceln(args ...interface{}) {
entry.Logln(TraceLevel, args...)
}
func (entry *Entry) Debugln(args ...interface{}) {
if entry.Logger.IsLevelEnabled(DebugLevel) {
entry.Debug(entry.sprintlnn(args...))
}
entry.Logln(DebugLevel, args...)
}
func (entry *Entry) Infoln(args ...interface{}) {
if entry.Logger.IsLevelEnabled(InfoLevel) {
entry.Info(entry.sprintlnn(args...))
}
entry.Logln(InfoLevel, args...)
}
func (entry *Entry) Println(args ...interface{}) {
@ -381,9 +377,7 @@ func (entry *Entry) Println(args ...interface{}) {
}
func (entry *Entry) Warnln(args ...interface{}) {
if entry.Logger.IsLevelEnabled(WarnLevel) {
entry.Warn(entry.sprintlnn(args...))
}
entry.Logln(WarnLevel, args...)
}
func (entry *Entry) Warningln(args ...interface{}) {
@ -391,22 +385,16 @@ func (entry *Entry) Warningln(args ...interface{}) {
}
func (entry *Entry) Errorln(args ...interface{}) {
if entry.Logger.IsLevelEnabled(ErrorLevel) {
entry.Error(entry.sprintlnn(args...))
}
entry.Logln(ErrorLevel, args...)
}
func (entry *Entry) Fatalln(args ...interface{}) {
if entry.Logger.IsLevelEnabled(FatalLevel) {
entry.Fatal(entry.sprintlnn(args...))
}
entry.Logln(FatalLevel, args...)
entry.Logger.Exit(1)
}
func (entry *Entry) Panicln(args ...interface{}) {
if entry.Logger.IsLevelEnabled(PanicLevel) {
entry.Panic(entry.sprintlnn(args...))
}
entry.Logln(PanicLevel, args...)
}
// Sprintlnn => Sprint no newline. This is to get the behavior of how

View File

@ -1,141 +0,0 @@
package logrus
import (
"bytes"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestEntryWithError(t *testing.T) {
assert := assert.New(t)
defer func() {
ErrorKey = "error"
}()
err := fmt.Errorf("kaboom at layer %d", 4711)
assert.Equal(err, WithError(err).Data["error"])
logger := New()
logger.Out = &bytes.Buffer{}
entry := NewEntry(logger)
assert.Equal(err, entry.WithError(err).Data["error"])
ErrorKey = "err"
assert.Equal(err, entry.WithError(err).Data["err"])
}
func TestEntryPanicln(t *testing.T) {
errBoom := fmt.Errorf("boom time")
defer func() {
p := recover()
assert.NotNil(t, p)
switch pVal := p.(type) {
case *Entry:
assert.Equal(t, "kaboom", pVal.Message)
assert.Equal(t, errBoom, pVal.Data["err"])
default:
t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
}
}()
logger := New()
logger.Out = &bytes.Buffer{}
entry := NewEntry(logger)
entry.WithField("err", errBoom).Panicln("kaboom")
}
func TestEntryPanicf(t *testing.T) {
errBoom := fmt.Errorf("boom again")
defer func() {
p := recover()
assert.NotNil(t, p)
switch pVal := p.(type) {
case *Entry:
assert.Equal(t, "kaboom true", pVal.Message)
assert.Equal(t, errBoom, pVal.Data["err"])
default:
t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
}
}()
logger := New()
logger.Out = &bytes.Buffer{}
entry := NewEntry(logger)
entry.WithField("err", errBoom).Panicf("kaboom %v", true)
}
const (
badMessage = "this is going to panic"
panicMessage = "this is broken"
)
type panickyHook struct{}
func (p *panickyHook) Levels() []Level {
return []Level{InfoLevel}
}
func (p *panickyHook) Fire(entry *Entry) error {
if entry.Message == badMessage {
panic(panicMessage)
}
return nil
}
func TestEntryHooksPanic(t *testing.T) {
logger := New()
logger.Out = &bytes.Buffer{}
logger.Level = InfoLevel
logger.Hooks.Add(&panickyHook{})
defer func() {
p := recover()
assert.NotNil(t, p)
assert.Equal(t, panicMessage, p)
entry := NewEntry(logger)
entry.Info("another message")
}()
entry := NewEntry(logger)
entry.Info(badMessage)
}
func TestEntryWithIncorrectField(t *testing.T) {
assert := assert.New(t)
fn := func() {}
e := Entry{}
eWithFunc := e.WithFields(Fields{"func": fn})
eWithFuncPtr := e.WithFields(Fields{"funcPtr": &fn})
assert.Equal(eWithFunc.err, `can not add field "func"`)
assert.Equal(eWithFuncPtr.err, `can not add field "funcPtr"`)
eWithFunc = eWithFunc.WithField("not_a_func", "it is a string")
eWithFuncPtr = eWithFuncPtr.WithField("not_a_func", "it is a string")
assert.Equal(eWithFunc.err, `can not add field "func"`)
assert.Equal(eWithFuncPtr.err, `can not add field "funcPtr"`)
eWithFunc = eWithFunc.WithTime(time.Now())
eWithFuncPtr = eWithFuncPtr.WithTime(time.Now())
assert.Equal(eWithFunc.err, `can not add field "func"`)
assert.Equal(eWithFuncPtr.err, `can not add field "funcPtr"`)
}

Some files were not shown because too many files have changed in this diff Show More