Beispiel #1
0
func configureAPI(api *operations.TodoListAPI) http.Handler {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	api.KeyAuth = func(token string) (interface{}, error) {
		return nil, errors.NotImplemented("api key auth (key) x-petstore-token from header has not yet been implemented")
	}

	api.TodosAddOneHandler = todos.AddOneHandlerFunc(func(params todos.AddOneParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation todos.AddOne has not yet been implemented")
	})
	api.TodosDestroyOneHandler = todos.DestroyOneHandlerFunc(func(params todos.DestroyOneParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation todos.DestroyOne has not yet been implemented")
	})
	api.TodosFindHandler = todos.FindHandlerFunc(func(params todos.FindParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation todos.Find has not yet been implemented")
	})
	api.TodosUpdateOneHandler = todos.UpdateOneHandlerFunc(func(params todos.UpdateOneParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation todos.UpdateOne has not yet been implemented")
	})

	api.ServerShutdown = func() {}
	// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }

	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
}
func configureAPI(api *operations.EventListAPI) {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	api.DeleteEventByIDHandler = events.DeleteEventByIDHandlerFunc(func(params events.DeleteEventByIDParams) middleware.Responder {
		return middleware.NotImplemented("operation deleteEventById has not yet been implemented")
	})
	api.PostEventHandler = events.PostEventHandlerFunc(func(params events.PostEventParams) middleware.Responder {
		return middleware.NotImplemented("operation postEvent has not yet been implemented")
	})
	api.GetEventByIDHandler = events.GetEventByIDHandlerFunc(func(params events.GetEventByIDParams) middleware.Responder {
		return middleware.NotImplemented("operation getEventById has not yet been implemented")
	})
	api.GetEventsHandler = events.GetEventsHandlerFunc(func() middleware.Responder {
		return middleware.NotImplemented("operation getEvents has not yet been implemented")
	})
	api.PutEventByIDHandler = events.PutEventByIDHandlerFunc(func(params events.PutEventByIDParams) middleware.Responder {
		return middleware.NotImplemented("operation putEventById has not yet been implemented")
	})

}
Beispiel #3
0
// New creates a new default runtime for a swagger api client.
func New(swaggerSpec *spec.Document) *Runtime {
	var rt Runtime
	rt.DefaultMediaType = httpkit.JSONMime

	// TODO: actually infer this stuff from the spec
	rt.Consumers = map[string]httpkit.Consumer{
		httpkit.JSONMime: httpkit.JSONConsumer(),
	}
	rt.Producers = map[string]httpkit.Producer{
		httpkit.JSONMime: httpkit.JSONProducer(),
	}
	rt.Spec = swaggerSpec
	rt.Transport = http.DefaultTransport
	rt.client = http.DefaultClient
	rt.client.Transport = rt.Transport
	rt.Host = swaggerSpec.Host()
	rt.BasePath = swaggerSpec.BasePath()
	schemes := swaggerSpec.Spec().Schemes
	if len(schemes) == 0 {
		schemes = append(schemes, "http")
	}
	rt.methodsAndPaths = make(map[string]methodAndPath)
	for mth, pathItem := range rt.Spec.Operations() {
		for pth, op := range pathItem {
			if len(op.Schemes) > 0 {
				rt.methodsAndPaths[op.ID] = methodAndPath{mth, pth, op.Schemes}
			} else {
				rt.methodsAndPaths[op.ID] = methodAndPath{mth, pth, schemes}
			}
		}
	}
	return &rt
}
func configureAPI(api *operations.EventListAPI) http.Handler {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	api.EventsDeleteEventByIDHandler = events.DeleteEventByIDHandlerFunc(func(params events.DeleteEventByIDParams) middleware.Responder {
		return middleware.NotImplemented("operation events.DeleteEventByID has not yet been implemented")
	})
	api.EventsGetEventByIDHandler = events.GetEventByIDHandlerFunc(func(params events.GetEventByIDParams) middleware.Responder {
		return middleware.NotImplemented("operation events.GetEventByID has not yet been implemented")
	})
	api.EventsGetEventsHandler = events.GetEventsHandlerFunc(func() middleware.Responder {
		return middleware.NotImplemented("operation events.GetEvents has not yet been implemented")
	})
	api.EventsPostEventHandler = events.PostEventHandlerFunc(func(params events.PostEventParams) middleware.Responder {
		return middleware.NotImplemented("operation events.PostEvent has not yet been implemented")
	})
	api.EventsPutEventByIDHandler = events.PutEventByIDHandlerFunc(func(params events.PutEventByIDParams) middleware.Responder {
		return middleware.NotImplemented("operation events.PutEventByID has not yet been implemented")
	})

	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
}
Beispiel #5
0
func configureAPI(api *operations.TodoListAPI) http.Handler {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	api.TodosAddOneHandler = todos.AddOneHandlerFunc(func(params todos.AddOneParams) middleware.Responder {
		return middleware.NotImplemented("operation todos.AddOne has not yet been implemented")
	})
	api.TodosDestroyOneHandler = todos.DestroyOneHandlerFunc(func(params todos.DestroyOneParams) middleware.Responder {
		return middleware.NotImplemented("operation todos.DestroyOne has not yet been implemented")
	})
	api.TodosFindTodosHandler = todos.FindTodosHandlerFunc(func(params todos.FindTodosParams) middleware.Responder {
		return middleware.NotImplemented("operation todos.FindTodos has not yet been implemented")
	})
	api.TodosUpdateOneHandler = todos.UpdateOneHandlerFunc(func(params todos.UpdateOneParams) middleware.Responder {
		return middleware.NotImplemented("operation todos.UpdateOne has not yet been implemented")
	})

	api.ServerShutdown = func() {}
	// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }

	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
}
func configureAPI(api *operations.ToDoListAPI) {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	api.XPetstoreTokenAuth = func(token string) (interface{}, error) {
		return nil, errors.NotImplemented("api key auth x-petstore-token from header has not yet been implemented")
	}

	api.AddOneHandler = todos.AddOneHandlerFunc(func(principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation addOne has not yet been implemented")
	})
	api.DestroyOneHandler = todos.DestroyOneHandlerFunc(func(params todos.DestroyOneParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation destroyOne has not yet been implemented")
	})
	api.FindHandler = todos.FindHandlerFunc(func(principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation find has not yet been implemented")
	})
	api.UpdateOneHandler = todos.UpdateOneHandlerFunc(func(params todos.UpdateOneParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation updateOne has not yet been implemented")
	})

}
Beispiel #7
0
func TestBuildRequest_BuildHTTP_Files(t *testing.T) {
	cont, _ := ioutil.ReadFile("./client.go")
	reqWrtr := client.RequestWriterFunc(func(req client.Request, reg strfmt.Registry) error {
		req.SetFormParam("something", "some value")
		req.SetFileParam("file", "./client.go")
		req.SetQueryParam("hello", "world")
		req.SetPathParam("id", "1234")
		req.SetHeaderParam("X-Rate-Limit", "200")
		return nil
	})
	r, _ := newRequest("GET", "/flats/{id}/", reqWrtr)
	r.SetHeaderParam(httpkit.HeaderContentType, httpkit.JSONMime)

	req, err := r.BuildHTTP(httpkit.JSONProducer(), nil)
	if assert.NoError(t, err) && assert.NotNil(t, req) {
		assert.Equal(t, "200", req.Header.Get("x-rate-limit"))
		assert.Equal(t, "world", req.URL.Query().Get("hello"))
		assert.Equal(t, "/flats/1234/", req.URL.Path)
		mediaType, params, err := mime.ParseMediaType(req.Header.Get(httpkit.HeaderContentType))
		if assert.NoError(t, err) {
			assert.Equal(t, httpkit.MultipartFormMime, mediaType)
			boundary := params["boundary"]
			mr := multipart.NewReader(req.Body, boundary)
			frm, err := mr.ReadForm(1 << 20)
			if assert.NoError(t, err) {
				assert.Equal(t, "some value", frm.Value["something"][0])
				mpff := frm.File["file"][0]
				mpf, _ := mpff.Open()
				assert.Equal(t, "client.go", mpff.Filename)
				actual, _ := ioutil.ReadAll(mpf)
				assert.Equal(t, cont, actual)
			}
		}
	}
}
func configureAPI(api *operations.GophergalaLearningResourcesAPI) http.Handler {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	api.AddLearningResourceHandler = operations.AddLearningResourceHandlerFunc(func(params operations.AddLearningResourceParams) middleware.Responder {
		return middleware.NotImplemented("operation .AddLearningResource has not yet been implemented")
	})
	api.DeleteLearningResourceHandler = operations.DeleteLearningResourceHandlerFunc(func(params operations.DeleteLearningResourceParams) middleware.Responder {
		return middleware.NotImplemented("operation .DeleteLearningResource has not yet been implemented")
	})
	api.FindLearningResourceByIDHandler = operations.FindLearningResourceByIDHandlerFunc(func(params operations.FindLearningResourceByIDParams) middleware.Responder {
		return middleware.NotImplemented("operation .FindLearningResourceByID has not yet been implemented")
	})
	api.FindLearningResourcesHandler = operations.FindLearningResourcesHandlerFunc(func(params operations.FindLearningResourcesParams) middleware.Responder {
		return middleware.NotImplemented("operation .FindLearningResources has not yet been implemented")
	})

	api.ServerShutdown = func() {}
	// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }

	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
}
Beispiel #9
0
// New creates a new default runtime for a swagger api client.
func New(host, basePath string, schemes []string) *Runtime {
	var rt Runtime
	rt.DefaultMediaType = httpkit.JSONMime

	// TODO: actually infer this stuff from the spec
	rt.Consumers = map[string]httpkit.Consumer{
		httpkit.JSONMime: httpkit.JSONConsumer(),
		httpkit.XMLMime:  httpkit.XMLConsumer(),
		httpkit.TextMime: httpkit.TextConsumer(),
	}
	rt.Producers = map[string]httpkit.Producer{
		httpkit.JSONMime: httpkit.JSONProducer(),
		httpkit.XMLMime:  httpkit.XMLProducer(),
		httpkit.TextMime: httpkit.TextProducer(),
	}
	rt.Transport = http.DefaultTransport
	rt.Jar = nil
	rt.Host = host
	rt.BasePath = basePath
	rt.Context = context.Background()
	rt.clientOnce = new(sync.Once)
	if !strings.HasPrefix(rt.BasePath, "/") {
		rt.BasePath = "/" + rt.BasePath
	}
	rt.Debug = os.Getenv("DEBUG") == "1"
	if len(schemes) > 0 {
		rt.schemes = schemes
	}
	return &rt
}
Beispiel #10
0
func configureAPI(api *operations.PortLayerAPI) http.Handler {
	if options.PortLayerOptions.Debug {
		log.SetLevel(log.DebugLevel)
	}

	ctx := context.Background()

	sessionconfig := &session.Config{
		Service:        options.PortLayerOptions.SDK,
		Insecure:       options.PortLayerOptions.Insecure,
		Keepalive:      options.PortLayerOptions.Keepalive,
		DatacenterPath: options.PortLayerOptions.DatacenterPath,
		ClusterPath:    options.PortLayerOptions.ClusterPath,
		PoolPath:       options.PortLayerOptions.PoolPath,
		DatastorePath:  options.PortLayerOptions.DatastorePath,
	}

	sess, err := session.NewSession(sessionconfig).Create(ctx)
	if err != nil {
		log.Fatalf("configure_port_layer ERROR: %s", err)
	}

	// Configure the func invoked if the PL panics or is restarted by vic-init
	api.ServerShutdown = func() {
		log.Infof("Shutting down port-layer-server")

		// Logout the session
		if err := sess.Logout(ctx); err != nil {
			log.Warnf("unable to log out of session: %s", err)
		}
	}

	// initialize the port layer
	if err = portlayer.Init(ctx, sess); err != nil {
		log.Fatalf("could not initialize port layer: %s", err)
	}

	// configure the api here
	api.ServeError = errors.ServeError

	api.BinConsumer = httpkit.ByteStreamConsumer()

	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	api.TxtProducer = httpkit.TextProducer()

	handlerCtx := &handlers.HandlerContext{
		Session: sess,
	}
	for _, handler := range portlayerhandlers {
		handler.Configure(api, handlerCtx)
	}

	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
}
Beispiel #11
0
// New creates a new default runtim for a swagger api client.
func New(swaggerSpec *spec.Document) *Runtime {
	var rt Runtime
	rt.DefaultMediaType = "application/json"
	rt.Consumers = map[string]httpkit.Consumer{
		"application/json": httpkit.JSONConsumer(),
	}
	rt.Producers = map[string]httpkit.Producer{
		"application/json": httpkit.JSONProducer(),
	}
	return &rt
}
func configureAPI(api *operations.TodoListAPI) http.Handler {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	api.TodosFindTodosHandler = todos.FindTodosHandlerFunc(func(params todos.FindTodosParams) middleware.Responder {
		return middleware.NotImplemented("operation todos.FindTodos has not yet been implemented")
	})

	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
}
func TestContentType_Issue264(t *testing.T) {
	swspec, err := spec.Load("../../fixtures/bugs/264/swagger.yml")
	if assert.NoError(t, err) {
		api := untyped.NewAPI(swspec)
		api.RegisterConsumer("application/json", httpkit.JSONConsumer())
		api.RegisterProducer("application/json", httpkit.JSONProducer())
		api.RegisterOperation("delete", "/key/{id}", new(stubOperationHandler))

		handler := Serve(swspec, api)
		request, _ := http.NewRequest("DELETE", "/key/1", nil)
		recorder := httptest.NewRecorder()
		handler.ServeHTTP(recorder, request)
		assert.Equal(t, 200, recorder.Code)
	}
}
func configureAPI(api *operations.TaskTrackerAPI) http.Handler {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	api.APIKeyAuth = func(token string) (interface{}, error) {
		return nil, errors.NotImplemented("api key auth (api_key) token from query has not yet been implemented")
	}

	api.TokenHeaderAuth = func(token string) (interface{}, error) {
		return nil, errors.NotImplemented("api key auth (token_header) X-Token from header has not yet been implemented")
	}

	api.TasksAddCommentToTaskHandler = tasks.AddCommentToTaskHandlerFunc(func(params tasks.AddCommentToTaskParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation tasks.AddCommentToTask has not yet been implemented")
	})
	api.TasksCreateTaskHandler = tasks.CreateTaskHandlerFunc(func(params tasks.CreateTaskParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation tasks.CreateTask has not yet been implemented")
	})
	api.TasksDeleteTaskHandler = tasks.DeleteTaskHandlerFunc(func(params tasks.DeleteTaskParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation tasks.DeleteTask has not yet been implemented")
	})
	api.TasksGetTaskCommentsHandler = tasks.GetTaskCommentsHandlerFunc(func(params tasks.GetTaskCommentsParams) middleware.Responder {
		return middleware.NotImplemented("operation tasks.GetTaskComments has not yet been implemented")
	})
	api.TasksGetTaskDetailsHandler = tasks.GetTaskDetailsHandlerFunc(func(params tasks.GetTaskDetailsParams) middleware.Responder {
		return middleware.NotImplemented("operation tasks.GetTaskDetails has not yet been implemented")
	})
	api.TasksListTasksHandler = tasks.ListTasksHandlerFunc(func(params tasks.ListTasksParams) middleware.Responder {
		return middleware.NotImplemented("operation tasks.ListTasks has not yet been implemented")
	})
	api.TasksUpdateTaskHandler = tasks.UpdateTaskHandlerFunc(func(params tasks.UpdateTaskParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation tasks.UpdateTask has not yet been implemented")
	})
	api.TasksUploadTaskFileHandler = tasks.UploadTaskFileHandlerFunc(func(params tasks.UploadTaskFileParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation tasks.UploadTaskFile has not yet been implemented")
	})

	api.ServerShutdown = func() {}
	// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }

	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
}
Beispiel #15
0
func configureAPI(api *operations.TodoListAPI) http.Handler {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	api.TodosAddOneHandler = todos.AddOneHandlerFunc(func(params todos.AddOneParams) middleware.Responder {
		if err := addItem(params.Body); err != nil {
			return todos.NewAddOneDefault(500).WithPayload(&models.Error{Code: swag.Int64(500), Message: err.Error()})
		}
		return todos.NewAddOneCreated().WithPayload(params.Body)
	})

	api.TodosDestroyOneHandler = todos.DestroyOneHandlerFunc(func(params todos.DestroyOneParams) middleware.Responder {
		if err := deleteItem(params.ID); err != nil {
			return todos.NewDestroyOneDefault(500).WithPayload(&models.Error{Code: swag.Int64(500), Message: err.Error()})
		}
		return todos.NewDestroyOneNoContent()
	})

	api.TodosFindTodosHandler = todos.FindTodosHandlerFunc(func(params todos.FindTodosParams) middleware.Responder {
		mergedParams := todos.NewFindTodosParams()
		mergedParams.Since = swag.Int64(0)
		if params.Since != nil {
			mergedParams.Since = params.Since
		}
		if params.Limit != nil {
			mergedParams.Limit = params.Limit
		}
		return todos.NewFindTodosOK().WithPayload(allItems(*mergedParams.Since, *mergedParams.Limit))
	})

	api.TodosUpdateOneHandler = todos.UpdateOneHandlerFunc(func(params todos.UpdateOneParams) middleware.Responder {
		if err := updateItem(params.ID, params.Body); err != nil {
			return todos.NewUpdateOneDefault(500).WithPayload(&models.Error{Code: swag.Int64(500), Message: err.Error()})
		}
		return todos.NewUpdateOneOK().WithPayload(params.Body)
	})

	api.ServerShutdown = func() {}

	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
}
Beispiel #16
0
// NewAPI creates the default untyped API
func NewAPI(spec *spec.Document) *API {
	return &API{
		spec:            spec,
		DefaultProduces: httpkit.JSONMime,
		DefaultConsumes: httpkit.JSONMime,
		consumers: map[string]httpkit.Consumer{
			httpkit.JSONMime: httpkit.JSONConsumer(),
		},
		producers: map[string]httpkit.Producer{
			httpkit.JSONMime: httpkit.JSONProducer(),
		},
		authenticators: make(map[string]httpkit.Authenticator),
		operations:     make(map[string]httpkit.OperationHandler),
		ServeError:     errors.ServeError,
		Models:         make(map[string]func() interface{}),
		formats:        strfmt.NewFormats(),
	}
}
func configureAPI(api *jenkins.JenkinsAPI) http.Handler {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	api.JobGetJobListHandler = job.GetJobListHandlerFunc(func() middleware.Responder {
		return middleware.NotImplemented("operation job.GetJobList has not yet been implemented")
	})

	api.JobGetJobListHandler = job.GetJobListHandlerFunc(logic.GetJobListHandler)

	api.HealthGetServiceHealthHandler = health.GetServiceHealthHandlerFunc(func() middleware.Responder {
		return middleware.NotImplemented("operation health.GetServiceHealth has not yet been implemented")
	})

	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
}
Beispiel #18
0
func TestBuildRequest_BuildHTTP_Form(t *testing.T) {
	reqWrtr := client.RequestWriterFunc(func(req client.Request, reg strfmt.Registry) error {
		req.SetFormParam("something", "some value")
		req.SetQueryParam("hello", "world")
		req.SetPathParam("id", "1234")
		req.SetHeaderParam("X-Rate-Limit", "200")
		return nil
	})
	r, _ := newRequest("GET", "/flats/{id}/", reqWrtr)
	r.SetHeaderParam(httpkit.HeaderContentType, httpkit.JSONMime)

	req, err := r.BuildHTTP(httpkit.JSONProducer(), nil)
	if assert.NoError(t, err) && assert.NotNil(t, req) {
		assert.Equal(t, "200", req.Header.Get("x-rate-limit"))
		assert.Equal(t, "world", req.URL.Query().Get("hello"))
		assert.Equal(t, "/flats/1234/", req.URL.Path)
		expected := []byte("something=some+value")
		actual, _ := ioutil.ReadAll(req.Body)
		assert.Equal(t, expected, actual)
	}
}
Beispiel #19
0
func configureAPI(api *operations.FastpassAPI) http.Handler {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	f := fastpass.NewFastPass()

	api.AddEventHandler = operations.AddEventHandlerFunc(f.AddEventHandler)
	api.DeleteEventHandler = operations.DeleteEventHandlerFunc(f.DeleteEventHandler)
	api.GetTicketHandler = operations.GetTicketHandlerFunc(f.GetTicketHandler)
	api.ListEventsHandler = operations.ListEventsHandlerFunc(f.ListEventsHandler)
	api.TicketingHandler = operations.TicketingHandlerFunc(f.TicketingHandler)

	api.ServerShutdown = func() {}
	// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }

	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
}
Beispiel #20
0
// New creates a new default runtime for a swagger api client.
func New(swaggerSpec *spec.Document) *Runtime {
	var rt Runtime
	rt.DefaultMediaType = httpkit.JSONMime
	rt.Consumers = map[string]httpkit.Consumer{
		httpkit.JSONMime: httpkit.JSONConsumer(),
	}
	rt.Producers = map[string]httpkit.Producer{
		httpkit.JSONMime: httpkit.JSONProducer(),
	}
	rt.Spec = swaggerSpec
	rt.Transport = http.DefaultTransport
	rt.client = http.DefaultClient
	rt.Host = swaggerSpec.Host()
	rt.BasePath = swaggerSpec.BasePath()
	rt.methodsAndPaths = make(map[string]methodAndPath)
	for mth, pathItem := range rt.Spec.Operations() {
		for pth, op := range pathItem {
			rt.methodsAndPaths[op.ID] = methodAndPath{mth, pth}
		}
	}
	return &rt
}
Beispiel #21
0
// New creates a new default runtime for a swagger api client.
func New(swaggerSpec *spec.Document) *Runtime {
	var rt Runtime
	rt.DefaultMediaType = httpkit.JSONMime

	// TODO: actually infer this stuff from the spec
	rt.Consumers = map[string]httpkit.Consumer{
		httpkit.JSONMime: httpkit.JSONConsumer(),
	}
	rt.Producers = map[string]httpkit.Producer{
		httpkit.JSONMime: httpkit.JSONProducer(),
	}
	rt.Spec = swaggerSpec
	rt.Transport = http.DefaultTransport
	rt.client = http.DefaultClient
	rt.client.Transport = rt.Transport
	rt.Host = swaggerSpec.Host()
	rt.BasePath = swaggerSpec.BasePath()
	if !strings.HasPrefix(rt.BasePath, "/") {
		rt.BasePath = "/" + rt.BasePath
	}
	rt.Debug = os.Getenv("DEBUG") == "1"
	schemes := swaggerSpec.Spec().Schemes
	if len(schemes) == 0 {
		schemes = append(schemes, "http")
	}
	rt.methodsAndPaths = make(map[string]methodAndPath)
	for mth, pathItem := range rt.Spec.Operations() {
		for pth, op := range pathItem {
			nm := ensureUniqueName(op.ID, mth, pth, rt.methodsAndPaths)
			op.ID = nm
			if len(op.Schemes) > 0 {
				rt.methodsAndPaths[nm] = methodAndPath{mth, pth, op.Schemes}
			} else {
				rt.methodsAndPaths[nm] = methodAndPath{mth, pth, schemes}
			}
		}
	}
	return &rt
}
Beispiel #22
0
func TestBuildRequest_BuildHTTP_Payload(t *testing.T) {
	bd := []struct{ Name, Hobby string }{{"Tom", "Organ trail"}, {"John", "Bird watching"}}
	reqWrtr := client.RequestWriterFunc(func(req client.Request, reg strfmt.Registry) error {
		req.SetBodyParam(bd)
		req.SetQueryParam("hello", "world")
		req.SetPathParam("id", "1234")
		req.SetHeaderParam("X-Rate-Limit", "200")
		return nil
	})
	r, _ := newRequest("GET", "/flats/{id}/", reqWrtr)
	r.SetHeaderParam(httpkit.HeaderContentType, httpkit.JSONMime)

	req, err := r.BuildHTTP(httpkit.JSONProducer(), nil)
	if assert.NoError(t, err) && assert.NotNil(t, req) {
		assert.Equal(t, "200", req.Header.Get("x-rate-limit"))
		assert.Equal(t, "world", req.URL.Query().Get("hello"))
		assert.Equal(t, "/flats/1234/", req.URL.Path)
		expectedBody, _ := json.Marshal(bd)
		actualBody, _ := ioutil.ReadAll(req.Body)
		assert.Equal(t, append(expectedBody, '\n'), actualBody)
	}
}
Beispiel #23
0
// New creates a new default runtime for a swagger api client.
func New(host, basePath string, schemes []string) *Runtime {
	var rt Runtime
	rt.DefaultMediaType = httpkit.JSONMime

	// TODO: actually infer this stuff from the spec
	rt.Consumers = map[string]httpkit.Consumer{
		httpkit.JSONMime: httpkit.JSONConsumer(),
	}
	rt.Producers = map[string]httpkit.Producer{
		httpkit.JSONMime: httpkit.JSONProducer(),
	}
	rt.Transport = http.DefaultTransport
	rt.client = http.DefaultClient
	rt.Host = host
	rt.BasePath = basePath
	if !strings.HasPrefix(rt.BasePath, "/") {
		rt.BasePath = "/" + rt.BasePath
	}
	rt.Debug = os.Getenv("DEBUG") == "1"
	if len(schemes) > 0 {
		rt.schemes = schemes
	}
	return &rt
}
Beispiel #24
0
// WriteImage writes the image to given image store
func WriteImage(host string, image *ImageWithMeta, data io.ReadCloser) error {
	defer trace.End(trace.Begin(image.ID))

	transport := httptransport.New(host, "/", []string{"http"})
	client := apiclient.New(transport, nil)

	transport.Consumers["application/json"] = httpkit.JSONConsumer()
	transport.Producers["application/json"] = httpkit.JSONProducer()
	transport.Consumers["application/octet-stream"] = httpkit.ByteStreamConsumer()
	transport.Producers["application/octet-stream"] = httpkit.ByteStreamProducer()

	key := new(string)
	blob := new(string)

	*key = metadata.MetaDataKey
	*blob = image.Meta

	r, err := client.Storage.WriteImage(
		storage.NewWriteImageParamsWithContext(ctx).
			WithImageID(image.ID).
			WithParentID(*image.Parent).
			WithStoreName(image.Store).
			WithMetadatakey(key).
			WithMetadataval(blob).
			WithImageFile(data).
			WithSum(image.Layer.BlobSum),
	)
	if err != nil {
		log.Debugf("Creating an image failed: %s", err)
		return err
	}
	log.Printf("Created an image %#v", r.Payload)

	return nil

}
func configureAPI(api *operations.PetStoreAPI) {
	// configure the api here
	api.ServeError = errors.ServeError

	api.XMLConsumer = httpkit.ConsumerFunc(func(r io.Reader, target interface{}) error {
		return errors.NotImplemented("xml consumer has not yet been implemented")
	})
	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	api.XMLProducer = httpkit.ProducerFunc(func(w io.Writer, data interface{}) error {
		return errors.NotImplemented("xml producer has not yet been implemented")
	})

	api.APIKeyAuth = func(token string) (*models.User, error) {
		return nil, errors.NotImplemented("api key auth api_key from header has not yet been implemented")
	}

	api.GetPetByIDHandler = pet.GetPetByIDHandlerFunc(func(params pet.GetPetByIDParams, principal *models.User) (*models.Pet, error) {
		return nil, errors.NotImplemented("operation getPetById has not yet been implemented")
	})
	api.LogoutUserHandler = user.LogoutUserHandlerFunc(func() error {
		return errors.NotImplemented("operation logoutUser has not yet been implemented")
	})
	api.DeleteUserHandler = user.DeleteUserHandlerFunc(func(params user.DeleteUserParams) error {
		return errors.NotImplemented("operation deleteUser has not yet been implemented")
	})
	api.DeleteOrderHandler = store.DeleteOrderHandlerFunc(func(params store.DeleteOrderParams) error {
		return errors.NotImplemented("operation deleteOrder has not yet been implemented")
	})
	api.UpdateUserHandler = user.UpdateUserHandlerFunc(func(params user.UpdateUserParams) error {
		return errors.NotImplemented("operation updateUser has not yet been implemented")
	})
	api.LoginUserHandler = user.LoginUserHandlerFunc(func(params user.LoginUserParams) (string, error) {
		return "", errors.NotImplemented("operation loginUser has not yet been implemented")
	})
	api.DeletePetHandler = pet.DeletePetHandlerFunc(func(params pet.DeletePetParams, principal *models.User) error {
		return errors.NotImplemented("operation deletePet has not yet been implemented")
	})
	api.UpdatePetHandler = pet.UpdatePetHandlerFunc(func(params pet.UpdatePetParams, principal *models.User) error {
		return errors.NotImplemented("operation updatePet has not yet been implemented")
	})
	api.CreateUsersWithListInputHandler = user.CreateUsersWithListInputHandlerFunc(func(params user.CreateUsersWithListInputParams) error {
		return errors.NotImplemented("operation createUsersWithListInput has not yet been implemented")
	})
	api.AddPetHandler = pet.AddPetHandlerFunc(func(params pet.AddPetParams, principal *models.User) error {
		return errors.NotImplemented("operation addPet has not yet been implemented")
	})
	api.CreateUserHandler = user.CreateUserHandlerFunc(func(params user.CreateUserParams) error {
		return errors.NotImplemented("operation createUser has not yet been implemented")
	})
	api.FindPetsByStatusHandler = pet.FindPetsByStatusHandlerFunc(func(params pet.FindPetsByStatusParams, principal *models.User) ([]models.Pet, error) {
		return nil, errors.NotImplemented("operation findPetsByStatus has not yet been implemented")
	})
	api.GetUserByNameHandler = user.GetUserByNameHandlerFunc(func(params user.GetUserByNameParams) (*models.User, error) {
		return nil, errors.NotImplemented("operation getUserByName has not yet been implemented")
	})
	api.PlaceOrderHandler = store.PlaceOrderHandlerFunc(func(params store.PlaceOrderParams) (*models.Order, error) {
		return nil, errors.NotImplemented("operation placeOrder has not yet been implemented")
	})
	api.UpdatePetWithFormHandler = pet.UpdatePetWithFormHandlerFunc(func(params pet.UpdatePetWithFormParams, principal *models.User) error {
		return errors.NotImplemented("operation updatePetWithForm has not yet been implemented")
	})
	api.GetOrderByIDHandler = store.GetOrderByIDHandlerFunc(func(params store.GetOrderByIDParams) (*models.Order, error) {
		return nil, errors.NotImplemented("operation getOrderById has not yet been implemented")
	})
	api.FindPetsByTagsHandler = pet.FindPetsByTagsHandlerFunc(func(params pet.FindPetsByTagsParams, principal *models.User) ([]models.Pet, error) {
		return nil, errors.NotImplemented("operation findPetsByTags has not yet been implemented")
	})
	api.CreateUsersWithArrayInputHandler = user.CreateUsersWithArrayInputHandlerFunc(func(params user.CreateUsersWithArrayInputParams) error {
		return errors.NotImplemented("operation createUsersWithArrayInput has not yet been implemented")
	})

}
Beispiel #26
0
	"encoding/json"
	"io/ioutil"
	"mime"
	"mime/multipart"
	"os"
	"path/filepath"
	"testing"

	"github.com/go-swagger/go-swagger/client"
	"github.com/go-swagger/go-swagger/httpkit"
	"github.com/go-swagger/go-swagger/strfmt"
	"github.com/stretchr/testify/assert"
)

