func main() { flag.Parse() log.Printf("using store: %s\n", storePath) store := libmachine.NewFilestore(storePath, "", "") m, err := libmachine.New(store) if err != nil { log.Fatal(err) } mcn = m wsContainer := restful.NewContainer() h := HostResource{} h.Register(wsContainer) config := swagger.Config{ WebServices: wsContainer.RegisteredWebServices(), WebServicesUrl: "http://localhost:8080", ApiPath: "/apidocs.json", SwaggerPath: "/apidocs/", SwaggerFilePath: "swagger"} swagger.RegisterSwaggerService(config, wsContainer) log.Printf("start listening on localhost:8080") server := &http.Server{Addr: ":8080", Handler: wsContainer} log.Fatal(server.ListenAndServe()) }
func main() { // to see what happens in the package, uncomment the following //restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) wsContainer := restful.NewContainer() u := UserResource{map[string]User{}} u.Register(wsContainer) // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. 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/emicklei/xProjects/swagger-ui/dist"} swagger.RegisterSwaggerService(config, wsContainer) log.Printf("start listening on localhost:8080") server := &http.Server{Addr: ":8080", Handler: wsContainer} log.Fatal(server.ListenAndServe()) }
func runRestAPI(wsContainer *restful.Container) { config := swagger.Config{ WebServices: wsContainer.RegisteredWebServices(), WebServicesUrl: "/", // host + port, ApiPath: "/forewind/security.json", SwaggerPath: "/forewind/doc/", SwaggerFilePath: "./dist", // TODO set it Title: "libsecurity-go", // TODO set it Description: "The libsecurity-go tool is for", } swagger.RegisterSwaggerService(config, wsContainer) if *generateJSONFlag { go generateJSON(config.ApiPath, config.SwaggerFilePath+"/") } log.Printf("start listening on %v", *host) var err error if strings.HasPrefix(strings.ToLower(*protocol), httpsStr) { err = http.ListenAndServeTLS(*host, *sslServerCert, *sslServerKey, wsContainer) } else { err = http.ListenAndServe(*host, wsContainer) } if err != nil { log.Fatal(err) } }
// InstallSwaggerAPI installs the /swaggerapi/ endpoint to allow schema discovery // and traversal. It is optional to allow consumers of the Kubernetes master to // register their own web services into the Kubernetes mux prior to initialization // of swagger, so that other resource types show up in the documentation. func (m *Master) InstallSwaggerAPI() { hostAndPort := m.externalHost protocol := "https://" // TODO: this is kind of messed up, we should just pipe in the full URL from the outside, rather // than guessing at it. if len(m.externalHost) == 0 && m.clusterIP != nil { host := m.clusterIP.String() if m.publicReadWritePort != 0 { hostAndPort = net.JoinHostPort(host, strconv.Itoa(m.publicReadWritePort)) } else { // Use the read only port. hostAndPort = net.JoinHostPort(host, strconv.Itoa(m.publicReadOnlyPort)) protocol = "http://" } } webServicesUrl := protocol + hostAndPort // Enable swagger UI and discovery API swaggerConfig := swagger.Config{ WebServicesUrl: webServicesUrl, WebServices: m.handlerContainer.RegisteredWebServices(), ApiPath: "/swaggerapi/", SwaggerPath: "/swaggerui/", SwaggerFilePath: "/swagger-ui/", } swagger.RegisterSwaggerService(swaggerConfig, m.handlerContainer) }
func enableSwagger() { config := swagger.Config{ WebServices: restful.DefaultContainer.RegisteredWebServices(), // you control what services are visible ApiPath: "/apidocs.json", SwaggerPath: "/apidocs/", SwaggerFilePath: "swagger-ui/"} swagger.RegisterSwaggerService(config, restful.DefaultContainer) }
func (a *Application) initSwagger() { swconfig := swagger.Config{ WebServices: a.Container.RegisteredWebServices(), WebServicesUrl: a.Config.Get("swagger.ws_url").(string), ApiPath: a.Config.Get("swagger.api_path").(string), SwaggerPath: a.Config.Get("swagger.url").(string), SwaggerFilePath: a.Config.Get("swagger.file_path").(string), } swagger.RegisterSwaggerService(swconfig, a.Container) }
func Swagger(wsContainer *restful.Container, apiPath, swaggerPath, swaggerFilepath string) { config := swagger.Config{ WebServices: wsContainer.RegisteredWebServices(), // you control what services are visible ApiPath: apiPath, // Optionally, specifiy where the UI is located SwaggerPath: swaggerPath, SwaggerFilePath: swaggerFilepath, } swagger.RegisterSwaggerService(config, wsContainer) }
func main() { flag.Parse() log.Printf("loading configuration from [%s]", *propertiesFile) var err error if props, err = properties.LoadFile(*propertiesFile, properties.UTF8); err != nil { log.Fatalf("[soysos][error] Unable to read properties:%v\n", err) } addr := props.MustGet("http.server.host") + ":" + props.MustGet("http.server.port") basePath := "http://" + addr SwaggerPath = props.GetString("swagger.path", "") cmap := make(map[string]CatFact) cmap["Lion"] = CatFact{"", "Lion", "Lions have sharp teef :D"} cat := CatResource{cmap} root := RootResource{SwaggerPath} user := UserResource{} wsContainer := restful.NewContainer() wsContainer.Filter(GlobalLogging) wsContainer.Filter(enableCORS) restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) cat.Register(wsContainer) root.Register(wsContainer) user.Register(wsContainer) config := swagger.Config{ WebServices: wsContainer.RegisteredWebServices(), WebServicesUrl: basePath, ApiPath: "/apidocs.json", SwaggerPath: SwaggerPath, SwaggerFilePath: props.GetString("swagger.file.path", "")} swagger.RegisterSwaggerService(config, wsContainer) cors := restful.CrossOriginResourceSharing{ AllowedHeaders: []string{"Accept", "Authorization"}, AllowedMethods: []string{"GET"}, CookiesAllowed: false, Container: wsContainer} //wsContainer.Filter(wsContainer.OPTIONSFilter) wsContainer.Filter(cors.Filter) server := &http.Server{Addr: addr, Handler: wsContainer} log.Printf("start listening on %s", basePath) log.Fatal(server.ListenAndServe()) }
func main() { datastore, err := kv.Open("mpush.kvdb", &kv.Options{}) if err != nil { log.Fatal(err) } defer datastore.Close() wsContainer := restful.NewContainer() restful.Filter(globalLogging) dsl := DistributionListResource{datastore} dsl.Register(wsContainer) wsPush := new(restful.WebService) wsPush.Path("/api/push") wsPush.Route(wsPush.POST(""). Consumes("application/x-www-form-urlencoded"). To(func(request *restful.Request, response *restful.Response) { pushHandler(request, response, datastore) }). // docs Doc("push to a distribution list"). Param(wsPush.BodyParameter("List", "list to send to").DataType("string")). Param(wsPush.BodyParameter("Title", "title of notification").DataType("string")). Param(wsPush.BodyParameter("Body", "body of notification").DataType("string")). Reads(PushNotification{})) // from the request wsContainer.Add(wsPush) // static files wsStatic := new(restful.WebService) wsStatic.Route(wsStatic.GET("/static/{resource}").To(staticFromPathParam)) wsStatic.Route(wsStatic.GET("/static").To(staticFromQueryParam)) wsContainer.Add(wsStatic) // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. 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: "/home/dgryski/work/src/cvs/swagger-ui/dist"} swagger.RegisterSwaggerService(config, wsContainer) log.Printf("start listening on localhost:8080") server := &http.Server{Addr: ":8080", Handler: wsContainer} log.Fatal(server.ListenAndServe()) }
// InstallSwaggerAPI installs the /swaggerapi/ endpoint to allow schema discovery // and traversal. It is optional to allow consumers of the Kubernetes master to // register their own web services into the Kubernetes mux prior to initialization // of swagger, so that other resource types show up in the documentation. func (m *Master) InstallSwaggerAPI() { // Enable swagger UI and discovery API swaggerConfig := swagger.Config{ WebServicesUrl: m.readWriteServer, WebServices: m.handlerContainer.RegisteredWebServices(), // TODO: Parameterize the path? ApiPath: "/swaggerapi/", SwaggerPath: "/swaggerui/", SwaggerFilePath: "/swagger-ui/", } swagger.RegisterSwaggerService(swaggerConfig, m.handlerContainer) }
func main() { flag.Parse() // to see what happens in the package, uncomment the following //restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) wsContainer := NewHandlerContainer() var application app.Application var err error // Check configuration file was given if configfile == "" { fmt.Fprintln(os.Stderr, "Please provide configuration file") os.Exit(1) } // Setup a new applications for common APIs appCollection := conf.LoadAppConfiguration(configfile) fmt.Println(appCollection) for _, element := range appCollection.Apps { fmt.Println("Initializing..", element) application, err = app.InitApp(element.Name, element.ConfigFilePath) err = application.SetRoutes(wsContainer) if err != nil { fmt.Println("Unable to create http server endpoints") os.Exit(1) } } // Install the Swagger Service which provides a nice Web UI on your REST API // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. //fmt.Println("appCollection.Swagger.Status", appCollection.Swagger.Status) if appCollection.Swagger.Status { config := swagger.Config{} config.WebServices = wsContainer.RegisteredWebServices() config.WebServicesUrl = appCollection.Swagger.WebServicesUrl config.ApiPath = appCollection.Swagger.ApiPath config.SwaggerPath = appCollection.Swagger.SwaggerPath config.SwaggerFilePath = appCollection.Swagger.SwaggerFilePath swagger.RegisterSwaggerService(config, wsContainer) } log.Printf("start listening on localhost:8080") server := &http.Server{Addr: ":8080", Handler: wsContainer} log.Fatal(server.ListenAndServe()) }
// InstallSwaggerAPI installs the /swaggerapi/ endpoint to allow schema discovery // and traversal. It is optional to allow consumers of the Kubernetes GenericAPIServer to // register their own web services into the Kubernetes mux prior to initialization // of swagger, so that other resource types show up in the documentation. func (s *GenericAPIServer) InstallSwaggerAPI() { hostAndPort := s.ExternalAddress protocol := "https://" webServicesUrl := protocol + hostAndPort // Enable swagger UI and discovery API swaggerConfig := swagger.Config{ WebServicesUrl: webServicesUrl, WebServices: s.HandlerContainer.RegisteredWebServices(), ApiPath: "/swaggerapi/", SwaggerPath: "/swaggerui/", SwaggerFilePath: "/swagger-ui/", } swagger.RegisterSwaggerService(swaggerConfig, s.HandlerContainer) }
func StartRestAPIServer() { registerWebServiceHistoricalReplicationControllerMetric() registerWebServiceHistoricalReplicationController() registerWebServiceHistoricalEvent() registerWebServiceHealthCheck() registerWebServiceAuditLog() registerWebServiceBuildLog() // Place the method+path to description mapping to map for audit for _, rws := range restful.DefaultContainer.RegisteredWebServices() { for _, r := range rws.Routes() { audit.AddDescription(r.String(), r.Doc) } } // You can install the Swagger Service which provides a nice Web UI on your REST API // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. config := swagger.Config{ WebServices: restful.DefaultContainer.RegisteredWebServices(), // you control what services are visible //WebServicesUrl: "http://localhost:8080", ApiPath: "/apidocs.json", // Optionally, specifiy where the UI is located SwaggerPath: "/apidocs/", SwaggerFilePath: "swaggerui"} swagger.RegisterSwaggerService(config, restful.DefaultContainer) restapiPort, ok := configuration.LocalConfiguration.GetInt("restapiPort") if ok == false { log.Error("Can't find restapiPort") panic("Can't find restapiPort") } server := &http.Server{Addr: ":" + strconv.Itoa(restapiPort), Handler: restful.DefaultContainer} certificate, ok := configuration.LocalConfiguration.GetString("certificate") if ok == false { log.Error("Can't find certificate path") panic("Can't find certificate path") } key, ok := configuration.LocalConfiguration.GetString("key") if ok == false { log.Error("Can't find certificate path") panic("Can't find key path") } server.ListenAndServeTLS(certificate, key) }
// Install adds the SwaggerUI webservice to the given mux. func (s Swagger) Install(c *mux.APIContainer) { swagger.RegisterSwaggerService(swagger.Config{ WebServicesUrl: "https://" + s.ExternalAddress, WebServices: c.RegisteredWebServices(), ApiPath: "/swaggerapi/", SwaggerPath: "/swaggerui/", SwaggerFilePath: "/swagger-ui/", SchemaFormatHandler: func(typeName string) string { switch typeName { case "metav1.Time", "*metav1.Time": return "date-time" } return "" }, }, c.Container) }
func main() { // to see what happens in the package, uncomment the following restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) wsContainer := restful.NewContainer() // Root var root = resources.RootResource{} root.Register(wsContainer) // lookups resourcesv1.EmploymentTypesResource{}.Register(wsContainer) resourcesv1.TagsResource{}.Register(wsContainer) resourcesv1.PostsResource{}.Register(wsContainer) resourcesv1.ScrumTeamsResource{}.Register(wsContainer) resourcesv1.SprintsResource{}.Register(wsContainer) // Add container filter to enable CORS cors := restful.CrossOriginResourceSharing{ ExposeHeaders: []string{"X-My-Header"}, AllowedHeaders: []string{"Content-Type"}, CookiesAllowed: false, Container: wsContainer} wsContainer.Filter(cors.Filter) // Add container filter to respond to OPTIONS wsContainer.Filter(wsContainer.OPTIONSFilter) // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. config := swagger.Config{ WebServices: wsContainer.RegisteredWebServices(), // you control what services are visible WebServicesUrl: "http://localhost:5555", ApiPath: "/apidocs.json", // Optionally, specifiy where the UI is located SwaggerPath: "/apidocs/", SwaggerFilePath: "./swagger-ui/dist"} swagger.RegisterSwaggerService(config, wsContainer) log.Printf("start listening on localhost:5555") server := &http.Server{Addr: ":5555", Handler: wsContainer} log.Fatal(server.ListenAndServe()) }
// New creates a new Docker remote API service instance in the form of an // http.Handler. func New(impl api.Service, swaggerFilePath string) http.Handler { baseSrv := newBaseServer(impl) containersSrv := newContainersServer(impl) container := restful.NewContainer() container.Add(baseSrv.WebService) container.Add(containersSrv.WebService) swaggerConf := swagger.Config{ WebServices: container.RegisteredWebServices(), ApiPath: "/docs/apidocs.json", SwaggerPath: "/docs/swagger/", SwaggerFilePath: swaggerFilePath, } swagger.RegisterSwaggerService(swaggerConf, container) return container }
func StartServer(e *env.Env) { restful.SetLogger(e.Log) aEnv := ApiEnv{e} wsContainer := restful.NewContainer() // Enable gzip encoding //wsContainer.EnableContentEncoding(true) // Request logging wsContainer.Filter(aEnv.ReqLogger) // Route error handling wsContainer.ServiceErrorHandler(aEnv.WriteServiceErrorJson) // Register apis aEnv.registerUserApis(wsContainer) aEnv.registerPostApis(wsContainer) aEnv.registerVoteApis(wsContainer) // Some bullshit so ServiceErrorHandler works... errWs := new(restful.WebService) errWs.Path("/") wsContainer.Add(errWs) if e.SwaggerPath != "" { config := swagger.Config{ WebServices: wsContainer.RegisteredWebServices(), ApiPath: "/swagger/apidocs.json", SwaggerPath: "/swagger/apidocs/", SwaggerFilePath: e.SwaggerPath, } //Container just for swagger swContainer := restful.NewContainer() swagger.RegisterSwaggerService(config, swContainer) http.Handle("/swagger/", swContainer) } http.Handle("/", wsContainer) e.Log.Info("[server/api] start listening on localhost:" + e.ApiPort) e.Log.Fatal(http.ListenAndServe(":"+e.ApiPort, nil)) }
//main - Application. func main() { log.Printf("Configuring container.") container := restful.NewContainer() container.Filter(filter.NCSACommonLogFormatLogger()) container.Add(webservice.TaskWebService()) log.Printf("Registering Swagger.") config := swagger.Config{ WebServices: container.RegisteredWebServices(), ApiPath: "/apidocs.json", ApiVersion: "1.0", Info: swagger.Info{Title: "hubertwo/go-todo", Description: "Simple TODO list manager in Go."}} swagger.RegisterSwaggerService(config, container) log.Printf("Starting server.") server := &http.Server{Addr: ":8080", Handler: container} log.Fatal(server.ListenAndServe()) }
// InstallSwaggerAPI installs the /swaggerapi/ endpoint to allow schema discovery // and traversal. It is optional to allow consumers of the Kubernetes master to // register their own web services into the Kubernetes mux prior to initialization // of swagger, so that other resource types show up in the documentation. func (m *Master) InstallSwaggerAPI() { webServicesUrl := "" // Use the secure read write port, if available. if m.publicReadWritePort != 0 { webServicesUrl = "https://" + net.JoinHostPort(m.publicIP.String(), strconv.Itoa(m.publicReadWritePort)) } else { // Use the read only port. webServicesUrl = "http://" + net.JoinHostPort(m.publicIP.String(), strconv.Itoa(m.publicReadOnlyPort)) } // Enable swagger UI and discovery API swaggerConfig := swagger.Config{ WebServicesUrl: webServicesUrl, WebServices: m.handlerContainer.RegisteredWebServices(), ApiPath: "/swaggerapi/", SwaggerPath: "/swaggerui/", SwaggerFilePath: "/swagger-ui/", } swagger.RegisterSwaggerService(swaggerConfig, m.handlerContainer) }
func main() { err := config.LoadGlobalConfig() if err != nil { log.Fatalf("Failed to load config: %v", err) } go images.StartGC() go images.StartImageUpdate() // to see what happens in the package, uncomment the following //restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) wsContainer := restful.NewContainer() u := DockerResource{url: "unix:///var/run/docker.sock"} u.Register(wsContainer) wsContainer.Filter(func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { resp.AddHeader("Access-Control-Allow-Origin", "*") chain.ProcessFilter(req, resp) }) wsContainer.Handle("/", http.FileServer(assetFS())) // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. 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/emicklei/xProjects/swagger-ui/dist"} swagger.RegisterSwaggerService(config, wsContainer) log.Printf("start listening on localhost:8080") server := &http.Server{Addr: ":8080", Handler: wsContainer} log.Fatal(server.ListenAndServe()) }
// InstallSwaggerAPI installs the /swaggerapi/ endpoint to allow schema discovery // and traversal. It is optional to allow consumers of the Kubernetes GenericAPIServer to // register their own web services into the Kubernetes mux prior to initialization // of swagger, so that other resource types show up in the documentation. func (s *GenericAPIServer) InstallSwaggerAPI() { hostAndPort := s.ExternalAddress protocol := "https://" webServicesUrl := protocol + hostAndPort // Enable swagger UI and discovery API swaggerConfig := swagger.Config{ WebServicesUrl: webServicesUrl, WebServices: s.HandlerContainer.RegisteredWebServices(), ApiPath: "/swaggerapi/", SwaggerPath: "/swaggerui/", SwaggerFilePath: "/swagger-ui/", SchemaFormatHandler: func(typeName string) string { switch typeName { case "unversioned.Time", "*unversioned.Time": return "date-time" } return "" }, } swagger.RegisterSwaggerService(swaggerConfig, s.HandlerContainer) }
func main() { wsContainer := restful.NewContainer() u := UserResource{map[string]User{}} u.Register(wsContainer) // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. 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/emicklei/Downloads/swagger-ui-1.1.7"} swagger.RegisterSwaggerService(config, wsContainer) log.Printf("start listening on localhost:8080") server := &http.Server{Addr: ":8080", Handler: wsContainer} log.Fatal(server.ListenAndServe()) }
func main() { ws := new(restful.WebService) ws.Path("/itrain").Consumes(restful.MIME_JSON).Produces(restful.MIME_JSON) ws.Route(ws.GET("/version"). To(report_version). Doc("get itrain version number"). Operation("version")) ws.Route(ws.GET("/report_inverter"). To(report_inverter). Doc("get inverter report data"). Operation("report_inverter"). Param(ws.QueryParameter("sd", "startdate"))) restful.Add(ws) config := swagger.Config{ WebServices: restful.DefaultContainer.RegisteredWebServices(), // you control what services are visible WebServicesUrl: "/", ApiPath: "/apidocs.json", // specifiy where the UI is located SwaggerPath: "/apidocs/", SwaggerFilePath: "./swaggerui"} swagger.RegisterSwaggerService(config, restful.DefaultContainer) var ( hostname string = "127.0.0.1" port int = 8080 ) // Listen on hostname:port fmt.Printf("Listening on %s:%d...\n", hostname, port) err := http.ListenAndServe(fmt.Sprintf("%s:%d", hostname, port), nil) if err != nil { log.Fatal("Error: ", err) } }
func main() { // initialize postgres backend conn, err := api.NewDB("postgres", dbInfo) fatal(err) defer conn.Close() // initialize token validator v, err := api.GoogleTokenValidator(webClientID) fatal(err) // Add db and token validator to user resource userResource := &user.Resource{conn, v} // Register container wsContainer := restful.NewContainer() user.RegisterContainer(wsContainer, userResource) // Setup api docs config := swagger.Config{ ApiVersion: "1", WebServices: wsContainer.RegisteredWebServices(), WebServicesUrl: swaggerAPIURL, ApiPath: "/apidocs.json", SwaggerPath: "/apidocs/", SwaggerFilePath: swaggerFilePath} swagger.RegisterSwaggerService(config, wsContainer) // Start server log.Printf("listening on localhost:%s", port) server := &http.Server{Addr: fmt.Sprintf(":%s", port), Handler: wsContainer} if tls { log.Fatal(server.ListenAndServeTLS(tlsCert, tlsKey)) } else { log.Fatal(server.ListenAndServe()) } }
func main() { ws := new(restful.WebService) ws.Path("/books") ws.Consumes(restful.MIME_JSON, restful.MIME_XML) ws.Produces(restful.MIME_JSON, restful.MIME_XML) restful.Add(ws) ws.Route(ws.GET("/{medium}").To(noop). Doc("Search all books"). Param(ws.PathParameter("medium", "digital or paperback").DataType("string")). Param(ws.QueryParameter("language", "en,nl,de").DataType("string")). Param(ws.HeaderParameter("If-Modified-Since", "last known timestamp").DataType("datetime")). Do(returns200, returns500)) ws.Route(ws.PUT("/{medium}").To(noop). Doc("Add a new book"). Param(ws.PathParameter("medium", "digital or paperback").DataType("string")). Reads(Book{})) // You can install the Swagger Service which provides a nice Web UI on your REST API // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. config := swagger.Config{ WebServices: restful.DefaultContainer.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/emicklei/xProjects/swagger-ui/dist"} swagger.RegisterSwaggerService(config, restful.DefaultContainer) log.Printf("start listening on localhost:8080") server := &http.Server{Addr: ":8080", Handler: restful.DefaultContainer} log.Fatal(server.ListenAndServe()) }
// InstallSwaggerAPI installs the /swaggerapi/ endpoint to allow schema discovery // and traversal. It is optional to allow consumers of the Kubernetes GenericAPIServer to // register their own web services into the Kubernetes mux prior to initialization // of swagger, so that other resource types show up in the documentation. func (s *GenericAPIServer) InstallSwaggerAPI() { hostAndPort := s.externalHost protocol := "https://" // TODO: this is kind of messed up, we should just pipe in the full URL from the outside, rather // than guessing at it. if len(s.externalHost) == 0 && s.ClusterIP != nil { host := s.ClusterIP.String() if s.PublicReadWritePort != 0 { hostAndPort = net.JoinHostPort(host, strconv.Itoa(s.PublicReadWritePort)) } } webServicesUrl := protocol + hostAndPort // Enable swagger UI and discovery API swaggerConfig := swagger.Config{ WebServicesUrl: webServicesUrl, WebServices: s.HandlerContainer.RegisteredWebServices(), ApiPath: "/swaggerapi/", SwaggerPath: "/swaggerui/", SwaggerFilePath: "/swagger-ui/", } swagger.RegisterSwaggerService(swaggerConfig, s.HandlerContainer) }
// Run launches the OpenShift master. It takes optional installers that may install additional endpoints into the server. // All endpoints get configured CORS behavior // Protected installers' endpoints are protected by API authentication and authorization. // Unprotected installers' endpoints do not have any additional protection added. func (c *MasterConfig) Run(protected []APIInstaller, unprotected []APIInstaller) { var extra []string safe := kmaster.NewHandlerContainer(http.NewServeMux()) open := kmaster.NewHandlerContainer(http.NewServeMux()) // enforce authentication on protected endpoints protected = append(protected, APIInstallFunc(c.InstallProtectedAPI)) for _, i := range protected { extra = append(extra, i.InstallAPI(safe)...) } handler := c.authorizationFilter(safe) handler = authenticationHandlerFilter(handler, c.Authenticator, c.getRequestContextMapper()) handler = namespacingFilter(handler, c.getRequestContextMapper()) handler = cacheControlFilter(handler, "no-store") // protected endpoints should not be cached // unprotected resources unprotected = append(unprotected, APIInstallFunc(c.InstallUnprotectedAPI)) for _, i := range unprotected { extra = append(extra, i.InstallAPI(open)...) } handler = indexAPIPaths(handler) open.Handle("/", handler) // install swagger swaggerConfig := swagger.Config{ WebServicesUrl: c.Options.MasterPublicURL, WebServices: append(safe.RegisteredWebServices(), open.RegisteredWebServices()...), ApiPath: swaggerAPIPrefix, PostBuildHandler: customizeSwaggerDefinition, } // log nothing from swagger swagger.LogInfo = func(format string, v ...interface{}) {} swagger.RegisterSwaggerService(swaggerConfig, open) extra = append(extra, fmt.Sprintf("Started Swagger Schema API at %%s%s", swaggerAPIPrefix)) handler = open // add CORS support if origins := c.ensureCORSAllowedOrigins(); len(origins) != 0 { handler = apiserver.CORS(handler, origins, nil, nil, "true") } if c.WebConsoleEnabled() { handler = assetServerRedirect(handler, c.Options.AssetConfig.PublicURL) } // Make the outermost filter the requestContextMapper to ensure all components share the same context if contextHandler, err := kapi.NewRequestContextFilter(c.getRequestContextMapper(), handler); err != nil { glog.Fatalf("Error setting up request context filter: %v", err) } else { handler = contextHandler } // TODO: MaxRequestsInFlight should be subdivided by intent, type of behavior, and speed of // execution - updates vs reads, long reads vs short reads, fat reads vs skinny reads. if c.Options.ServingInfo.MaxRequestsInFlight > 0 { sem := make(chan bool, c.Options.ServingInfo.MaxRequestsInFlight) handler = apiserver.MaxInFlightLimit(sem, longRunningRE, handler) } c.serve(handler, extra) // Attempt to verify the server came up for 20 seconds (100 tries * 100ms, 100ms timeout per try) cmdutil.WaitForSuccessfulDial(c.TLS, c.Options.ServingInfo.BindNetwork, c.Options.ServingInfo.BindAddress, 100*time.Millisecond, 100*time.Millisecond, 100) }
// Run launches the OpenShift master. It takes optional installers that may install additional endpoints into the server. // All endpoints get configured CORS behavior // Protected installers' endpoints are protected by API authentication and authorization. // Unprotected installers' endpoints do not have any additional protection added. func (c *MasterConfig) Run(protected []APIInstaller, unprotected []APIInstaller) { var extra []string safe := kmaster.NewHandlerContainer(http.NewServeMux()) open := kmaster.NewHandlerContainer(http.NewServeMux()) // enforce authentication on protected endpoints protected = append(protected, APIInstallFunc(c.InstallProtectedAPI)) for _, i := range protected { extra = append(extra, i.InstallAPI(safe)...) } handler := c.authorizationFilter(safe) handler = authenticationHandlerFilter(handler, c.Authenticator, c.getRequestContextMapper()) handler = namespacingFilter(handler, c.getRequestContextMapper()) handler = cacheControlFilter(handler, "no-store") // protected endpoints should not be cached // unprotected resources unprotected = append(unprotected, APIInstallFunc(c.InstallUnprotectedAPI)) for _, i := range unprotected { extra = append(extra, i.InstallAPI(open)...) } handler = indexAPIPaths(handler) open.Handle("/", handler) // install swagger swaggerConfig := swagger.Config{ WebServicesUrl: c.Options.MasterPublicURL, WebServices: append(safe.RegisteredWebServices(), open.RegisteredWebServices()...), ApiPath: swaggerAPIPrefix, PostBuildHandler: customizeSwaggerDefinition, } // log nothing from swagger swagger.LogInfo = func(format string, v ...interface{}) {} swagger.RegisterSwaggerService(swaggerConfig, open) extra = append(extra, fmt.Sprintf("Started Swagger Schema API at %%s%s", swaggerAPIPrefix)) handler = open // add CORS support if origins := c.ensureCORSAllowedOrigins(); len(origins) != 0 { handler = apiserver.CORS(handler, origins, nil, nil, "true") } if c.WebConsoleEnabled() { handler = assetServerRedirect(handler, c.Options.AssetConfig.PublicURL) } // Make the outermost filter the requestContextMapper to ensure all components share the same context if contextHandler, err := kapi.NewRequestContextFilter(c.getRequestContextMapper(), handler); err != nil { glog.Fatalf("Error setting up request context filter: %v", err) } else { handler = contextHandler } // TODO: MaxRequestsInFlight should be subdivided by intent, type of behavior, and speed of // execution - updates vs reads, long reads vs short reads, fat reads vs skinny reads. if c.Options.ServingInfo.MaxRequestsInFlight > 0 { sem := make(chan bool, c.Options.ServingInfo.MaxRequestsInFlight) handler = apiserver.MaxInFlightLimit(sem, longRunningRE, handler) } timeout := c.Options.ServingInfo.RequestTimeoutSeconds if timeout == -1 { timeout = 0 } server := &http.Server{ Addr: c.Options.ServingInfo.BindAddress, Handler: handler, ReadTimeout: time.Duration(timeout) * time.Second, WriteTimeout: time.Duration(timeout) * time.Second, MaxHeaderBytes: 1 << 20, } go util.Forever(func() { for _, s := range extra { glog.Infof(s, c.Options.ServingInfo.BindAddress) } if c.TLS { server.TLSConfig = &tls.Config{ // Change default from SSLv3 to TLSv1.0 (because of POODLE vulnerability) MinVersion: tls.VersionTLS10, // Populate PeerCertificates in requests, but don't reject connections without certificates // This allows certificates to be validated by authenticators, while still allowing other auth types ClientAuth: tls.RequestClientCert, ClientCAs: c.ClientCAs, } glog.Fatal(cmdutil.ListenAndServeTLS(server, c.Options.ServingInfo.BindNetwork, c.Options.ServingInfo.ServerCert.CertFile, c.Options.ServingInfo.ServerCert.KeyFile)) } else { glog.Fatal(server.ListenAndServe()) } }, 0) // Attempt to verify the server came up for 20 seconds (100 tries * 100ms, 100ms timeout per try) cmdutil.WaitForSuccessfulDial(c.TLS, c.Options.ServingInfo.BindNetwork, c.Options.ServingInfo.BindAddress, 100*time.Millisecond, 100*time.Millisecond, 100) // Create required policy rules if needed c.ensureComponentAuthorizationRules() // Ensure the default SCCs are created c.ensureDefaultSecurityContextConstraints() // Bind default roles for service accounts in the default namespace if needed c.ensureDefaultNamespaceServiceAccountRoles() // Create the infra namespace c.ensureOpenShiftInfraNamespace() // Create the shared resource namespace c.ensureOpenShiftSharedResourcesNamespace() }
// Run launches the OpenShift master. It takes optional installers that may install additional endpoints into the server. // All endpoints get configured CORS behavior // Protected installers' endpoints are protected by API authentication and authorization. // Unprotected installers' endpoints do not have any additional protection added. func (c *MasterConfig) Run(protected []APIInstaller, unprotected []APIInstaller) { var extra []string safe := genericapiserver.NewHandlerContainer(http.NewServeMux(), kapi.Codecs) open := genericapiserver.NewHandlerContainer(http.NewServeMux(), kapi.Codecs) // enforce authentication on protected endpoints protected = append(protected, APIInstallFunc(c.InstallProtectedAPI)) for _, i := range protected { msgs, err := i.InstallAPI(safe) if err != nil { glog.Fatalf("error installing api %v", err) } extra = append(extra, msgs...) } handler := c.versionSkewFilter(safe) handler = c.authorizationFilter(handler) handler = c.impersonationFilter(handler) // audit handler must comes before the impersonationFilter to read the original user handler = c.auditHandler(handler) handler = authenticationHandlerFilter(handler, c.Authenticator, c.getRequestContextMapper()) handler = namespacingFilter(handler, c.getRequestContextMapper()) handler = cacheControlFilter(handler, "no-store") // protected endpoints should not be cached // unprotected resources unprotected = append(unprotected, APIInstallFunc(c.InstallUnprotectedAPI)) for _, i := range unprotected { msgs, err := i.InstallAPI(open) if err != nil { glog.Fatalf("error installing api %v", err) } extra = append(extra, msgs...) } var kubeAPILevels []string if c.Options.KubernetesMasterConfig != nil { kubeAPILevels = configapi.GetEnabledAPIVersionsForGroup(*c.Options.KubernetesMasterConfig, kapi.GroupName) } handler = indexAPIPaths(c.Options.APILevels, kubeAPILevels, handler) open.Handle("/", handler) // install swagger swaggerConfig := swagger.Config{ WebServicesUrl: c.Options.MasterPublicURL, WebServices: append(safe.RegisteredWebServices(), open.RegisteredWebServices()...), ApiPath: swaggerAPIPrefix, PostBuildHandler: customizeSwaggerDefinition, } // log nothing from swagger swagger.LogInfo = func(format string, v ...interface{}) {} swagger.RegisterSwaggerService(swaggerConfig, open) extra = append(extra, fmt.Sprintf("Started Swagger Schema API at %%s%s", swaggerAPIPrefix)) openAPIConfig := openapi.Config{ SwaggerConfig: &swaggerConfig, IgnorePrefixes: []string{"/swaggerapi"}, Info: &spec.Info{ InfoProps: spec.InfoProps{ Title: "OpenShift API (with Kubernetes)", Version: version.Get().String(), License: &spec.License{ Name: "Apache 2.0 (ASL2.0)", URL: "http://www.apache.org/licenses/LICENSE-2.0", }, Description: heredoc.Doc(` OpenShift provides builds, application lifecycle, image content management, and administrative policy on top of Kubernetes. The API allows consistent management of those objects. All API operations are authenticated via an Authorization bearer token that is provided for service accounts as a generated secret (in JWT form) or via the native OAuth endpoint located at /oauth/authorize. Core infrastructure components may use client certificates that require no authentication. All API operations return a 'resourceVersion' string that represents the version of the object in the underlying storage. The standard LIST operation performs a snapshot read of the underlying objects, returning a resourceVersion representing a consistent version of the listed objects. The WATCH operation allows all updates to a set of objects after the provided resourceVersion to be observed by a client. By listing and beginning a watch from the returned resourceVersion, clients may observe a consistent view of the state of one or more objects. Note that WATCH always returns the update after the provided resourceVersion. Watch may be extended a limited time in the past - using etcd 2 the watch window is 1000 events (which on a large cluster may only be a few tens of seconds) so clients must explicitly handle the "watch to old error" by re-listing. Objects are divided into two rough categories - those that have a lifecycle and must reflect the state of the cluster, and those that have no state. Objects with lifecycle typically have three main sections: * 'metadata' common to all objects * a 'spec' that represents the desired state * a 'status' that represents how much of the desired state is reflected on the cluster at the current time Objects that have no state have 'metadata' but may lack a 'spec' or 'status' section. Objects are divided into those that are namespace scoped (only exist inside of a namespace) and those that are cluster scoped (exist outside of a namespace). A namespace scoped resource will be deleted when the namespace is deleted and cannot be created if the namespace has not yet been created or is in the process of deletion. Cluster scoped resources are typically only accessible to admins - resources like nodes, persistent volumes, and cluster policy. All objects have a schema that is a combination of the 'kind' and 'apiVersion' fields. This schema is additive only for any given version - no backwards incompatible changes are allowed without incrementing the apiVersion. The server will return and accept a number of standard responses that share a common schema - for instance, the common error type is 'unversioned.Status' (described below) and will be returned on any error from the API server. The API is available in multiple serialization formats - the default is JSON (Accept: application/json and Content-Type: application/json) but clients may also use YAML (application/yaml) or the native Protobuf schema (application/vnd.kubernetes.protobuf). Note that the format of the WATCH API call is slightly different - for JSON it returns newline delimited objects while for Protobuf it returns length-delimited frames (4 bytes in network-order) that contain a 'versioned.Watch' Protobuf object. See the OpenShift documentation at https://docs.openshift.org for more information. `), }, }, DefaultResponse: &spec.Response{ ResponseProps: spec.ResponseProps{ Description: "Default Response.", }, }, } err := openapi.RegisterOpenAPIService(&openAPIConfig, open) if err != nil { glog.Fatalf("Failed to generate open api spec: %v", err) } extra = append(extra, fmt.Sprintf("Started OpenAPI Schema at %%s%s", openapi.OpenAPIServePath)) handler = open // add CORS support if origins := c.ensureCORSAllowedOrigins(); len(origins) != 0 { handler = apiserver.CORS(handler, origins, nil, nil, "true") } if c.WebConsoleEnabled() { handler = assetServerRedirect(handler, c.Options.AssetConfig.PublicURL) } // Make the outermost filter the requestContextMapper to ensure all components share the same context if contextHandler, err := kapi.NewRequestContextFilter(c.getRequestContextMapper(), handler); err != nil { glog.Fatalf("Error setting up request context filter: %v", err) } else { handler = contextHandler } longRunningRequestCheck := apiserver.BasicLongRunningRequestCheck(longRunningRE, map[string]string{"watch": "true"}) // TODO: MaxRequestsInFlight should be subdivided by intent, type of behavior, and speed of // execution - updates vs reads, long reads vs short reads, fat reads vs skinny reads. if c.Options.ServingInfo.MaxRequestsInFlight > 0 { sem := make(chan bool, c.Options.ServingInfo.MaxRequestsInFlight) handler = apiserver.MaxInFlightLimit(sem, longRunningRequestCheck, handler) } c.serve(handler, extra) // Attempt to verify the server came up for 20 seconds (100 tries * 100ms, 100ms timeout per try) cmdutil.WaitForSuccessfulDial(c.TLS, c.Options.ServingInfo.BindNetwork, c.Options.ServingInfo.BindAddress, 100*time.Millisecond, 100*time.Millisecond, 100) }
// InstallSwaggerAPI installs the /swaggerapi/ endpoint to allow schema discovery // and traversal. It is optional to allow consumers of the Kubernetes GenericAPIServer to // register their own web services into the Kubernetes mux prior to initialization // of swagger, so that other resource types show up in the documentation. func (s *GenericAPIServer) InstallSwaggerAPI() { // Enable swagger UI and discovery API swagger.RegisterSwaggerService(*s.getSwaggerConfig(), s.HandlerContainer) }