Last active
December 27, 2015 23:49
-
-
Save viblo/7409083 to your computer and use it in GitHub Desktop.
global response object with swagger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"net/http" | |
"github.com/emicklei/go-restful" | |
"github.com/emicklei/go-restful/swagger" | |
) | |
type Response struct { | |
Code int `json:"code"` | |
Data *Objects `json:"data"` | |
} | |
type Objects struct { | |
Users *[]User `json:"users,omitempty"` | |
Items *[]Item `json:"items,omitempty"` | |
} | |
type User struct { | |
Id, Name string | |
Phone struct { | |
Country string | |
Number string | |
} | |
} | |
type Item struct { | |
Id, Name string | |
} | |
func findUser(request *restful.Request, response *restful.Response) { | |
response.WriteErrorString(http.StatusNotFound, "Not implemented") | |
} | |
func findItem(request *restful.Request, response *restful.Response) { | |
response.WriteErrorString(http.StatusNotFound, "Not implemented") | |
} | |
func main() { | |
wsContainer := restful.NewContainer() | |
ws := new(restful.WebService) | |
//ws.Path("/root") | |
ws.Route(ws.GET("users/{id}").To(findUser). | |
// docs | |
Doc("get a user"). | |
Param(ws.PathParameter("id", "identifier of the user").DataType("string")). | |
Writes(Response{Data: &Objects{Users: &[]User{}}})) // on the response | |
ws.Route(ws.GET("items/{id}").To(findItem). | |
// docs | |
Doc("get item by id"). | |
Param(ws.PathParameter("id", "identifier of the item").DataType("string")). | |
Writes(Response{Data: &Objects{Items: &[]Item{}}})) // on the response | |
wsContainer.Add(ws) | |
config := swagger.Config{ | |
WebServices: wsContainer.RegisteredWebServices(), // you control what services are visible | |
WebServicesUrl: "http://localhost:8080", | |
ApiPath: "/apidocs.json", | |
// Optionally, specifiy where the UI is located | |
SwaggerPath: "/apidocs/", | |
SwaggerFilePath: "/Users/blomqvist/go-test/swagger-ui/dist"} | |
swagger.RegisterSwaggerService(config, wsContainer) | |
server := &http.Server{Addr: ":8080", Handler: wsContainer} | |
log.Fatal(server.ListenAndServe()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment