package main import ( "net/http" "github.com/emicklei/go-restful" ) func main() { ws := new(restful.WebService) ws.Route(ws.GET("/hello").To(hello)) restful.Add(ws) http.ListenAndServe(":8080", nil) } func hello(req *restful.Request, resp *restful.Response) { resp.Write([]byte("Hello, world!")) }
package main import ( "encoding/json" "net/http" "github.com/emicklei/go-restful" ) type User struct { Name string `json:"name"` Age int `json:"age"` } var users = []User{ {Name: "Alice", Age: 25}, {Name: "Bob", Age: 30}, {Name: "Charlie", Age: 35}, } func main() { ws := new(restful.WebService) ws.Route(ws.GET("/users").To(getUsers)) restful.Add(ws) http.ListenAndServe(":8080", nil) } func getUsers(req *restful.Request, resp *restful.Response) { resp.WriteHeaderAndEntity(http.StatusOK, users) }In this example, we define an endpoint using the `GET` method that returns a list of users in JSON format. The `getUsers` function is called when a GET request is made to `/users`, and it writes the `users` variable (a slice of `User` structs) to the response as JSON. In both examples, we use the go-restful package to create a new `restful.WebService` and define an endpoint using the `GET` method. We then register the web service using the `restful.Add` function and start an HTTP server that listens on port 8080. Finally, we define a function that handles the GET request and writes a response using the `resp` parameter.