From b7d952cfe9ff3f82178a19c82bd271b2ce32f8d8 Mon Sep 17 00:00:00 2001 From: ernest Date: Wed, 21 Oct 2020 11:24:44 +0200 Subject: [PATCH] add encoding example to test issue #449 --- examples/restful-std-encoding.go | 98 ++++++++++++++++++++++++++++++++ go.mod | 2 + 2 files changed, 100 insertions(+) create mode 100644 examples/restful-std-encoding.go diff --git a/examples/restful-std-encoding.go b/examples/restful-std-encoding.go new file mode 100644 index 00000000..dadbef59 --- /dev/null +++ b/examples/restful-std-encoding.go @@ -0,0 +1,98 @@ +package main + +import ( + "log" + "net/http" + + "github.com/emicklei/go-restful" +) + +type User struct { + ID int + Active bool +} + +func main() { + restful.Add(NewUserService()) + restful.DefaultContainer.EnableContentEncoding(true) + log.Print("start listening on localhost:8080") + log.Fatal(http.ListenAndServe(":8080", nil)) +} + +func NewUserService() *restful.WebService { + ws := new(restful.WebService) + ws. + Path("/users"). + Consumes(restful.MIME_JSON). + Produces(restful.MIME_JSON) + ws.Route(ws.GET("/").To(listUsers)) + return ws +} + +// curl -vvv -H accept-encoding:gzip http://localhost:8080/users +// curl -vvv http://localhost:8080/users +func listUsers(request *restful.Request, response *restful.Response) { + users := []User{ + User{ + ID: 1, + Active: true, + }, + User{ + ID: 2, + Active: false, + }, + } + response.WriteEntity(users) +} + +/** +~/go/src/github.com/emicklei/go-restful (v3 *=) +$ curl -vvv -H accept-encoding:gzip http://localhost:8080/users +* Trying ::1... +* TCP_NODELAY set +* Connected to localhost (::1) port 8080 (#0) +> GET /users HTTP/1.1 +> Host: localhost:8080 +> User-Agent: curl/7.54.0 +> Accept: */ /* +> accept-encoding:gzip +> +< HTTP/1.1 200 OK +< Content-Encoding: gzip +< Content-Type: application/json +< Date: Wed, 21 Oct 2020 09:20:49 GMT +< Content-Length: 94 +< +��1 +1�������i��na��A,$��Ҙ&���=���nE࣍>����S�"���tp/m�ޯ�/��� +* Connection #0 to host localhost left intact +���?��I +**/ + +/** +$ curl -vvv http://localhost:8080/users +* Trying ::1... +* TCP_NODELAY set +* Connected to localhost (::1) port 8080 (#0) +> GET /users HTTP/1.1 +> Host: localhost:8080 +> User-Agent: curl/7.54.0 +> Accept: */ /* +> +< HTTP/1.1 200 OK +< Content-Type: application/json +< Date: Wed, 21 Oct 2020 09:23:13 GMT +< Content-Length: 73 +< +[ + { + "ID": 1, + "Active": true + }, + { + "ID": 2, + "Active": false + } +* Connection #0 to host localhost left intact +] +**/ diff --git a/go.mod b/go.mod index 325c09bc..1c73b310 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module github.com/emicklei/go-restful/v3 go 1.13 + +require github.com/emicklei/go-restful v2.14.2+incompatible // indirect