package main import ( "net/http" "github.com/emicklei/go-restful" ) func main() { // Create a new Container object container := restful.NewContainer() // Create a new WebService object under the container service := new(restful.WebService) // Define a route for the GET method on the root URL service.Route(service.GET("/").To(func(req *restful.Request, resp *restful.Response) { resp.Write([]byte("Hello, world!")) })) // Add the service to the container container.Add(service) // Start the HTTP server http.ListenAndServe(":8080", container) }
package main import ( "net/http" "github.com/emicklei/go-restful" ) type User struct { Name string Email string } func main() { // Create a new Container object with auto-generated Swagger documentation container := restful.NewContainer() container.EnableSwaggerUi("/docs/", "/swagger.json") // Create a new WebService object under the container with Swagger documentation options service := new(restful.WebService) service.Path("/users"). Consumes(restful.MIME_JSON). Produces(restful.MIME_JSON). ApiVersion("1.0"). Doc("Manage users"). Doc("All paths require authentication."). Doc("Use /authentication to get authenticated first.") // Define a route for the POST method on the "/users" URL service.Route(service.POST("").To(func(req *restful.Request, resp *restful.Response) { user := new(User) err := req.ReadEntity(user) if err != nil { resp.WriteErrorString(http.StatusBadRequest, err.Error()) return } resp.WriteEntity(user) }). Doc("Create a new user"). Reads(User{}). Writes(User{})) // Add the service to the container container.Add(service) // Start the HTTP server http.ListenAndServe(":8080", container) }This example also creates a new `Container` and then adds a single `WebService` to it. However, this `WebService` defines a more complex route for the `POST` method on the "/users" URL that accepts a JSON payload representing a new user, creates the user, and then returns the same JSON representation in the response. Additionally, this `WebService` specifies various Swagger documentation options to generate documentation for the API.