var testProducers = map[string]httpkit.Producer{
	httpkit.JSONMime: httpkit.JSONProducer(),
}

func TestBuildRequest_SetHeaders(t *testing.T) {
	r, _ := newRequest("GET", "/flats/{id}/", nil)
	// single value
	r.SetHeaderParam("X-Rate-Limit", "500")
	assert.Equal(t, "500", r.header.Get("X-Rate-Limit"))
	r.SetHeaderParam("X-Rate-Limit", "400")
	assert.Equal(t, "400", r.header.Get("X-Rate-Limit"))

	// multi value
	r.SetHeaderParam("X-Accepts", "json", "xml", "yaml")
	assert.EqualValues(t, []string{"json", "xml", "yaml"}, r.header["X-Accepts"])
}
func configureAPI(api *operations.PetstoreAPI) http.Handler {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.XMLConsumer = httpkit.ConsumerFunc(func(r io.Reader, target interface{}) error {
		return errors.NotImplemented("xml consumer has not yet been implemented")
	})

	api.JSONProducer = httpkit.JSONProducer()

	api.XMLProducer = httpkit.ProducerFunc(func(w io.Writer, data interface{}) error {
		return errors.NotImplemented("xml producer has not yet been implemented")
	})

	api.APIKeyAuth = func(token string) (interface{}, error) {
		return nil, errors.NotImplemented("api key auth (api_key) api_key from header has not yet been implemented")
	}

	api.PetAddPetHandler = pet.AddPetHandlerFunc(func(params pet.AddPetParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation pet.AddPet has not yet been implemented")
	})
	api.UserCreateUserHandler = user.CreateUserHandlerFunc(func(params user.CreateUserParams) middleware.Responder {
		return middleware.NotImplemented("operation user.CreateUser has not yet been implemented")
	})
	api.UserCreateUsersWithArrayInputHandler = user.CreateUsersWithArrayInputHandlerFunc(func(params user.CreateUsersWithArrayInputParams) middleware.Responder {
		return middleware.NotImplemented("operation user.CreateUsersWithArrayInput has not yet been implemented")
	})
	api.UserCreateUsersWithListInputHandler = user.CreateUsersWithListInputHandlerFunc(func(params user.CreateUsersWithListInputParams) middleware.Responder {
		return middleware.NotImplemented("operation user.CreateUsersWithListInput has not yet been implemented")
	})
	api.StoreDeleteOrderHandler = store.DeleteOrderHandlerFunc(func(params store.DeleteOrderParams) middleware.Responder {
		return middleware.NotImplemented("operation store.DeleteOrder has not yet been implemented")
	})
	api.PetDeletePetHandler = pet.DeletePetHandlerFunc(func(params pet.DeletePetParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation pet.DeletePet has not yet been implemented")
	})
	api.UserDeleteUserHandler = user.DeleteUserHandlerFunc(func(params user.DeleteUserParams) middleware.Responder {
		return middleware.NotImplemented("operation user.DeleteUser has not yet been implemented")
	})
	api.PetFindPetsByStatusHandler = pet.FindPetsByStatusHandlerFunc(func(params pet.FindPetsByStatusParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation pet.FindPetsByStatus has not yet been implemented")
	})
	api.PetFindPetsByTagsHandler = pet.FindPetsByTagsHandlerFunc(func(params pet.FindPetsByTagsParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation pet.FindPetsByTags has not yet been implemented")
	})
	api.StoreGetInventoryHandler = store.GetInventoryHandlerFunc(func(principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation store.GetInventory has not yet been implemented")
	})
	api.StoreGetOrderByIDHandler = store.GetOrderByIDHandlerFunc(func(params store.GetOrderByIDParams) middleware.Responder {
		return middleware.NotImplemented("operation store.GetOrderByID has not yet been implemented")
	})
	api.PetGetPetByIDHandler = pet.GetPetByIDHandlerFunc(func(params pet.GetPetByIDParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation pet.GetPetByID has not yet been implemented")
	})
	api.UserGetUserByNameHandler = user.GetUserByNameHandlerFunc(func(params user.GetUserByNameParams) middleware.Responder {
		return middleware.NotImplemented("operation user.GetUserByName has not yet been implemented")
	})
	api.UserLoginUserHandler = user.LoginUserHandlerFunc(func(params user.LoginUserParams) middleware.Responder {
		return middleware.NotImplemented("operation user.LoginUser has not yet been implemented")
	})
	api.UserLogoutUserHandler = user.LogoutUserHandlerFunc(func() middleware.Responder {
		return middleware.NotImplemented("operation user.LogoutUser has not yet been implemented")
	})
	api.StorePlaceOrderHandler = store.PlaceOrderHandlerFunc(func(params store.PlaceOrderParams) middleware.Responder {
		return middleware.NotImplemented("operation store.PlaceOrder has not yet been implemented")
	})
	api.PetUpdatePetHandler = pet.UpdatePetHandlerFunc(func(params pet.UpdatePetParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation pet.UpdatePet has not yet been implemented")
	})
	api.PetUpdatePetWithFormHandler = pet.UpdatePetWithFormHandlerFunc(func(params pet.UpdatePetWithFormParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation pet.UpdatePetWithForm has not yet been implemented")
	})
	api.UserUpdateUserHandler = user.UpdateUserHandlerFunc(func(params user.UpdateUserParams) middleware.Responder {
		return middleware.NotImplemented("operation user.UpdateUser has not yet been implemented")
	})
	api.PetUploadFileHandler = pet.UploadFileHandlerFunc(func(params pet.UploadFileParams, principal interface{}) middleware.Responder {
		return middleware.NotImplemented("operation pet.UploadFile has not yet been implemented")
	})

	api.ServerShutdown = func() {}
	// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }

	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
}
Beispiel #28
0
// RegisterProducer registers a producer for a media type
func (d *API) RegisterProducer(mediaType string, handler httpkit.Producer) {
	if d.producers == nil {
		d.producers = map[string]httpkit.Producer{httpkit.JSONMime: httpkit.JSONProducer()}
	}
	d.producers[strings.ToLower(mediaType)] = handler
}
func configureAPI(api *operations.GophergalaLearningResourcesAPI) http.Handler {
	// configure the api here
	api.ServeError = errors.ServeError

	api.JSONConsumer = httpkit.JSONConsumer()

	api.JSONProducer = httpkit.JSONProducer()

	api.AddLearningResourceHandler = operations.AddLearningResourceHandlerFunc(func(params operations.AddLearningResourceParams) middleware.Responder {
		if err := addLearningResource(params.LearningResource); err != nil {
			return operations.NewAddLearningResourceDefault(500).WithPayload(&models.ErrorModel{Code: 500, Message: err.Error()})
		}
		return operations.NewAddLearningResourceOK().WithPayload(params.LearningResource)
	})
	api.AddReviewHandler = operations.AddReviewHandlerFunc(func(params operations.AddReviewParams) middleware.Responder {
		err := db.AddReview(params.Review)
		if err != nil {
			return operations.NewAddReviewDefault(500).WithPayload(&models.ErrorModel{Code: 500, Message: err.Error()})
		}
		return operations.NewAddReviewOK().WithPayload(params.Review)
	})
	api.AddScreenshotHandler = operations.AddScreenshotHandlerFunc(func(params operations.AddScreenshotParams) middleware.Responder {
		err := db.AddScreenshot(&params)
		if err != nil {
			return operations.NewAddScreenshotDefault(500).WithPayload(&models.ErrorModel{Code: 500, Message: err.Error()})
		}
		return operations.NewAddScreenshotOK()
	})
	api.AddUserHandler = operations.AddUserHandlerFunc(func(params operations.AddUserParams) middleware.Responder {
		err := db.AddUser(params.User)
		if err != nil {
			return operations.NewAddUserDefault(500).WithPayload(&models.ErrorModel{Code: 500, Message: err.Error()})
		}
		return operations.NewAddUserOK()
	})
	api.AuthUserHandler = operations.AuthUserHandlerFunc(func(params operations.AuthUserParams) middleware.Responder {
		authed := db.AuthUser(params.User.Email, params.User.Password)
		if authed {
			return operations.NewAuthUserOK()
		}
		return operations.NewAuthUserDefault(403)
	})
	api.DeleteLearningResourceHandler = operations.DeleteLearningResourceHandlerFunc(func(params operations.DeleteLearningResourceParams) middleware.Responder {
		err := db.DeleteLearningResource(params.ID)
		if err != nil {
			return operations.NewDeleteLearningResourceDefault(500).WithPayload(&models.ErrorModel{Code: 500, Message: err.Error()})
		}
		return operations.NewDeleteLearningResourceNoContent()
	})
	api.DeleteReviewHandler = operations.DeleteReviewHandlerFunc(func(params operations.DeleteReviewParams) middleware.Responder {
		return middleware.NotImplemented("operation .DeleteReview has not yet been implemented")
	})
	api.DeleteUserHandler = operations.DeleteUserHandlerFunc(func(params operations.DeleteUserParams) middleware.Responder {
		return middleware.NotImplemented("operation .DeleteUser has not yet been implemented")
	})
	api.FindLanguagesHandler = operations.FindLanguagesHandlerFunc(func() middleware.Responder {
		langs, err := db.FindLanguages()
		if err != nil {
			operations.NewFindLanguagesDefault(500).WithPayload(&models.ErrorModel{Code: 500, Message: err.Error()})
		}
		ls := models.Languages{langs}
		return operations.NewFindLanguagesOK().WithPayload(&ls)
	})
	api.FindLearningResourceByIDHandler = operations.FindLearningResourceByIDHandlerFunc(func(params operations.FindLearningResourceByIDParams) middleware.Responder {
		learningResource, err := db.FindLearningResourceByID(params.ID)
		if err != nil {
			return operations.NewFindLearningResourceByIDDefault(500).WithPayload(&models.ErrorModel{Code: 500, Message: err.Error()})
		}
		return operations.NewFindLearningResourceByIDOK().WithPayload(learningResource)
	})
	api.FindLearningResourcesHandler = operations.FindLearningResourcesHandlerFunc(func(params operations.FindLearningResourcesParams) middleware.Responder {
		learningResources := []*models.LearningResource{}
		var err error
		if len(params.Types) == 0 {
			learningResources, err = db.FindLearningResources("all")
			if err != nil {
				return operations.NewFindLearningResourcesDefault(500).WithPayload(&models.ErrorModel{Code: 500, Message: err.Error()})
			}
		}
		for _, t := range params.Types {
			lr, err := db.FindLearningResources(t)
			if err != nil {
				return operations.NewFindLearningResourcesDefault(500).WithPayload(&models.ErrorModel{Code: 500, Message: err.Error()})
			}
			learningResources = append(learningResources, lr...)
		}
		return operations.NewFindLearningResourcesOK().WithPayload(learningResources)
	})
	api.FindReviewByIDHandler = operations.FindReviewByIDHandlerFunc(func(params operations.FindReviewByIDParams) middleware.Responder {
		return middleware.NotImplemented("operation .FindReviewByID has not yet been implemented")
	})
	api.FindReviewsHandler = operations.FindReviewsHandlerFunc(func() middleware.Responder {
		return middleware.NotImplemented("operation .FindReviews has not yet been implemented")
	})
	api.FindReviewsForLearningResourceHandler = operations.FindReviewsForLearningResourceHandlerFunc(func(params operations.FindReviewsForLearningResourceParams) middleware.Responder {
		reviews, err := db.FindReviewsForLearningResource(params.ID)
		if err != nil {
			return operations.NewFindReviewsForLearningResourceDefault(500).WithPayload(&models.ErrorModel{Code: 500, Message: err.Error()})
		}
		return operations.NewFindReviewsForLearningResourceOK().WithPayload(reviews)
	})
	api.FindRecommendationForLearningResourceHandler = operations.FindRecommendationForLearningResourceHandlerFunc(func(params operations.FindRecommendationForLearningResourceParams) middleware.Responder {
		return middleware.NotImplemented("operation .FindRecommendationForLearningResource has not yet been implemented")
	})
	api.FindUserByIDHandler = operations.FindUserByIDHandlerFunc(func(params operations.FindUserByIDParams) middleware.Responder {
		return middleware.NotImplemented("operation .FindUserByID has not yet been implemented")
	})

	api.ServerShutdown = func() {}
	// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }

	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
}