sync: resync vendor folder
This commit is contained in:
parent
2cb50078b1
commit
8f71532ed8
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,4 @@
|
||||||
|
language: go
|
||||||
|
|
||||||
|
go:
|
||||||
|
- 1.x
|
||||||
|
|
@ -1,5 +1,8 @@
|
||||||
Change history of swagger
|
Change history of swagger
|
||||||
=
|
=
|
||||||
|
2017-01-30
|
||||||
|
- moved from go-restful/swagger to go-restful-swagger12
|
||||||
|
|
||||||
2015-10-16
|
2015-10-16
|
||||||
- add type override mechanism for swagger models (MR 254, nathanejohnson)
|
- add type override mechanism for swagger models (MR 254, nathanejohnson)
|
||||||
- replace uses of wildcard in generated apidocs (issue 251)
|
- replace uses of wildcard in generated apidocs (issue 251)
|
||||||
|
|
@ -0,0 +1,22 @@
|
||||||
|
Copyright (c) 2017 Ernest Micklei
|
||||||
|
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
@ -1,3 +1,8 @@
|
||||||
|
# go-restful-swagger12
|
||||||
|
|
||||||
|
[](https://travis-ci.org/emicklei/go-restful-swagger12)
|
||||||
|
[](https://godoc.org/github.com/emicklei/go-restful-swagger12)
|
||||||
|
|
||||||
How to use Swagger UI with go-restful
|
How to use Swagger UI with go-restful
|
||||||
=
|
=
|
||||||
|
|
||||||
|
|
@ -74,3 +79,5 @@ Notes
|
||||||
--
|
--
|
||||||
- The Nickname of an Operation is automatically set by finding the name of the function. You can override it using RouteBuilder.Operation(..)
|
- The Nickname of an Operation is automatically set by finding the name of the function. You can override it using RouteBuilder.Operation(..)
|
||||||
- The WebServices field of swagger.Config can be used to control which service you want to expose and document ; you can have multiple configs and therefore multiple endpoints.
|
- The WebServices field of swagger.Config can be used to control which service you want to expose and document ; you can have multiple configs and therefore multiple endpoints.
|
||||||
|
|
||||||
|
© 2017, ernestmicklei.com. MIT License. Contributions welcome.
|
||||||
|
|
@ -226,6 +226,9 @@ func (sws SwaggerService) composeDeclaration(ws *restful.WebService, pathPrefix
|
||||||
pathToRoutes := newOrderedRouteMap()
|
pathToRoutes := newOrderedRouteMap()
|
||||||
for _, other := range ws.Routes() {
|
for _, other := range ws.Routes() {
|
||||||
if strings.HasPrefix(other.Path, pathPrefix) {
|
if strings.HasPrefix(other.Path, pathPrefix) {
|
||||||
|
if len(pathPrefix) > 1 && len(other.Path) > len(pathPrefix) && other.Path[len(pathPrefix)] != '/' {
|
||||||
|
continue
|
||||||
|
}
|
||||||
pathToRoutes.Add(other.Path, other)
|
pathToRoutes.Add(other.Path, other)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -290,14 +293,13 @@ func composeResponseMessages(route restful.Route, decl *ApiDeclaration, config *
|
||||||
if each.Model != nil {
|
if each.Model != nil {
|
||||||
st := reflect.TypeOf(each.Model)
|
st := reflect.TypeOf(each.Model)
|
||||||
isCollection, st := detectCollectionType(st)
|
isCollection, st := detectCollectionType(st)
|
||||||
|
// collection cannot be in responsemodel
|
||||||
|
if !isCollection {
|
||||||
modelName := modelBuilder{}.keyFrom(st)
|
modelName := modelBuilder{}.keyFrom(st)
|
||||||
if isCollection {
|
|
||||||
modelName = "array[" + modelName + "]"
|
|
||||||
}
|
|
||||||
modelBuilder{Models: &decl.Models, Config: config}.addModel(st, "")
|
modelBuilder{Models: &decl.Models, Config: config}.addModel(st, "")
|
||||||
// reference the model
|
|
||||||
message.ResponseModel = modelName
|
message.ResponseModel = modelName
|
||||||
}
|
}
|
||||||
|
}
|
||||||
messages = append(messages, message)
|
messages = append(messages, message)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
|
|
@ -331,12 +333,13 @@ func detectCollectionType(st reflect.Type) (bool, reflect.Type) {
|
||||||
|
|
||||||
// addModelFromSample creates and adds (or overwrites) a Model from a sample resource
|
// addModelFromSample creates and adds (or overwrites) a Model from a sample resource
|
||||||
func (sws SwaggerService) addModelFromSampleTo(operation *Operation, isResponse bool, sample interface{}, models *ModelList) {
|
func (sws SwaggerService) addModelFromSampleTo(operation *Operation, isResponse bool, sample interface{}, models *ModelList) {
|
||||||
|
mb := modelBuilder{Models: models, Config: &sws.config}
|
||||||
if isResponse {
|
if isResponse {
|
||||||
type_, items := asDataType(sample, &sws.config)
|
sampleType, items := asDataType(sample, &sws.config)
|
||||||
operation.Type = type_
|
operation.Type = sampleType
|
||||||
operation.Items = items
|
operation.Items = items
|
||||||
}
|
}
|
||||||
modelBuilder{Models: models, Config: &sws.config}.addModelFrom(sample)
|
mb.addModelFrom(sample)
|
||||||
}
|
}
|
||||||
|
|
||||||
func asSwaggerParameter(param restful.ParameterData) Parameter {
|
func asSwaggerParameter(param restful.ParameterData) Parameter {
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
language: go
|
||||||
|
|
||||||
|
go:
|
||||||
|
- 1.x
|
||||||
|
|
||||||
|
script: go test -v
|
||||||
|
|
@ -1,39 +1,71 @@
|
||||||
Change history of go-restful
|
Change history of go-restful
|
||||||
=
|
=
|
||||||
|
2017-02-16
|
||||||
|
- solved issue #304, make operation names unique
|
||||||
|
|
||||||
|
2017-01-30
|
||||||
|
|
||||||
|
[IMPORTANT] For swagger users, change your import statement to:
|
||||||
|
swagger "github.com/emicklei/go-restful-swagger12"
|
||||||
|
|
||||||
|
- moved swagger 1.2 code to go-restful-swagger12
|
||||||
|
- created TAG 2.0.0
|
||||||
|
|
||||||
|
2017-01-27
|
||||||
|
|
||||||
|
- remove defer request body close
|
||||||
|
- expose Dispatch for testing filters and Routefunctions
|
||||||
|
- swagger response model cannot be array
|
||||||
|
- created TAG 1.0.0
|
||||||
|
|
||||||
|
2016-12-22
|
||||||
|
|
||||||
|
- (API change) Remove code related to caching request content. Removes SetCacheReadEntity(doCache bool)
|
||||||
|
|
||||||
2016-11-26
|
2016-11-26
|
||||||
|
|
||||||
- Default change! now use CurlyRouter (was RouterJSR311)
|
- Default change! now use CurlyRouter (was RouterJSR311)
|
||||||
- Default change! no more caching of request content
|
- Default change! no more caching of request content
|
||||||
- Default change! do not recover from panics
|
- Default change! do not recover from panics
|
||||||
|
|
||||||
2016-09-22
|
2016-09-22
|
||||||
|
|
||||||
- fix the DefaultRequestContentType feature
|
- fix the DefaultRequestContentType feature
|
||||||
|
|
||||||
2016-02-14
|
2016-02-14
|
||||||
|
|
||||||
- take the qualify factor of the Accept header mediatype into account when deciding the contentype of the response
|
- take the qualify factor of the Accept header mediatype into account when deciding the contentype of the response
|
||||||
- add constructors for custom entity accessors for xml and json
|
- add constructors for custom entity accessors for xml and json
|
||||||
|
|
||||||
2015-09-27
|
2015-09-27
|
||||||
|
|
||||||
- rename new WriteStatusAnd... to WriteHeaderAnd... for consistency
|
- rename new WriteStatusAnd... to WriteHeaderAnd... for consistency
|
||||||
|
|
||||||
2015-09-25
|
2015-09-25
|
||||||
|
|
||||||
- fixed problem with changing Header after WriteHeader (issue 235)
|
- fixed problem with changing Header after WriteHeader (issue 235)
|
||||||
|
|
||||||
2015-09-14
|
2015-09-14
|
||||||
|
|
||||||
- changed behavior of WriteHeader (immediate write) and WriteEntity (no status write)
|
- changed behavior of WriteHeader (immediate write) and WriteEntity (no status write)
|
||||||
- added support for custom EntityReaderWriters.
|
- added support for custom EntityReaderWriters.
|
||||||
|
|
||||||
2015-08-06
|
2015-08-06
|
||||||
|
|
||||||
- add support for reading entities from compressed request content
|
- add support for reading entities from compressed request content
|
||||||
- use sync.Pool for compressors of http response and request body
|
- use sync.Pool for compressors of http response and request body
|
||||||
- add Description to Parameter for documentation in Swagger UI
|
- add Description to Parameter for documentation in Swagger UI
|
||||||
|
|
||||||
2015-03-20
|
2015-03-20
|
||||||
|
|
||||||
- add configurable logging
|
- add configurable logging
|
||||||
|
|
||||||
2015-03-18
|
2015-03-18
|
||||||
|
|
||||||
- if not specified, the Operation is derived from the Route function
|
- if not specified, the Operation is derived from the Route function
|
||||||
|
|
||||||
2015-03-17
|
2015-03-17
|
||||||
|
|
||||||
- expose Parameter creation functions
|
- expose Parameter creation functions
|
||||||
- make trace logger an interface
|
- make trace logger an interface
|
||||||
- fix OPTIONSFilter
|
- fix OPTIONSFilter
|
||||||
|
|
@ -42,21 +74,26 @@ Change history of go-restful
|
||||||
- add Notes to Route
|
- add Notes to Route
|
||||||
|
|
||||||
2014-11-27
|
2014-11-27
|
||||||
|
|
||||||
- (api add) PrettyPrint per response. (as proposed in #167)
|
- (api add) PrettyPrint per response. (as proposed in #167)
|
||||||
|
|
||||||
2014-11-12
|
2014-11-12
|
||||||
|
|
||||||
- (api add) ApiVersion(.) for documentation in Swagger UI
|
- (api add) ApiVersion(.) for documentation in Swagger UI
|
||||||
|
|
||||||
2014-11-10
|
2014-11-10
|
||||||
|
|
||||||
- (api change) struct fields tagged with "description" show up in Swagger UI
|
- (api change) struct fields tagged with "description" show up in Swagger UI
|
||||||
|
|
||||||
2014-10-31
|
2014-10-31
|
||||||
|
|
||||||
- (api change) ReturnsError -> Returns
|
- (api change) ReturnsError -> Returns
|
||||||
- (api add) RouteBuilder.Do(aBuilder) for DRY use of RouteBuilder
|
- (api add) RouteBuilder.Do(aBuilder) for DRY use of RouteBuilder
|
||||||
- fix swagger nested structs
|
- fix swagger nested structs
|
||||||
- sort Swagger response messages by code
|
- sort Swagger response messages by code
|
||||||
|
|
||||||
2014-10-23
|
2014-10-23
|
||||||
|
|
||||||
- (api add) ReturnsError allows you to document Http codes in swagger
|
- (api add) ReturnsError allows you to document Http codes in swagger
|
||||||
- fixed problem with greedy CurlyRouter
|
- fixed problem with greedy CurlyRouter
|
||||||
- (api add) Access-Control-Max-Age in CORS
|
- (api add) Access-Control-Max-Age in CORS
|
||||||
|
|
@ -70,102 +107,117 @@ Change history of go-restful
|
||||||
- (api add) ParameterNamed for detailed documentation
|
- (api add) ParameterNamed for detailed documentation
|
||||||
|
|
||||||
2014-04-16
|
2014-04-16
|
||||||
|
|
||||||
- (api add) expose constructor of Request for testing.
|
- (api add) expose constructor of Request for testing.
|
||||||
|
|
||||||
2014-06-27
|
2014-06-27
|
||||||
|
|
||||||
- (api add) ParameterNamed gives access to a Parameter definition and its data (for further specification).
|
- (api add) ParameterNamed gives access to a Parameter definition and its data (for further specification).
|
||||||
- (api add) SetCacheReadEntity allow scontrol over whether or not the request body is being cached (default true for compatibility reasons).
|
- (api add) SetCacheReadEntity allow scontrol over whether or not the request body is being cached (default true for compatibility reasons).
|
||||||
|
|
||||||
2014-07-03
|
2014-07-03
|
||||||
|
|
||||||
- (api add) CORS can be configured with a list of allowed domains
|
- (api add) CORS can be configured with a list of allowed domains
|
||||||
|
|
||||||
2014-03-12
|
2014-03-12
|
||||||
|
|
||||||
- (api add) Route path parameters can use wildcard or regular expressions. (requires CurlyRouter)
|
- (api add) Route path parameters can use wildcard or regular expressions. (requires CurlyRouter)
|
||||||
|
|
||||||
2014-02-26
|
2014-02-26
|
||||||
|
|
||||||
- (api add) Request now provides information about the matched Route, see method SelectedRoutePath
|
- (api add) Request now provides information about the matched Route, see method SelectedRoutePath
|
||||||
|
|
||||||
2014-02-17
|
2014-02-17
|
||||||
|
|
||||||
- (api change) renamed parameter constants (go-lint checks)
|
- (api change) renamed parameter constants (go-lint checks)
|
||||||
|
|
||||||
2014-01-10
|
2014-01-10
|
||||||
- (api add) support for CloseNotify, see http://golang.org/pkg/net/http/#CloseNotifier
|
|
||||||
|
- (api add) support for CloseNotify, see http://golang.org/pkg/net/http/#CloseNotifier
|
||||||
|
|
||||||
2014-01-07
|
2014-01-07
|
||||||
- (api change) Write* methods in Response now return the error or nil.
|
|
||||||
- added example of serving HTML from a Go template.
|
- (api change) Write* methods in Response now return the error or nil.
|
||||||
- fixed comparing Allowed headers in CORS (is now case-insensitive)
|
- added example of serving HTML from a Go template.
|
||||||
|
- fixed comparing Allowed headers in CORS (is now case-insensitive)
|
||||||
|
|
||||||
2013-11-13
|
2013-11-13
|
||||||
- (api add) Response knows how many bytes are written to the response body.
|
|
||||||
|
- (api add) Response knows how many bytes are written to the response body.
|
||||||
|
|
||||||
2013-10-29
|
2013-10-29
|
||||||
- (api add) RecoverHandler(handler RecoverHandleFunction) to change how panic recovery is handled. Default behavior is to log and return a stacktrace. This may be a security issue as it exposes sourcecode information.
|
|
||||||
|
- (api add) RecoverHandler(handler RecoverHandleFunction) to change how panic recovery is handled. Default behavior is to log and return a stacktrace. This may be a security issue as it exposes sourcecode information.
|
||||||
|
|
||||||
2013-10-04
|
2013-10-04
|
||||||
- (api add) Response knows what HTTP status has been written
|
|
||||||
- (api add) Request can have attributes (map of string->interface, also called request-scoped variables
|
- (api add) Response knows what HTTP status has been written
|
||||||
|
- (api add) Request can have attributes (map of string->interface, also called request-scoped variables
|
||||||
|
|
||||||
2013-09-12
|
2013-09-12
|
||||||
- (api change) Router interface simplified
|
|
||||||
- Implemented CurlyRouter, a Router that does not use|allow regular expressions in paths
|
- (api change) Router interface simplified
|
||||||
|
- Implemented CurlyRouter, a Router that does not use|allow regular expressions in paths
|
||||||
|
|
||||||
2013-08-05
|
2013-08-05
|
||||||
- add OPTIONS support
|
- add OPTIONS support
|
||||||
- add CORS support
|
- add CORS support
|
||||||
|
|
||||||
2013-08-27
|
2013-08-27
|
||||||
- fixed some reported issues (see github)
|
|
||||||
- (api change) deprecated use of WriteError; use WriteErrorString instead
|
- fixed some reported issues (see github)
|
||||||
|
- (api change) deprecated use of WriteError; use WriteErrorString instead
|
||||||
|
|
||||||
2014-04-15
|
2014-04-15
|
||||||
- (fix) v1.0.1 tag: fix Issue 111: WriteErrorString
|
|
||||||
|
- (fix) v1.0.1 tag: fix Issue 111: WriteErrorString
|
||||||
|
|
||||||
2013-08-08
|
2013-08-08
|
||||||
- (api add) Added implementation Container: a WebServices collection with its own http.ServeMux allowing multiple endpoints per program. Existing uses of go-restful will register their services to the DefaultContainer.
|
|
||||||
- (api add) the swagger package has be extended to have a UI per container.
|
- (api add) Added implementation Container: a WebServices collection with its own http.ServeMux allowing multiple endpoints per program. Existing uses of go-restful will register their services to the DefaultContainer.
|
||||||
- if panic is detected then a small stack trace is printed (thanks to runner-mei)
|
- (api add) the swagger package has be extended to have a UI per container.
|
||||||
- (api add) WriteErrorString to Response
|
- if panic is detected then a small stack trace is printed (thanks to runner-mei)
|
||||||
|
- (api add) WriteErrorString to Response
|
||||||
|
|
||||||
Important API changes:
|
Important API changes:
|
||||||
|
|
||||||
- (api remove) package variable DoNotRecover no longer works ; use restful.DefaultContainer.DoNotRecover(true) instead.
|
- (api remove) package variable DoNotRecover no longer works ; use restful.DefaultContainer.DoNotRecover(true) instead.
|
||||||
- (api remove) package variable EnableContentEncoding no longer works ; use restful.DefaultContainer.EnableContentEncoding(true) instead.
|
- (api remove) package variable EnableContentEncoding no longer works ; use restful.DefaultContainer.EnableContentEncoding(true) instead.
|
||||||
|
|
||||||
|
|
||||||
2013-07-06
|
2013-07-06
|
||||||
|
|
||||||
- (api add) Added support for response encoding (gzip and deflate(zlib)). This feature is disabled on default (for backwards compatibility). Use restful.EnableContentEncoding = true in your initialization to enable this feature.
|
- (api add) Added support for response encoding (gzip and deflate(zlib)). This feature is disabled on default (for backwards compatibility). Use restful.EnableContentEncoding = true in your initialization to enable this feature.
|
||||||
|
|
||||||
2013-06-19
|
2013-06-19
|
||||||
|
|
||||||
- (improve) DoNotRecover option, moved request body closer, improved ReadEntity
|
- (improve) DoNotRecover option, moved request body closer, improved ReadEntity
|
||||||
|
|
||||||
2013-06-03
|
2013-06-03
|
||||||
|
|
||||||
- (api change) removed Dispatcher interface, hide PathExpression
|
- (api change) removed Dispatcher interface, hide PathExpression
|
||||||
- changed receiver names of type functions to be more idiomatic Go
|
- changed receiver names of type functions to be more idiomatic Go
|
||||||
|
|
||||||
2013-06-02
|
2013-06-02
|
||||||
|
|
||||||
- (optimize) Cache the RegExp compilation of Paths.
|
- (optimize) Cache the RegExp compilation of Paths.
|
||||||
|
|
||||||
2013-05-22
|
2013-05-22
|
||||||
|
|
||||||
- (api add) Added support for request/response filter functions
|
- (api add) Added support for request/response filter functions
|
||||||
|
|
||||||
2013-05-18
|
2013-05-18
|
||||||
|
|
||||||
|
|
||||||
- (api add) Added feature to change the default Http Request Dispatch function (travis cline)
|
- (api add) Added feature to change the default Http Request Dispatch function (travis cline)
|
||||||
- (api change) Moved Swagger Webservice to swagger package (see example restful-user)
|
- (api change) Moved Swagger Webservice to swagger package (see example restful-user)
|
||||||
|
|
||||||
[2012-11-14 .. 2013-05-18>
|
[2012-11-14 .. 2013-05-18>
|
||||||
|
|
||||||
- See https://github.com/emicklei/go-restful/commits
|
- See https://github.com/emicklei/go-restful/commits
|
||||||
|
|
||||||
2012-11-14
|
2012-11-14
|
||||||
|
|
||||||
- Initial commit
|
- Initial commit
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,7 @@
|
||||||
|
all: test
|
||||||
|
|
||||||
|
test:
|
||||||
|
go test -v .
|
||||||
|
|
||||||
|
ex:
|
||||||
|
cd examples && ls *.go | xargs go build -o /tmp/ignore
|
||||||
|
|
@ -1,8 +1,13 @@
|
||||||
go-restful
|
go-restful
|
||||||
==========
|
==========
|
||||||
|
|
||||||
package for building REST-style Web Services using Google Go
|
package for building REST-style Web Services using Google Go
|
||||||
|
|
||||||
|
[](https://travis-ci.org/emicklei/go-restful)
|
||||||
|
[](https://goreportcard.com/report/github.com/emicklei/go-restful)
|
||||||
|
[](https://godoc.org/github.com/emicklei/go-restful)
|
||||||
|
|
||||||
|
- [Code examples](https://github.com/emicklei/go-restful/tree/master/examples)
|
||||||
|
|
||||||
REST asks developers to use HTTP methods explicitly and in a way that's consistent with the protocol definition. This basic REST design principle establishes a one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods. According to this mapping:
|
REST asks developers to use HTTP methods explicitly and in a way that's consistent with the protocol definition. This basic REST design principle establishes a one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods. According to this mapping:
|
||||||
|
|
||||||
- GET = Retrieve a representation of a resource
|
- GET = Retrieve a representation of a resource
|
||||||
|
|
@ -40,35 +45,30 @@ func (u UserResource) findUser(request *restful.Request, response *restful.Respo
|
||||||
|
|
||||||
- Routes for request → function mapping with path parameter (e.g. {id}) support
|
- Routes for request → function mapping with path parameter (e.g. {id}) support
|
||||||
- Configurable router:
|
- Configurable router:
|
||||||
- Routing algorithm after [JSR311](http://jsr311.java.net/nonav/releases/1.1/spec/spec.html) that is implemented using (but does **not** accept) regular expressions (See RouterJSR311 which is used by default)
|
- (default) Fast routing algorithm that allows static elements, regular expressions and dynamic parameters in the URL path (e.g. /meetings/{id} or /static/{subpath:*}
|
||||||
- Fast routing algorithm that allows static elements, regular expressions and dynamic parameters in the URL path (e.g. /meetings/{id} or /static/{subpath:*}, See CurlyRouter)
|
- Routing algorithm after [JSR311](http://jsr311.java.net/nonav/releases/1.1/spec/spec.html) that is implemented using (but does **not** accept) regular expressions
|
||||||
- Request API for reading structs from JSON/XML and accesing parameters (path,query,header)
|
- Request API for reading structs from JSON/XML and accesing parameters (path,query,header)
|
||||||
- Response API for writing structs to JSON/XML and setting headers
|
- Response API for writing structs to JSON/XML and setting headers
|
||||||
|
- Customizable encoding using EntityReaderWriter registration
|
||||||
- Filters for intercepting the request → response flow on Service or Route level
|
- Filters for intercepting the request → response flow on Service or Route level
|
||||||
- Request-scoped variables using attributes
|
- Request-scoped variables using attributes
|
||||||
- Containers for WebServices on different HTTP endpoints
|
- Containers for WebServices on different HTTP endpoints
|
||||||
- Content encoding (gzip,deflate) of request and response payloads
|
- Content encoding (gzip,deflate) of request and response payloads
|
||||||
- Automatic responses on OPTIONS (using a filter)
|
- Automatic responses on OPTIONS (using a filter)
|
||||||
- Automatic CORS request handling (using a filter)
|
- Automatic CORS request handling (using a filter)
|
||||||
- API declaration for Swagger UI (see swagger package)
|
- API declaration for Swagger UI (see [go-restful-swagger12](https://github.com/emicklei/go-restful-swagger12),[go-restful-openapi](https://github.com/emicklei/go-restful-openapi))
|
||||||
- Panic recovery to produce HTTP 500, customizable using RecoverHandler(...)
|
- Panic recovery to produce HTTP 500, customizable using RecoverHandler(...)
|
||||||
- Route errors produce HTTP 404/405/406/415 errors, customizable using ServiceErrorHandler(...)
|
- Route errors produce HTTP 404/405/406/415 errors, customizable using ServiceErrorHandler(...)
|
||||||
- Configurable (trace) logging
|
- Configurable (trace) logging
|
||||||
- Customizable encoding using EntityReaderWriter registration
|
|
||||||
- Customizable gzip/deflate readers and writers using CompressorProvider registration
|
- Customizable gzip/deflate readers and writers using CompressorProvider registration
|
||||||
|
|
||||||
### Resources
|
### Resources
|
||||||
|
|
||||||
- [Documentation on godoc.org](http://godoc.org/github.com/emicklei/go-restful)
|
|
||||||
- [Code examples](https://github.com/emicklei/go-restful/tree/master/examples)
|
|
||||||
- [Example posted on blog](http://ernestmicklei.com/2012/11/go-restful-first-working-example/)
|
- [Example posted on blog](http://ernestmicklei.com/2012/11/go-restful-first-working-example/)
|
||||||
- [Design explained on blog](http://ernestmicklei.com/2012/11/go-restful-api-design/)
|
- [Design explained on blog](http://ernestmicklei.com/2012/11/go-restful-api-design/)
|
||||||
- [sourcegraph](https://sourcegraph.com/github.com/emicklei/go-restful)
|
- [sourcegraph](https://sourcegraph.com/github.com/emicklei/go-restful)
|
||||||
- [gopkg.in](https://gopkg.in/emicklei/go-restful.v1)
|
|
||||||
- [showcase: Mora - MongoDB REST Api server](https://github.com/emicklei/mora)
|
- [showcase: Mora - MongoDB REST Api server](https://github.com/emicklei/mora)
|
||||||
|
|
||||||
[](https://drone.io/github.com/emicklei/go-restful/latest)
|
|
||||||
|
|
||||||
(c) 2012 - 2015, http://ernestmicklei.com. MIT License
|
|
||||||
|
|
||||||
Type ```git shortlog -s``` for a full list of contributors.
|
Type ```git shortlog -s``` for a full list of contributors.
|
||||||
|
|
||||||
|
© 2012 - 2017, http://ernestmicklei.com. MIT License. Contributions are welcome.
|
||||||
|
|
@ -9,6 +9,7 @@ import (
|
||||||
"compress/zlib"
|
"compress/zlib"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// CompressorProvider describes a component that can provider compressors for the std methods.
|
||||||
type CompressorProvider interface {
|
type CompressorProvider interface {
|
||||||
// Returns a *gzip.Writer which needs to be released later.
|
// Returns a *gzip.Writer which needs to be released later.
|
||||||
// Before using it, call Reset().
|
// Before using it, call Reset().
|
||||||
|
|
|
||||||
|
|
@ -32,7 +32,7 @@ type Container struct {
|
||||||
contentEncodingEnabled bool // default is false
|
contentEncodingEnabled bool // default is false
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewContainer creates a new Container using a new ServeMux and default router (RouterJSR311)
|
// NewContainer creates a new Container using a new ServeMux and default router (CurlyRouter)
|
||||||
func NewContainer() *Container {
|
func NewContainer() *Container {
|
||||||
return &Container{
|
return &Container{
|
||||||
webServices: []*WebService{},
|
webServices: []*WebService{},
|
||||||
|
|
@ -74,7 +74,7 @@ func (c *Container) DoNotRecover(doNot bool) {
|
||||||
c.doNotRecover = doNot
|
c.doNotRecover = doNot
|
||||||
}
|
}
|
||||||
|
|
||||||
// Router changes the default Router (currently RouterJSR311)
|
// Router changes the default Router (currently CurlyRouter)
|
||||||
func (c *Container) Router(aRouter RouteSelector) {
|
func (c *Container) Router(aRouter RouteSelector) {
|
||||||
c.router = aRouter
|
c.router = aRouter
|
||||||
}
|
}
|
||||||
|
|
@ -188,6 +188,17 @@ func writeServiceError(err ServiceError, req *Request, resp *Response) {
|
||||||
resp.WriteErrorString(err.Code, err.Message)
|
resp.WriteErrorString(err.Code, err.Message)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Dispatch the incoming Http Request to a matching WebService.
|
||||||
|
func (c *Container) Dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request) {
|
||||||
|
if httpWriter == nil {
|
||||||
|
panic("httpWriter cannot be nil")
|
||||||
|
}
|
||||||
|
if httpRequest == nil {
|
||||||
|
panic("httpRequest cannot be nil")
|
||||||
|
}
|
||||||
|
c.dispatch(httpWriter, httpRequest)
|
||||||
|
}
|
||||||
|
|
||||||
// Dispatch the incoming Http Request to a matching WebService.
|
// Dispatch the incoming Http Request to a matching WebService.
|
||||||
func (c *Container) dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request) {
|
func (c *Container) dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request) {
|
||||||
writer := httpWriter
|
writer := httpWriter
|
||||||
|
|
@ -208,12 +219,6 @@ func (c *Container) dispatch(httpWriter http.ResponseWriter, httpRequest *http.R
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
// Install closing the request body (if any)
|
|
||||||
defer func() {
|
|
||||||
if nil != httpRequest.Body {
|
|
||||||
httpRequest.Body.Close()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Detect if compression is needed
|
// Detect if compression is needed
|
||||||
// assume without compression, test for override
|
// assume without compression, test for override
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
/*
|
/*
|
||||||
Package restful, a lean package for creating REST-style WebServices without magic.
|
Package restful , a lean package for creating REST-style WebServices without magic.
|
||||||
|
|
||||||
WebServices and Routes
|
WebServices and Routes
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
go test -test.v ...restful && \
|
|
||||||
go test -test.v ...swagger && \
|
|
||||||
go vet ...restful && \
|
|
||||||
go fmt ...swagger && \
|
|
||||||
go install ...swagger && \
|
|
||||||
go fmt ...restful && \
|
|
||||||
go install ...restful
|
|
||||||
cd examples
|
|
||||||
ls *.go | xargs -I {} go build -o /tmp/ignore {}
|
|
||||||
cd ..
|
|
||||||
|
|
@ -5,7 +5,7 @@ import (
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Logger corresponds to a minimal subset of the interface satisfied by stdlib log.Logger
|
// StdLogger corresponds to a minimal subset of the interface satisfied by stdlib log.Logger
|
||||||
type StdLogger interface {
|
type StdLogger interface {
|
||||||
Print(v ...interface{})
|
Print(v ...interface{})
|
||||||
Printf(format string, v ...interface{})
|
Printf(format string, v ...interface{})
|
||||||
|
|
@ -18,14 +18,17 @@ func init() {
|
||||||
SetLogger(stdlog.New(os.Stderr, "[restful] ", stdlog.LstdFlags|stdlog.Lshortfile))
|
SetLogger(stdlog.New(os.Stderr, "[restful] ", stdlog.LstdFlags|stdlog.Lshortfile))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetLogger sets the logger for this package
|
||||||
func SetLogger(customLogger StdLogger) {
|
func SetLogger(customLogger StdLogger) {
|
||||||
Logger = customLogger
|
Logger = customLogger
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Print delegates to the Logger
|
||||||
func Print(v ...interface{}) {
|
func Print(v ...interface{}) {
|
||||||
Logger.Print(v...)
|
Logger.Print(v...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Printf delegates to the Logger
|
||||||
func Printf(format string, v ...interface{}) {
|
func Printf(format string, v ...interface{}) {
|
||||||
Logger.Printf(format, v...)
|
Logger.Printf(format, v...)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,20 +5,15 @@ package restful
|
||||||
// that can be found in the LICENSE file.
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"compress/zlib"
|
"compress/zlib"
|
||||||
"io/ioutil"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
var defaultRequestContentType string
|
var defaultRequestContentType string
|
||||||
|
|
||||||
var doCacheReadEntityBytes = false
|
|
||||||
|
|
||||||
// Request is a wrapper for a http Request that provides convenience methods
|
// Request is a wrapper for a http Request that provides convenience methods
|
||||||
type Request struct {
|
type Request struct {
|
||||||
Request *http.Request
|
Request *http.Request
|
||||||
bodyContent *[]byte // to cache the request body for multiple reads of ReadEntity
|
|
||||||
pathParameters map[string]string
|
pathParameters map[string]string
|
||||||
attributes map[string]interface{} // for storing request-scoped values
|
attributes map[string]interface{} // for storing request-scoped values
|
||||||
selectedRoutePath string // root path + route path that matched the request, e.g. /meetings/{id}/attendees
|
selectedRoutePath string // root path + route path that matched the request, e.g. /meetings/{id}/attendees
|
||||||
|
|
@ -41,12 +36,6 @@ func DefaultRequestContentType(mime string) {
|
||||||
defaultRequestContentType = mime
|
defaultRequestContentType = mime
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetCacheReadEntity controls whether the response data ([]byte) is cached such that ReadEntity is repeatable.
|
|
||||||
// Default is true (due to backwardcompatibility). For better performance, you should set it to false if you don't need it.
|
|
||||||
func SetCacheReadEntity(doCache bool) {
|
|
||||||
doCacheReadEntityBytes = doCache
|
|
||||||
}
|
|
||||||
|
|
||||||
// PathParameter accesses the Path parameter value by its name
|
// PathParameter accesses the Path parameter value by its name
|
||||||
func (r *Request) PathParameter(name string) string {
|
func (r *Request) PathParameter(name string) string {
|
||||||
return r.pathParameters[name]
|
return r.pathParameters[name]
|
||||||
|
|
@ -81,18 +70,6 @@ func (r *Request) ReadEntity(entityPointer interface{}) (err error) {
|
||||||
contentType := r.Request.Header.Get(HEADER_ContentType)
|
contentType := r.Request.Header.Get(HEADER_ContentType)
|
||||||
contentEncoding := r.Request.Header.Get(HEADER_ContentEncoding)
|
contentEncoding := r.Request.Header.Get(HEADER_ContentEncoding)
|
||||||
|
|
||||||
// OLD feature, cache the body for reads
|
|
||||||
if doCacheReadEntityBytes {
|
|
||||||
if r.bodyContent == nil {
|
|
||||||
data, err := ioutil.ReadAll(r.Request.Body)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
r.bodyContent = &data
|
|
||||||
}
|
|
||||||
r.Request.Body = ioutil.NopCloser(bytes.NewReader(*r.bodyContent))
|
|
||||||
}
|
|
||||||
|
|
||||||
// check if the request body needs decompression
|
// check if the request body needs decompression
|
||||||
if ENCODING_GZIP == contentEncoding {
|
if ENCODING_GZIP == contentEncoding {
|
||||||
gzipReader := currentCompressorProvider.AcquireGzipReader()
|
gzipReader := currentCompressorProvider.AcquireGzipReader()
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DEPRECATED, use DefaultResponseContentType(mime)
|
// DefaultResponseMimeType is DEPRECATED, use DefaultResponseContentType(mime)
|
||||||
var DefaultResponseMimeType string
|
var DefaultResponseMimeType string
|
||||||
|
|
||||||
//PrettyPrintResponses controls the indentation feature of XML and JSON serialization
|
//PrettyPrintResponses controls the indentation feature of XML and JSON serialization
|
||||||
|
|
@ -27,11 +27,12 @@ type Response struct {
|
||||||
err error // err property is kept when WriteError is called
|
err error // err property is kept when WriteError is called
|
||||||
}
|
}
|
||||||
|
|
||||||
// Creates a new response based on a http ResponseWriter.
|
// NewResponse creates a new response based on a http ResponseWriter.
|
||||||
func NewResponse(httpWriter http.ResponseWriter) *Response {
|
func NewResponse(httpWriter http.ResponseWriter) *Response {
|
||||||
return &Response{httpWriter, "", []string{}, http.StatusOK, 0, PrettyPrintResponses, nil} // empty content-types
|
return &Response{httpWriter, "", []string{}, http.StatusOK, 0, PrettyPrintResponses, nil} // empty content-types
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DefaultResponseContentType set a default.
|
||||||
// If Accept header matching fails, fall back to this type.
|
// If Accept header matching fails, fall back to this type.
|
||||||
// Valid values are restful.MIME_JSON and restful.MIME_XML
|
// Valid values are restful.MIME_JSON and restful.MIME_XML
|
||||||
// Example:
|
// Example:
|
||||||
|
|
|
||||||
|
|
@ -34,6 +34,9 @@ type Route struct {
|
||||||
ParameterDocs []*Parameter
|
ParameterDocs []*Parameter
|
||||||
ResponseErrors map[int]ResponseError
|
ResponseErrors map[int]ResponseError
|
||||||
ReadSample, WriteSample interface{} // structs that model an example request or response payload
|
ReadSample, WriteSample interface{} // structs that model an example request or response payload
|
||||||
|
|
||||||
|
// Extra information used to store custom information about the route.
|
||||||
|
Metadata map[string]interface{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize for Route
|
// Initialize for Route
|
||||||
|
|
|
||||||
|
|
@ -5,10 +5,12 @@ package restful
|
||||||
// that can be found in the LICENSE file.
|
// that can be found in the LICENSE file.
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"reflect"
|
"reflect"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
|
||||||
"github.com/emicklei/go-restful/log"
|
"github.com/emicklei/go-restful/log"
|
||||||
)
|
)
|
||||||
|
|
@ -22,6 +24,9 @@ type RouteBuilder struct {
|
||||||
httpMethod string // required
|
httpMethod string // required
|
||||||
function RouteFunction // required
|
function RouteFunction // required
|
||||||
filters []FilterFunction
|
filters []FilterFunction
|
||||||
|
|
||||||
|
typeNameHandleFunc TypeNameHandleFunction // required
|
||||||
|
|
||||||
// documentation
|
// documentation
|
||||||
doc string
|
doc string
|
||||||
notes string
|
notes string
|
||||||
|
|
@ -29,6 +34,7 @@ type RouteBuilder struct {
|
||||||
readSample, writeSample interface{}
|
readSample, writeSample interface{}
|
||||||
parameters []*Parameter
|
parameters []*Parameter
|
||||||
errorMap map[int]ResponseError
|
errorMap map[int]ResponseError
|
||||||
|
metadata map[string]interface{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Do evaluates each argument with the RouteBuilder itself.
|
// Do evaluates each argument with the RouteBuilder itself.
|
||||||
|
|
@ -92,8 +98,13 @@ func (b *RouteBuilder) Notes(notes string) *RouteBuilder {
|
||||||
// Reads tells what resource type will be read from the request payload. Optional.
|
// Reads tells what resource type will be read from the request payload. Optional.
|
||||||
// A parameter of type "body" is added ,required is set to true and the dataType is set to the qualified name of the sample's type.
|
// A parameter of type "body" is added ,required is set to true and the dataType is set to the qualified name of the sample's type.
|
||||||
func (b *RouteBuilder) Reads(sample interface{}) *RouteBuilder {
|
func (b *RouteBuilder) Reads(sample interface{}) *RouteBuilder {
|
||||||
|
fn := b.typeNameHandleFunc
|
||||||
|
if fn == nil {
|
||||||
|
fn = reflectTypeName
|
||||||
|
}
|
||||||
|
typeAsName := fn(sample)
|
||||||
|
|
||||||
b.readSample = sample
|
b.readSample = sample
|
||||||
typeAsName := reflect.TypeOf(sample).String()
|
|
||||||
bodyParameter := &Parameter{&ParameterData{Name: "body"}}
|
bodyParameter := &Parameter{&ParameterData{Name: "body"}}
|
||||||
bodyParameter.beBody()
|
bodyParameter.beBody()
|
||||||
bodyParameter.Required(true)
|
bodyParameter.Required(true)
|
||||||
|
|
@ -148,6 +159,7 @@ func (b *RouteBuilder) Returns(code int, message string, model interface{}) *Rou
|
||||||
Code: code,
|
Code: code,
|
||||||
Message: message,
|
Message: message,
|
||||||
Model: model,
|
Model: model,
|
||||||
|
IsDefault: false,
|
||||||
}
|
}
|
||||||
// lazy init because there is no NewRouteBuilder (yet)
|
// lazy init because there is no NewRouteBuilder (yet)
|
||||||
if b.errorMap == nil {
|
if b.errorMap == nil {
|
||||||
|
|
@ -157,10 +169,36 @@ func (b *RouteBuilder) Returns(code int, message string, model interface{}) *Rou
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DefaultReturns is a special Returns call that sets the default of the response ; the code is zero.
|
||||||
|
func (b *RouteBuilder) DefaultReturns(message string, model interface{}) *RouteBuilder {
|
||||||
|
b.Returns(0, message, model)
|
||||||
|
// Modify the ResponseError just added/updated
|
||||||
|
re := b.errorMap[0]
|
||||||
|
// errorMap is initialized
|
||||||
|
b.errorMap[0] = ResponseError{
|
||||||
|
Code: re.Code,
|
||||||
|
Message: re.Message,
|
||||||
|
Model: re.Model,
|
||||||
|
IsDefault: true,
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
// Metadata adds or updates a key=value pair to the metadata map.
|
||||||
|
func (b *RouteBuilder) Metadata(key string, value interface{}) *RouteBuilder {
|
||||||
|
if b.metadata == nil {
|
||||||
|
b.metadata = map[string]interface{}{}
|
||||||
|
}
|
||||||
|
b.metadata[key] = value
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResponseError represents a response; not necessarily an error.
|
||||||
type ResponseError struct {
|
type ResponseError struct {
|
||||||
Code int
|
Code int
|
||||||
Message string
|
Message string
|
||||||
Model interface{}
|
Model interface{}
|
||||||
|
IsDefault bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *RouteBuilder) servicePath(path string) *RouteBuilder {
|
func (b *RouteBuilder) servicePath(path string) *RouteBuilder {
|
||||||
|
|
@ -186,6 +224,13 @@ func (b *RouteBuilder) copyDefaults(rootProduces, rootConsumes []string) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// typeNameHandler sets the function that will convert types to strings in the parameter
|
||||||
|
// and model definitions.
|
||||||
|
func (b *RouteBuilder) typeNameHandler(handler TypeNameHandleFunction) *RouteBuilder {
|
||||||
|
b.typeNameHandleFunc = handler
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
// Build creates a new Route using the specification details collected by the RouteBuilder
|
// Build creates a new Route using the specification details collected by the RouteBuilder
|
||||||
func (b *RouteBuilder) Build() Route {
|
func (b *RouteBuilder) Build() Route {
|
||||||
pathExpr, err := newPathExpression(b.currentPath)
|
pathExpr, err := newPathExpression(b.currentPath)
|
||||||
|
|
@ -217,7 +262,8 @@ func (b *RouteBuilder) Build() Route {
|
||||||
ParameterDocs: b.parameters,
|
ParameterDocs: b.parameters,
|
||||||
ResponseErrors: b.errorMap,
|
ResponseErrors: b.errorMap,
|
||||||
ReadSample: b.readSample,
|
ReadSample: b.readSample,
|
||||||
WriteSample: b.writeSample}
|
WriteSample: b.writeSample,
|
||||||
|
Metadata: b.metadata}
|
||||||
route.postBuild()
|
route.postBuild()
|
||||||
return route
|
return route
|
||||||
}
|
}
|
||||||
|
|
@ -226,6 +272,8 @@ func concatPath(path1, path2 string) string {
|
||||||
return strings.TrimRight(path1, "/") + "/" + strings.TrimLeft(path2, "/")
|
return strings.TrimRight(path1, "/") + "/" + strings.TrimLeft(path2, "/")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var anonymousFuncCount int32
|
||||||
|
|
||||||
// nameOfFunction returns the short name of the function f for documentation.
|
// nameOfFunction returns the short name of the function f for documentation.
|
||||||
// It uses a runtime feature for debugging ; its value may change for later Go versions.
|
// It uses a runtime feature for debugging ; its value may change for later Go versions.
|
||||||
func nameOfFunction(f interface{}) string {
|
func nameOfFunction(f interface{}) string {
|
||||||
|
|
@ -236,5 +284,10 @@ func nameOfFunction(f interface{}) string {
|
||||||
last = strings.TrimSuffix(last, ")-fm") // Go 1.5
|
last = strings.TrimSuffix(last, ")-fm") // Go 1.5
|
||||||
last = strings.TrimSuffix(last, "·fm") // < Go 1.5
|
last = strings.TrimSuffix(last, "·fm") // < Go 1.5
|
||||||
last = strings.TrimSuffix(last, "-fm") // Go 1.5
|
last = strings.TrimSuffix(last, "-fm") // Go 1.5
|
||||||
|
if last == "func1" { // this could mean conflicts in API docs
|
||||||
|
val := atomic.AddInt32(&anonymousFuncCount, 1)
|
||||||
|
last = "func" + fmt.Sprintf("%d", val)
|
||||||
|
atomic.StoreInt32(&anonymousFuncCount, val)
|
||||||
|
}
|
||||||
return last
|
return last
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ package restful
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"os"
|
"os"
|
||||||
|
"reflect"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/emicklei/go-restful/log"
|
"github.com/emicklei/go-restful/log"
|
||||||
|
|
@ -24,6 +25,8 @@ type WebService struct {
|
||||||
documentation string
|
documentation string
|
||||||
apiVersion string
|
apiVersion string
|
||||||
|
|
||||||
|
typeNameHandleFunc TypeNameHandleFunction
|
||||||
|
|
||||||
dynamicRoutes bool
|
dynamicRoutes bool
|
||||||
|
|
||||||
// protects 'routes' if dynamic routes are enabled
|
// protects 'routes' if dynamic routes are enabled
|
||||||
|
|
@ -34,6 +37,25 @@ func (w *WebService) SetDynamicRoutes(enable bool) {
|
||||||
w.dynamicRoutes = enable
|
w.dynamicRoutes = enable
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TypeNameHandleFunction declares functions that can handle translating the name of a sample object
|
||||||
|
// into the restful documentation for the service.
|
||||||
|
type TypeNameHandleFunction func(sample interface{}) string
|
||||||
|
|
||||||
|
// TypeNameHandler sets the function that will convert types to strings in the parameter
|
||||||
|
// and model definitions. If not set, the web service will invoke
|
||||||
|
// reflect.TypeOf(object).String().
|
||||||
|
func (w *WebService) TypeNameHandler(handler TypeNameHandleFunction) *WebService {
|
||||||
|
w.typeNameHandleFunc = handler
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
|
||||||
|
// reflectTypeName is the default TypeNameHandleFunction and for a given object
|
||||||
|
// returns the name that Go identifies it with (e.g. "string" or "v1.Object") via
|
||||||
|
// the reflection API.
|
||||||
|
func reflectTypeName(sample interface{}) string {
|
||||||
|
return reflect.TypeOf(sample).String()
|
||||||
|
}
|
||||||
|
|
||||||
// compilePathExpression ensures that the path is compiled into a RegEx for those routers that need it.
|
// compilePathExpression ensures that the path is compiled into a RegEx for those routers that need it.
|
||||||
func (w *WebService) compilePathExpression() {
|
func (w *WebService) compilePathExpression() {
|
||||||
compiled, err := newPathExpression(w.rootPath)
|
compiled, err := newPathExpression(w.rootPath)
|
||||||
|
|
@ -174,7 +196,7 @@ func (w *WebService) RemoveRoute(path, method string) error {
|
||||||
|
|
||||||
// Method creates a new RouteBuilder and initialize its http method
|
// Method creates a new RouteBuilder and initialize its http method
|
||||||
func (w *WebService) Method(httpMethod string) *RouteBuilder {
|
func (w *WebService) Method(httpMethod string) *RouteBuilder {
|
||||||
return new(RouteBuilder).servicePath(w.rootPath).Method(httpMethod)
|
return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method(httpMethod)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Produces specifies that this WebService can produce one or more MIME types.
|
// Produces specifies that this WebService can produce one or more MIME types.
|
||||||
|
|
@ -239,30 +261,30 @@ func (w *WebService) Documentation() string {
|
||||||
|
|
||||||
// HEAD is a shortcut for .Method("HEAD").Path(subPath)
|
// HEAD is a shortcut for .Method("HEAD").Path(subPath)
|
||||||
func (w *WebService) HEAD(subPath string) *RouteBuilder {
|
func (w *WebService) HEAD(subPath string) *RouteBuilder {
|
||||||
return new(RouteBuilder).servicePath(w.rootPath).Method("HEAD").Path(subPath)
|
return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("HEAD").Path(subPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GET is a shortcut for .Method("GET").Path(subPath)
|
// GET is a shortcut for .Method("GET").Path(subPath)
|
||||||
func (w *WebService) GET(subPath string) *RouteBuilder {
|
func (w *WebService) GET(subPath string) *RouteBuilder {
|
||||||
return new(RouteBuilder).servicePath(w.rootPath).Method("GET").Path(subPath)
|
return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("GET").Path(subPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// POST is a shortcut for .Method("POST").Path(subPath)
|
// POST is a shortcut for .Method("POST").Path(subPath)
|
||||||
func (w *WebService) POST(subPath string) *RouteBuilder {
|
func (w *WebService) POST(subPath string) *RouteBuilder {
|
||||||
return new(RouteBuilder).servicePath(w.rootPath).Method("POST").Path(subPath)
|
return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("POST").Path(subPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// PUT is a shortcut for .Method("PUT").Path(subPath)
|
// PUT is a shortcut for .Method("PUT").Path(subPath)
|
||||||
func (w *WebService) PUT(subPath string) *RouteBuilder {
|
func (w *WebService) PUT(subPath string) *RouteBuilder {
|
||||||
return new(RouteBuilder).servicePath(w.rootPath).Method("PUT").Path(subPath)
|
return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("PUT").Path(subPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// PATCH is a shortcut for .Method("PATCH").Path(subPath)
|
// PATCH is a shortcut for .Method("PATCH").Path(subPath)
|
||||||
func (w *WebService) PATCH(subPath string) *RouteBuilder {
|
func (w *WebService) PATCH(subPath string) *RouteBuilder {
|
||||||
return new(RouteBuilder).servicePath(w.rootPath).Method("PATCH").Path(subPath)
|
return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("PATCH").Path(subPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// DELETE is a shortcut for .Method("DELETE").Path(subPath)
|
// DELETE is a shortcut for .Method("DELETE").Path(subPath)
|
||||||
func (w *WebService) DELETE(subPath string) *RouteBuilder {
|
func (w *WebService) DELETE(subPath string) *RouteBuilder {
|
||||||
return new(RouteBuilder).servicePath(w.rootPath).Method("DELETE").Path(subPath)
|
return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("DELETE").Path(subPath)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
language: go
|
|
||||||
|
|
||||||
go:
|
|
||||||
- 1.4
|
|
||||||
- 1.3
|
|
||||||
- 1.2
|
|
||||||
- tip
|
|
||||||
|
|
||||||
install:
|
|
||||||
- if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi
|
|
||||||
|
|
||||||
script:
|
|
||||||
- go test -cover
|
|
||||||
|
|
@ -1,67 +0,0 @@
|
||||||
# How to contribute #
|
|
||||||
|
|
||||||
We'd love to accept your patches and contributions to this project. There are
|
|
||||||
a just a few small guidelines you need to follow.
|
|
||||||
|
|
||||||
|
|
||||||
## Contributor License Agreement ##
|
|
||||||
|
|
||||||
Contributions to any Google project must be accompanied by a Contributor
|
|
||||||
License Agreement. This is not a copyright **assignment**, it simply gives
|
|
||||||
Google permission to use and redistribute your contributions as part of the
|
|
||||||
project.
|
|
||||||
|
|
||||||
* If you are an individual writing original source code and you're sure you
|
|
||||||
own the intellectual property, then you'll need to sign an [individual
|
|
||||||
CLA][].
|
|
||||||
|
|
||||||
* If you work for a company that wants to allow you to contribute your work,
|
|
||||||
then you'll need to sign a [corporate CLA][].
|
|
||||||
|
|
||||||
You generally only need to submit a CLA once, so if you've already submitted
|
|
||||||
one (even if it was for a different project), you probably don't need to do it
|
|
||||||
again.
|
|
||||||
|
|
||||||
[individual CLA]: https://developers.google.com/open-source/cla/individual
|
|
||||||
[corporate CLA]: https://developers.google.com/open-source/cla/corporate
|
|
||||||
|
|
||||||
|
|
||||||
## Submitting a patch ##
|
|
||||||
|
|
||||||
1. It's generally best to start by opening a new issue describing the bug or
|
|
||||||
feature you're intending to fix. Even if you think it's relatively minor,
|
|
||||||
it's helpful to know what people are working on. Mention in the initial
|
|
||||||
issue that you are planning to work on that bug or feature so that it can
|
|
||||||
be assigned to you.
|
|
||||||
|
|
||||||
1. Follow the normal process of [forking][] the project, and setup a new
|
|
||||||
branch to work in. It's important that each group of changes be done in
|
|
||||||
separate branches in order to ensure that a pull request only includes the
|
|
||||||
commits related to that bug or feature.
|
|
||||||
|
|
||||||
1. Go makes it very simple to ensure properly formatted code, so always run
|
|
||||||
`go fmt` on your code before committing it. You should also run
|
|
||||||
[golint][] over your code. As noted in the [golint readme][], it's not
|
|
||||||
strictly necessary that your code be completely "lint-free", but this will
|
|
||||||
help you find common style issues.
|
|
||||||
|
|
||||||
1. Any significant changes should almost always be accompanied by tests. The
|
|
||||||
project already has good test coverage, so look at some of the existing
|
|
||||||
tests if you're unsure how to go about it. [gocov][] and [gocov-html][]
|
|
||||||
are invaluable tools for seeing which parts of your code aren't being
|
|
||||||
exercised by your tests.
|
|
||||||
|
|
||||||
1. Do your best to have [well-formed commit messages][] for each change.
|
|
||||||
This provides consistency throughout the project, and ensures that commit
|
|
||||||
messages are able to be formatted properly by various git tools.
|
|
||||||
|
|
||||||
1. Finally, push the commits to your fork and submit a [pull request][].
|
|
||||||
|
|
||||||
[forking]: https://help.github.com/articles/fork-a-repo
|
|
||||||
[golint]: https://github.com/golang/lint
|
|
||||||
[golint readme]: https://github.com/golang/lint/blob/master/README
|
|
||||||
[gocov]: https://github.com/axw/gocov
|
|
||||||
[gocov-html]: https://github.com/matm/gocov-html
|
|
||||||
[well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html
|
|
||||||
[squash]: http://git-scm.com/book/en/Git-Tools-Rewriting-History#Squashing-Commits
|
|
||||||
[pull request]: https://help.github.com/articles/creating-a-pull-request
|
|
||||||
|
|
@ -1,202 +0,0 @@
|
||||||
|
|
||||||
Apache License
|
|
||||||
Version 2.0, January 2004
|
|
||||||
http://www.apache.org/licenses/
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
||||||
|
|
||||||
1. Definitions.
|
|
||||||
|
|
||||||
"License" shall mean the terms and conditions for use, reproduction,
|
|
||||||
and distribution as defined by Sections 1 through 9 of this document.
|
|
||||||
|
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by
|
|
||||||
the copyright owner that is granting the License.
|
|
||||||
|
|
||||||
"Legal Entity" shall mean the union of the acting entity and all
|
|
||||||
other entities that control, are controlled by, or are under common
|
|
||||||
control with that entity. For the purposes of this definition,
|
|
||||||
"control" means (i) the power, direct or indirect, to cause the
|
|
||||||
direction or management of such entity, whether by contract or
|
|
||||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
||||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
||||||
|
|
||||||
"You" (or "Your") shall mean an individual or Legal Entity
|
|
||||||
exercising permissions granted by this License.
|
|
||||||
|
|
||||||
"Source" form shall mean the preferred form for making modifications,
|
|
||||||
including but not limited to software source code, documentation
|
|
||||||
source, and configuration files.
|
|
||||||
|
|
||||||
"Object" form shall mean any form resulting from mechanical
|
|
||||||
transformation or translation of a Source form, including but
|
|
||||||
not limited to compiled object code, generated documentation,
|
|
||||||
and conversions to other media types.
|
|
||||||
|
|
||||||
"Work" shall mean the work of authorship, whether in Source or
|
|
||||||
Object form, made available under the License, as indicated by a
|
|
||||||
copyright notice that is included in or attached to the work
|
|
||||||
(an example is provided in the Appendix below).
|
|
||||||
|
|
||||||
"Derivative Works" shall mean any work, whether in Source or Object
|
|
||||||
form, that is based on (or derived from) the Work and for which the
|
|
||||||
editorial revisions, annotations, elaborations, or other modifications
|
|
||||||
represent, as a whole, an original work of authorship. For the purposes
|
|
||||||
of this License, Derivative Works shall not include works that remain
|
|
||||||
separable from, or merely link (or bind by name) to the interfaces of,
|
|
||||||
the Work and Derivative Works thereof.
|
|
||||||
|
|
||||||
"Contribution" shall mean any work of authorship, including
|
|
||||||
the original version of the Work and any modifications or additions
|
|
||||||
to that Work or Derivative Works thereof, that is intentionally
|
|
||||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
||||||
or by an individual or Legal Entity authorized to submit on behalf of
|
|
||||||
the copyright owner. For the purposes of this definition, "submitted"
|
|
||||||
means any form of electronic, verbal, or written communication sent
|
|
||||||
to the Licensor or its representatives, including but not limited to
|
|
||||||
communication on electronic mailing lists, source code control systems,
|
|
||||||
and issue tracking systems that are managed by, or on behalf of, the
|
|
||||||
Licensor for the purpose of discussing and improving the Work, but
|
|
||||||
excluding communication that is conspicuously marked or otherwise
|
|
||||||
designated in writing by the copyright owner as "Not a Contribution."
|
|
||||||
|
|
||||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
||||||
on behalf of whom a Contribution has been received by Licensor and
|
|
||||||
subsequently incorporated within the Work.
|
|
||||||
|
|
||||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
copyright license to reproduce, prepare Derivative Works of,
|
|
||||||
publicly display, publicly perform, sublicense, and distribute the
|
|
||||||
Work and such Derivative Works in Source or Object form.
|
|
||||||
|
|
||||||
3. Grant of Patent License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
(except as stated in this section) patent license to make, have made,
|
|
||||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
||||||
where such license applies only to those patent claims licensable
|
|
||||||
by such Contributor that are necessarily infringed by their
|
|
||||||
Contribution(s) alone or by combination of their Contribution(s)
|
|
||||||
with the Work to which such Contribution(s) was submitted. If You
|
|
||||||
institute patent litigation against any entity (including a
|
|
||||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
||||||
or a Contribution incorporated within the Work constitutes direct
|
|
||||||
or contributory patent infringement, then any patent licenses
|
|
||||||
granted to You under this License for that Work shall terminate
|
|
||||||
as of the date such litigation is filed.
|
|
||||||
|
|
||||||
4. Redistribution. You may reproduce and distribute copies of the
|
|
||||||
Work or Derivative Works thereof in any medium, with or without
|
|
||||||
modifications, and in Source or Object form, provided that You
|
|
||||||
meet the following conditions:
|
|
||||||
|
|
||||||
(a) You must give any other recipients of the Work or
|
|
||||||
Derivative Works a copy of this License; and
|
|
||||||
|
|
||||||
(b) You must cause any modified files to carry prominent notices
|
|
||||||
stating that You changed the files; and
|
|
||||||
|
|
||||||
(c) You must retain, in the Source form of any Derivative Works
|
|
||||||
that You distribute, all copyright, patent, trademark, and
|
|
||||||
attribution notices from the Source form of the Work,
|
|
||||||
excluding those notices that do not pertain to any part of
|
|
||||||
the Derivative Works; and
|
|
||||||
|
|
||||||
(d) If the Work includes a "NOTICE" text file as part of its
|
|
||||||
distribution, then any Derivative Works that You distribute must
|
|
||||||
include a readable copy of the attribution notices contained
|
|
||||||
within such NOTICE file, excluding those notices that do not
|
|
||||||
pertain to any part of the Derivative Works, in at least one
|
|
||||||
of the following places: within a NOTICE text file distributed
|
|
||||||
as part of the Derivative Works; within the Source form or
|
|
||||||
documentation, if provided along with the Derivative Works; or,
|
|
||||||
within a display generated by the Derivative Works, if and
|
|
||||||
wherever such third-party notices normally appear. The contents
|
|
||||||
of the NOTICE file are for informational purposes only and
|
|
||||||
do not modify the License. You may add Your own attribution
|
|
||||||
notices within Derivative Works that You distribute, alongside
|
|
||||||
or as an addendum to the NOTICE text from the Work, provided
|
|
||||||
that such additional attribution notices cannot be construed
|
|
||||||
as modifying the License.
|
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and
|
|
||||||
may provide additional or different license terms and conditions
|
|
||||||
for use, reproduction, or distribution of Your modifications, or
|
|
||||||
for any such Derivative Works as a whole, provided Your use,
|
|
||||||
reproduction, and distribution of the Work otherwise complies with
|
|
||||||
the conditions stated in this License.
|
|
||||||
|
|
||||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
||||||
any Contribution intentionally submitted for inclusion in the Work
|
|
||||||
by You to the Licensor shall be under the terms and conditions of
|
|
||||||
this License, without any additional terms or conditions.
|
|
||||||
Notwithstanding the above, nothing herein shall supersede or modify
|
|
||||||
the terms of any separate license agreement you may have executed
|
|
||||||
with Licensor regarding such Contributions.
|
|
||||||
|
|
||||||
6. Trademarks. This License does not grant permission to use the trade
|
|
||||||
names, trademarks, service marks, or product names of the Licensor,
|
|
||||||
except as required for reasonable and customary use in describing the
|
|
||||||
origin of the Work and reproducing the content of the NOTICE file.
|
|
||||||
|
|
||||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
||||||
agreed to in writing, Licensor provides the Work (and each
|
|
||||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
||||||
implied, including, without limitation, any warranties or conditions
|
|
||||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
||||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
||||||
appropriateness of using or redistributing the Work and assume any
|
|
||||||
risks associated with Your exercise of permissions under this License.
|
|
||||||
|
|
||||||
8. Limitation of Liability. In no event and under no legal theory,
|
|
||||||
whether in tort (including negligence), contract, or otherwise,
|
|
||||||
unless required by applicable law (such as deliberate and grossly
|
|
||||||
negligent acts) or agreed to in writing, shall any Contributor be
|
|
||||||
liable to You for damages, including any direct, indirect, special,
|
|
||||||
incidental, or consequential damages of any character arising as a
|
|
||||||
result of this License or out of the use or inability to use the
|
|
||||||
Work (including but not limited to damages for loss of goodwill,
|
|
||||||
work stoppage, computer failure or malfunction, or any and all
|
|
||||||
other commercial damages or losses), even if such Contributor
|
|
||||||
has been advised of the possibility of such damages.
|
|
||||||
|
|
||||||
9. Accepting Warranty or Additional Liability. While redistributing
|
|
||||||
the Work or Derivative Works thereof, You may choose to offer,
|
|
||||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
||||||
or other liability obligations and/or rights consistent with this
|
|
||||||
License. However, in accepting such obligations, You may act only
|
|
||||||
on Your own behalf and on Your sole responsibility, not on behalf
|
|
||||||
of any other Contributor, and only if You agree to indemnify,
|
|
||||||
defend, and hold each Contributor harmless for any liability
|
|
||||||
incurred by, or claims asserted against, such Contributor by reason
|
|
||||||
of your accepting any such warranty or additional liability.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
APPENDIX: How to apply the Apache License to your work.
|
|
||||||
|
|
||||||
To apply the Apache License to your work, attach the following
|
|
||||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
||||||
replaced with your own identifying information. (Don't include
|
|
||||||
the brackets!) The text should be enclosed in the appropriate
|
|
||||||
comment syntax for the file format. We also recommend that a
|
|
||||||
file or class name and description of purpose be included on the
|
|
||||||
same "printed page" as the copyright notice for easier
|
|
||||||
identification within third-party archives.
|
|
||||||
|
|
||||||
Copyright [yyyy] [name of copyright owner]
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
|
|
@ -1,71 +0,0 @@
|
||||||
gofuzz
|
|
||||||
======
|
|
||||||
|
|
||||||
gofuzz is a library for populating go objects with random values.
|
|
||||||
|
|
||||||
[](https://godoc.org/github.com/google/gofuzz)
|
|
||||||
[](https://travis-ci.org/google/gofuzz)
|
|
||||||
|
|
||||||
This is useful for testing:
|
|
||||||
|
|
||||||
* Do your project's objects really serialize/unserialize correctly in all cases?
|
|
||||||
* Is there an incorrectly formatted object that will cause your project to panic?
|
|
||||||
|
|
||||||
Import with ```import "github.com/google/gofuzz"```
|
|
||||||
|
|
||||||
You can use it on single variables:
|
|
||||||
```go
|
|
||||||
f := fuzz.New()
|
|
||||||
var myInt int
|
|
||||||
f.Fuzz(&myInt) // myInt gets a random value.
|
|
||||||
```
|
|
||||||
|
|
||||||
You can use it on maps:
|
|
||||||
```go
|
|
||||||
f := fuzz.New().NilChance(0).NumElements(1, 1)
|
|
||||||
var myMap map[ComplexKeyType]string
|
|
||||||
f.Fuzz(&myMap) // myMap will have exactly one element.
|
|
||||||
```
|
|
||||||
|
|
||||||
Customize the chance of getting a nil pointer:
|
|
||||||
```go
|
|
||||||
f := fuzz.New().NilChance(.5)
|
|
||||||
var fancyStruct struct {
|
|
||||||
A, B, C, D *string
|
|
||||||
}
|
|
||||||
f.Fuzz(&fancyStruct) // About half the pointers should be set.
|
|
||||||
```
|
|
||||||
|
|
||||||
You can even customize the randomization completely if needed:
|
|
||||||
```go
|
|
||||||
type MyEnum string
|
|
||||||
const (
|
|
||||||
A MyEnum = "A"
|
|
||||||
B MyEnum = "B"
|
|
||||||
)
|
|
||||||
type MyInfo struct {
|
|
||||||
Type MyEnum
|
|
||||||
AInfo *string
|
|
||||||
BInfo *string
|
|
||||||
}
|
|
||||||
|
|
||||||
f := fuzz.New().NilChance(0).Funcs(
|
|
||||||
func(e *MyInfo, c fuzz.Continue) {
|
|
||||||
switch c.Intn(2) {
|
|
||||||
case 0:
|
|
||||||
e.Type = A
|
|
||||||
c.Fuzz(&e.AInfo)
|
|
||||||
case 1:
|
|
||||||
e.Type = B
|
|
||||||
c.Fuzz(&e.BInfo)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
var myObject MyInfo
|
|
||||||
f.Fuzz(&myObject) // Type will correspond to whether A or B info is set.
|
|
||||||
```
|
|
||||||
|
|
||||||
See more examples in ```example_test.go```.
|
|
||||||
|
|
||||||
Happy testing!
|
|
||||||
|
|
@ -1,18 +0,0 @@
|
||||||
/*
|
|
||||||
Copyright 2014 Google Inc. All rights reserved.
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Package fuzz is a library for populating go objects with random values.
|
|
||||||
package fuzz
|
|
||||||
|
|
@ -1,453 +0,0 @@
|
||||||
/*
|
|
||||||
Copyright 2014 Google Inc. All rights reserved.
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package fuzz
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"math/rand"
|
|
||||||
"reflect"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// fuzzFuncMap is a map from a type to a fuzzFunc that handles that type.
|
|
||||||
type fuzzFuncMap map[reflect.Type]reflect.Value
|
|
||||||
|
|
||||||
// Fuzzer knows how to fill any object with random fields.
|
|
||||||
type Fuzzer struct {
|
|
||||||
fuzzFuncs fuzzFuncMap
|
|
||||||
defaultFuzzFuncs fuzzFuncMap
|
|
||||||
r *rand.Rand
|
|
||||||
nilChance float64
|
|
||||||
minElements int
|
|
||||||
maxElements int
|
|
||||||
}
|
|
||||||
|
|
||||||
// New returns a new Fuzzer. Customize your Fuzzer further by calling Funcs,
|
|
||||||
// RandSource, NilChance, or NumElements in any order.
|
|
||||||
func New() *Fuzzer {
|
|
||||||
f := &Fuzzer{
|
|
||||||
defaultFuzzFuncs: fuzzFuncMap{
|
|
||||||
reflect.TypeOf(&time.Time{}): reflect.ValueOf(fuzzTime),
|
|
||||||
},
|
|
||||||
|
|
||||||
fuzzFuncs: fuzzFuncMap{},
|
|
||||||
r: rand.New(rand.NewSource(time.Now().UnixNano())),
|
|
||||||
nilChance: .2,
|
|
||||||
minElements: 1,
|
|
||||||
maxElements: 10,
|
|
||||||
}
|
|
||||||
return f
|
|
||||||
}
|
|
||||||
|
|
||||||
// Funcs adds each entry in fuzzFuncs as a custom fuzzing function.
|
|
||||||
//
|
|
||||||
// Each entry in fuzzFuncs must be a function taking two parameters.
|
|
||||||
// The first parameter must be a pointer or map. It is the variable that
|
|
||||||
// function will fill with random data. The second parameter must be a
|
|
||||||
// fuzz.Continue, which will provide a source of randomness and a way
|
|
||||||
// to automatically continue fuzzing smaller pieces of the first parameter.
|
|
||||||
//
|
|
||||||
// These functions are called sensibly, e.g., if you wanted custom string
|
|
||||||
// fuzzing, the function `func(s *string, c fuzz.Continue)` would get
|
|
||||||
// called and passed the address of strings. Maps and pointers will always
|
|
||||||
// be made/new'd for you, ignoring the NilChange option. For slices, it
|
|
||||||
// doesn't make much sense to pre-create them--Fuzzer doesn't know how
|
|
||||||
// long you want your slice--so take a pointer to a slice, and make it
|
|
||||||
// yourself. (If you don't want your map/pointer type pre-made, take a
|
|
||||||
// pointer to it, and make it yourself.) See the examples for a range of
|
|
||||||
// custom functions.
|
|
||||||
func (f *Fuzzer) Funcs(fuzzFuncs ...interface{}) *Fuzzer {
|
|
||||||
for i := range fuzzFuncs {
|
|
||||||
v := reflect.ValueOf(fuzzFuncs[i])
|
|
||||||
if v.Kind() != reflect.Func {
|
|
||||||
panic("Need only funcs!")
|
|
||||||
}
|
|
||||||
t := v.Type()
|
|
||||||
if t.NumIn() != 2 || t.NumOut() != 0 {
|
|
||||||
panic("Need 2 in and 0 out params!")
|
|
||||||
}
|
|
||||||
argT := t.In(0)
|
|
||||||
switch argT.Kind() {
|
|
||||||
case reflect.Ptr, reflect.Map:
|
|
||||||
default:
|
|
||||||
panic("fuzzFunc must take pointer or map type")
|
|
||||||
}
|
|
||||||
if t.In(1) != reflect.TypeOf(Continue{}) {
|
|
||||||
panic("fuzzFunc's second parameter must be type fuzz.Continue")
|
|
||||||
}
|
|
||||||
f.fuzzFuncs[argT] = v
|
|
||||||
}
|
|
||||||
return f
|
|
||||||
}
|
|
||||||
|
|
||||||
// RandSource causes f to get values from the given source of randomness.
|
|
||||||
// Use if you want deterministic fuzzing.
|
|
||||||
func (f *Fuzzer) RandSource(s rand.Source) *Fuzzer {
|
|
||||||
f.r = rand.New(s)
|
|
||||||
return f
|
|
||||||
}
|
|
||||||
|
|
||||||
// NilChance sets the probability of creating a nil pointer, map, or slice to
|
|
||||||
// 'p'. 'p' should be between 0 (no nils) and 1 (all nils), inclusive.
|
|
||||||
func (f *Fuzzer) NilChance(p float64) *Fuzzer {
|
|
||||||
if p < 0 || p > 1 {
|
|
||||||
panic("p should be between 0 and 1, inclusive.")
|
|
||||||
}
|
|
||||||
f.nilChance = p
|
|
||||||
return f
|
|
||||||
}
|
|
||||||
|
|
||||||
// NumElements sets the minimum and maximum number of elements that will be
|
|
||||||
// added to a non-nil map or slice.
|
|
||||||
func (f *Fuzzer) NumElements(atLeast, atMost int) *Fuzzer {
|
|
||||||
if atLeast > atMost {
|
|
||||||
panic("atLeast must be <= atMost")
|
|
||||||
}
|
|
||||||
if atLeast < 0 {
|
|
||||||
panic("atLeast must be >= 0")
|
|
||||||
}
|
|
||||||
f.minElements = atLeast
|
|
||||||
f.maxElements = atMost
|
|
||||||
return f
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fuzzer) genElementCount() int {
|
|
||||||
if f.minElements == f.maxElements {
|
|
||||||
return f.minElements
|
|
||||||
}
|
|
||||||
return f.minElements + f.r.Intn(f.maxElements-f.minElements+1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fuzzer) genShouldFill() bool {
|
|
||||||
return f.r.Float64() > f.nilChance
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fuzz recursively fills all of obj's fields with something random. First
|
|
||||||
// this tries to find a custom fuzz function (see Funcs). If there is no
|
|
||||||
// custom function this tests whether the object implements fuzz.Interface and,
|
|
||||||
// if so, calls Fuzz on it to fuzz itself. If that fails, this will see if
|
|
||||||
// there is a default fuzz function provided by this package. If all of that
|
|
||||||
// fails, this will generate random values for all primitive fields and then
|
|
||||||
// recurse for all non-primitives.
|
|
||||||
//
|
|
||||||
// Not safe for cyclic or tree-like structs!
|
|
||||||
//
|
|
||||||
// obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ )
|
|
||||||
// Intended for tests, so will panic on bad input or unimplemented fields.
|
|
||||||
func (f *Fuzzer) Fuzz(obj interface{}) {
|
|
||||||
v := reflect.ValueOf(obj)
|
|
||||||
if v.Kind() != reflect.Ptr {
|
|
||||||
panic("needed ptr!")
|
|
||||||
}
|
|
||||||
v = v.Elem()
|
|
||||||
f.doFuzz(v, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// FuzzNoCustom is just like Fuzz, except that any custom fuzz function for
|
|
||||||
// obj's type will not be called and obj will not be tested for fuzz.Interface
|
|
||||||
// conformance. This applies only to obj and not other instances of obj's
|
|
||||||
// type.
|
|
||||||
// Not safe for cyclic or tree-like structs!
|
|
||||||
// obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ )
|
|
||||||
// Intended for tests, so will panic on bad input or unimplemented fields.
|
|
||||||
func (f *Fuzzer) FuzzNoCustom(obj interface{}) {
|
|
||||||
v := reflect.ValueOf(obj)
|
|
||||||
if v.Kind() != reflect.Ptr {
|
|
||||||
panic("needed ptr!")
|
|
||||||
}
|
|
||||||
v = v.Elem()
|
|
||||||
f.doFuzz(v, flagNoCustomFuzz)
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
// Do not try to find a custom fuzz function. Does not apply recursively.
|
|
||||||
flagNoCustomFuzz uint64 = 1 << iota
|
|
||||||
)
|
|
||||||
|
|
||||||
func (f *Fuzzer) doFuzz(v reflect.Value, flags uint64) {
|
|
||||||
if !v.CanSet() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if flags&flagNoCustomFuzz == 0 {
|
|
||||||
// Check for both pointer and non-pointer custom functions.
|
|
||||||
if v.CanAddr() && f.tryCustom(v.Addr()) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if f.tryCustom(v) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if fn, ok := fillFuncMap[v.Kind()]; ok {
|
|
||||||
fn(v, f.r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
switch v.Kind() {
|
|
||||||
case reflect.Map:
|
|
||||||
if f.genShouldFill() {
|
|
||||||
v.Set(reflect.MakeMap(v.Type()))
|
|
||||||
n := f.genElementCount()
|
|
||||||
for i := 0; i < n; i++ {
|
|
||||||
key := reflect.New(v.Type().Key()).Elem()
|
|
||||||
f.doFuzz(key, 0)
|
|
||||||
val := reflect.New(v.Type().Elem()).Elem()
|
|
||||||
f.doFuzz(val, 0)
|
|
||||||
v.SetMapIndex(key, val)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
v.Set(reflect.Zero(v.Type()))
|
|
||||||
case reflect.Ptr:
|
|
||||||
if f.genShouldFill() {
|
|
||||||
v.Set(reflect.New(v.Type().Elem()))
|
|
||||||
f.doFuzz(v.Elem(), 0)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
v.Set(reflect.Zero(v.Type()))
|
|
||||||
case reflect.Slice:
|
|
||||||
if f.genShouldFill() {
|
|
||||||
n := f.genElementCount()
|
|
||||||
v.Set(reflect.MakeSlice(v.Type(), n, n))
|
|
||||||
for i := 0; i < n; i++ {
|
|
||||||
f.doFuzz(v.Index(i), 0)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
v.Set(reflect.Zero(v.Type()))
|
|
||||||
case reflect.Array:
|
|
||||||
if f.genShouldFill() {
|
|
||||||
n := v.Len()
|
|
||||||
for i := 0; i < n; i++ {
|
|
||||||
f.doFuzz(v.Index(i), 0)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
v.Set(reflect.Zero(v.Type()))
|
|
||||||
case reflect.Struct:
|
|
||||||
for i := 0; i < v.NumField(); i++ {
|
|
||||||
f.doFuzz(v.Field(i), 0)
|
|
||||||
}
|
|
||||||
case reflect.Chan:
|
|
||||||
fallthrough
|
|
||||||
case reflect.Func:
|
|
||||||
fallthrough
|
|
||||||
case reflect.Interface:
|
|
||||||
fallthrough
|
|
||||||
default:
|
|
||||||
panic(fmt.Sprintf("Can't handle %#v", v.Interface()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// tryCustom searches for custom handlers, and returns true iff it finds a match
|
|
||||||
// and successfully randomizes v.
|
|
||||||
func (f *Fuzzer) tryCustom(v reflect.Value) bool {
|
|
||||||
// First: see if we have a fuzz function for it.
|
|
||||||
doCustom, ok := f.fuzzFuncs[v.Type()]
|
|
||||||
if !ok {
|
|
||||||
// Second: see if it can fuzz itself.
|
|
||||||
if v.CanInterface() {
|
|
||||||
intf := v.Interface()
|
|
||||||
if fuzzable, ok := intf.(Interface); ok {
|
|
||||||
fuzzable.Fuzz(Continue{f: f, Rand: f.r})
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Finally: see if there is a default fuzz function.
|
|
||||||
doCustom, ok = f.defaultFuzzFuncs[v.Type()]
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
switch v.Kind() {
|
|
||||||
case reflect.Ptr:
|
|
||||||
if v.IsNil() {
|
|
||||||
if !v.CanSet() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
v.Set(reflect.New(v.Type().Elem()))
|
|
||||||
}
|
|
||||||
case reflect.Map:
|
|
||||||
if v.IsNil() {
|
|
||||||
if !v.CanSet() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
v.Set(reflect.MakeMap(v.Type()))
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{
|
|
||||||
f: f,
|
|
||||||
Rand: f.r,
|
|
||||||
})})
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Interface represents an object that knows how to fuzz itself. Any time we
|
|
||||||
// find a type that implements this interface we will delegate the act of
|
|
||||||
// fuzzing itself.
|
|
||||||
type Interface interface {
|
|
||||||
Fuzz(c Continue)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Continue can be passed to custom fuzzing functions to allow them to use
|
|
||||||
// the correct source of randomness and to continue fuzzing their members.
|
|
||||||
type Continue struct {
|
|
||||||
f *Fuzzer
|
|
||||||
|
|
||||||
// For convenience, Continue implements rand.Rand via embedding.
|
|
||||||
// Use this for generating any randomness if you want your fuzzing
|
|
||||||
// to be repeatable for a given seed.
|
|
||||||
*rand.Rand
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fuzz continues fuzzing obj. obj must be a pointer.
|
|
||||||
func (c Continue) Fuzz(obj interface{}) {
|
|
||||||
v := reflect.ValueOf(obj)
|
|
||||||
if v.Kind() != reflect.Ptr {
|
|
||||||
panic("needed ptr!")
|
|
||||||
}
|
|
||||||
v = v.Elem()
|
|
||||||
c.f.doFuzz(v, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// FuzzNoCustom continues fuzzing obj, except that any custom fuzz function for
|
|
||||||
// obj's type will not be called and obj will not be tested for fuzz.Interface
|
|
||||||
// conformance. This applies only to obj and not other instances of obj's
|
|
||||||
// type.
|
|
||||||
func (c Continue) FuzzNoCustom(obj interface{}) {
|
|
||||||
v := reflect.ValueOf(obj)
|
|
||||||
if v.Kind() != reflect.Ptr {
|
|
||||||
panic("needed ptr!")
|
|
||||||
}
|
|
||||||
v = v.Elem()
|
|
||||||
c.f.doFuzz(v, flagNoCustomFuzz)
|
|
||||||
}
|
|
||||||
|
|
||||||
// RandString makes a random string up to 20 characters long. The returned string
|
|
||||||
// may include a variety of (valid) UTF-8 encodings.
|
|
||||||
func (c Continue) RandString() string {
|
|
||||||
return randString(c.Rand)
|
|
||||||
}
|
|
||||||
|
|
||||||
// RandUint64 makes random 64 bit numbers.
|
|
||||||
// Weirdly, rand doesn't have a function that gives you 64 random bits.
|
|
||||||
func (c Continue) RandUint64() uint64 {
|
|
||||||
return randUint64(c.Rand)
|
|
||||||
}
|
|
||||||
|
|
||||||
// RandBool returns true or false randomly.
|
|
||||||
func (c Continue) RandBool() bool {
|
|
||||||
return randBool(c.Rand)
|
|
||||||
}
|
|
||||||
|
|
||||||
func fuzzInt(v reflect.Value, r *rand.Rand) {
|
|
||||||
v.SetInt(int64(randUint64(r)))
|
|
||||||
}
|
|
||||||
|
|
||||||
func fuzzUint(v reflect.Value, r *rand.Rand) {
|
|
||||||
v.SetUint(randUint64(r))
|
|
||||||
}
|
|
||||||
|
|
||||||
func fuzzTime(t *time.Time, c Continue) {
|
|
||||||
var sec, nsec int64
|
|
||||||
// Allow for about 1000 years of random time values, which keeps things
|
|
||||||
// like JSON parsing reasonably happy.
|
|
||||||
sec = c.Rand.Int63n(1000 * 365 * 24 * 60 * 60)
|
|
||||||
c.Fuzz(&nsec)
|
|
||||||
*t = time.Unix(sec, nsec)
|
|
||||||
}
|
|
||||||
|
|
||||||
var fillFuncMap = map[reflect.Kind]func(reflect.Value, *rand.Rand){
|
|
||||||
reflect.Bool: func(v reflect.Value, r *rand.Rand) {
|
|
||||||
v.SetBool(randBool(r))
|
|
||||||
},
|
|
||||||
reflect.Int: fuzzInt,
|
|
||||||
reflect.Int8: fuzzInt,
|
|
||||||
reflect.Int16: fuzzInt,
|
|
||||||
reflect.Int32: fuzzInt,
|
|
||||||
reflect.Int64: fuzzInt,
|
|
||||||
reflect.Uint: fuzzUint,
|
|
||||||
reflect.Uint8: fuzzUint,
|
|
||||||
reflect.Uint16: fuzzUint,
|
|
||||||
reflect.Uint32: fuzzUint,
|
|
||||||
reflect.Uint64: fuzzUint,
|
|
||||||
reflect.Uintptr: fuzzUint,
|
|
||||||
reflect.Float32: func(v reflect.Value, r *rand.Rand) {
|
|
||||||
v.SetFloat(float64(r.Float32()))
|
|
||||||
},
|
|
||||||
reflect.Float64: func(v reflect.Value, r *rand.Rand) {
|
|
||||||
v.SetFloat(r.Float64())
|
|
||||||
},
|
|
||||||
reflect.Complex64: func(v reflect.Value, r *rand.Rand) {
|
|
||||||
panic("unimplemented")
|
|
||||||
},
|
|
||||||
reflect.Complex128: func(v reflect.Value, r *rand.Rand) {
|
|
||||||
panic("unimplemented")
|
|
||||||
},
|
|
||||||
reflect.String: func(v reflect.Value, r *rand.Rand) {
|
|
||||||
v.SetString(randString(r))
|
|
||||||
},
|
|
||||||
reflect.UnsafePointer: func(v reflect.Value, r *rand.Rand) {
|
|
||||||
panic("unimplemented")
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// randBool returns true or false randomly.
|
|
||||||
func randBool(r *rand.Rand) bool {
|
|
||||||
if r.Int()&1 == 1 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
type charRange struct {
|
|
||||||
first, last rune
|
|
||||||
}
|
|
||||||
|
|
||||||
// choose returns a random unicode character from the given range, using the
|
|
||||||
// given randomness source.
|
|
||||||
func (r *charRange) choose(rand *rand.Rand) rune {
|
|
||||||
count := int64(r.last - r.first)
|
|
||||||
return r.first + rune(rand.Int63n(count))
|
|
||||||
}
|
|
||||||
|
|
||||||
var unicodeRanges = []charRange{
|
|
||||||
{' ', '~'}, // ASCII characters
|
|
||||||
{'\u00a0', '\u02af'}, // Multi-byte encoded characters
|
|
||||||
{'\u4e00', '\u9fff'}, // Common CJK (even longer encodings)
|
|
||||||
}
|
|
||||||
|
|
||||||
// randString makes a random string up to 20 characters long. The returned string
|
|
||||||
// may include a variety of (valid) UTF-8 encodings.
|
|
||||||
func randString(r *rand.Rand) string {
|
|
||||||
n := r.Intn(20)
|
|
||||||
runes := make([]rune, n)
|
|
||||||
for i := range runes {
|
|
||||||
runes[i] = unicodeRanges[r.Intn(len(unicodeRanges))].choose(r)
|
|
||||||
}
|
|
||||||
return string(runes)
|
|
||||||
}
|
|
||||||
|
|
||||||
// randUint64 makes random 64 bit numbers.
|
|
||||||
// Weirdly, rand doesn't have a function that gives you 64 random bits.
|
|
||||||
func randUint64(r *rand.Rand) uint64 {
|
|
||||||
return uint64(r.Uint32())<<32 | uint64(r.Uint32())
|
|
||||||
}
|
|
||||||
Loading…
Reference in New Issue