Exemplo n.º 1
0
func TestUntypedFileUpload(t *testing.T) {
	binder := paramsForFileUpload()

	body := bytes.NewBuffer(nil)
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile("file", "plain-jane.txt")
	assert.NoError(t, err)

	part.Write([]byte("the file contents"))
	writer.WriteField("name", "the-name")
	assert.NoError(t, writer.Close())

	urlStr := "http://localhost:8002/hello"
	req, _ := http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", writer.FormDataContentType())

	data := make(map[string]interface{})
	assert.NoError(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))
	assert.Equal(t, "the-name", data["name"])
	assert.NotNil(t, data["file"])
	assert.IsType(t, httpkit.File{}, data["file"])
	file := data["file"].(httpkit.File)
	assert.NotNil(t, file.Header)
	assert.Equal(t, "plain-jane.txt", file.Header.Filename)

	bb, err := ioutil.ReadAll(file.Data)
	assert.NoError(t, err)
	assert.Equal(t, []byte("the file contents"), bb)

	req, _ = http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", "application/json")
	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))

	req, _ = http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", "application(")
	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))

	body = bytes.NewBuffer(nil)
	writer = multipart.NewWriter(body)
	part, err = writer.CreateFormFile("bad-name", "plain-jane.txt")
	assert.NoError(t, err)

	part.Write([]byte("the file contents"))
	writer.WriteField("name", "the-name")
	assert.NoError(t, writer.Close())
	req, _ = http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", writer.FormDataContentType())

	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))

	req, _ = http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", writer.FormDataContentType())
	req.MultipartReader()

	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))
}
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))
}
Exemplo n.º 3
0
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")
	})

}
Exemplo n.º 4
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))
}
Exemplo n.º 5
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
}
Exemplo n.º 6
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))
}
Exemplo n.º 7
0
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))
}
Exemplo n.º 8
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
}
Exemplo n.º 9
0
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")
	})

}
Exemplo n.º 10
0
func TestBindRequest_BodyValidation(t *testing.T) {
	spec, api := petstore.NewAPI(t)
	ctx := NewContext(spec, api, nil)
	api.DefaultConsumes = httpkit.JSONMime
	ctx.router = DefaultRouter(spec, ctx.api)

	req, err := http.NewRequest("GET", "/pets", new(eofReader))
	if assert.NoError(t, err) {
		req.Header.Set("Content-Type", httpkit.JSONMime)

		ri, ok := ctx.RouteInfo(req)
		if assert.True(t, ok) {

			err := ctx.BindValidRequest(req, ri, rbn(func(r *http.Request, rr *MatchedRoute) error {
				defer r.Body.Close()
				var data interface{}
				err := httpkit.JSONConsumer().Consume(r.Body, &data)
				_ = data
				return err
			}))

			assert.Error(t, err)
			assert.Equal(t, io.EOF, err)
		}
	}

}
Exemplo n.º 11
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))
}
Exemplo n.º 12
0
func TestUntypedFormPost(t *testing.T) {
	params := parametersForFormUpload()
	binder := newUntypedRequestBinder(params, nil, strfmt.Default)

	urlStr := "http://localhost:8002/hello"
	req, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(`name=the-name&age=32`))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	data := make(map[string]interface{})
	assert.NoError(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))
	assert.Equal(t, "the-name", data["name"])
	assert.EqualValues(t, 32, data["age"])

	req, _ = http.NewRequest("POST", urlStr, bytes.NewBufferString(`name=%3&age=32`))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))
}
Exemplo n.º 13
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
}
Exemplo n.º 14
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.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))
}
Exemplo n.º 15
0
func TestUntypedBindingTypesForValid(t *testing.T) {

	op2 := parametersForAllTypes("")
	binder := newUntypedRequestBinder(op2, nil, strfmt.Default)

	confirmed := true
	name := "thomas"
	friend := map[string]interface{}{"name": "toby", "age": float64(32)}
	id, age, score, factor := int64(7575), int32(348), float32(5.309), float64(37.403)
	requestID := 19394858
	tags := []string{"one", "two", "three"}
	dt1 := time.Date(2014, 8, 9, 0, 0, 0, 0, time.UTC)
	planned := strfmt.Date(dt1)
	dt2 := time.Date(2014, 10, 12, 8, 5, 5, 0, time.UTC)
	delivered := strfmt.DateTime(dt2)
	picture := base64.URLEncoding.EncodeToString([]byte("hello"))
	uri, _ := url.Parse("http://localhost:8002/hello/7575")
	qs := uri.Query()
	qs.Add("name", name)
	qs.Add("confirmed", "true")
	qs.Add("age", "348")
	qs.Add("score", "5.309")
	qs.Add("factor", "37.403")
	qs.Add("tags", strings.Join(tags, ","))
	qs.Add("planned", planned.String())
	qs.Add("delivered", delivered.String())
	qs.Add("picture", picture)

	req, _ := http.NewRequest("POST", uri.String()+"?"+qs.Encode(), bytes.NewBuffer([]byte(`{"name":"toby","age":32}`)))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-Request-Id", "19394858")

	data := make(map[string]interface{})
	err := binder.Bind(req, RouteParams([]RouteParam{{"id", "7575"}}), httpkit.JSONConsumer(), &data)
	assert.NoError(t, err)
	assert.Equal(t, id, data["id"])
	assert.Equal(t, name, data["name"])
	assert.Equal(t, friend, data["friend"])
	assert.EqualValues(t, requestID, data["X-Request-Id"])
	assert.Equal(t, tags, data["tags"])
	assert.Equal(t, planned, data["planned"])
	assert.Equal(t, delivered, data["delivered"])
	assert.Equal(t, confirmed, data["confirmed"])
	assert.Equal(t, age, data["age"])
	assert.Equal(t, factor, data["factor"])
	assert.Equal(t, score, data["score"])
	pb, _ := base64.URLEncoding.DecodeString(picture)
	assert.EqualValues(t, pb, data["picture"].(strfmt.Base64))

}
Exemplo n.º 16
0
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)
	}
}
Exemplo n.º 17
0
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))
}
Exemplo n.º 18
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))
}
Exemplo n.º 19
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(),
	}
}
Exemplo n.º 20
0
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))
}
Exemplo n.º 21
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))
}
Exemplo n.º 22
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
}
Exemplo n.º 23
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
}
Exemplo n.º 24
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
}
Exemplo n.º 25
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

}
Exemplo n.º 26
0
// RegisterConsumer registers a consumer for a media type.
func (d *API) RegisterConsumer(mediaType string, handler httpkit.Consumer) {
	if d.consumers == nil {
		d.consumers = map[string]httpkit.Consumer{httpkit.JSONMime: httpkit.JSONConsumer()}
	}
	d.consumers[strings.ToLower(mediaType)] = handler
}
Exemplo n.º 27
0
// UnmarshalJSON unmarshals this object with a polymorphic type from a JSON structure
func (m *ProductRatePlan) UnmarshalJSON(raw []byte) error {
	var data struct {
		AggregatingComponents []*AggregatingComponent `json:"aggregatingComponents,omitempty"`

		BillingEntity *string `json:"billingEntity,omitempty"`

		ChangedBy *string `json:"changedBy,omitempty"`

		CreateZeroValuedInvoices bool `json:"createZeroValuedInvoices,omitempty"`

		Created strfmt.DateTime `json:"created,omitempty"`

		Crmid *string `json:"crmid,omitempty"`

		Currency string `json:"currency,omitempty"`

		DisplayName *string `json:"displayName,omitempty"`

		Duration int32 `json:"duration,omitempty"`

		DurationPeriod string `json:"durationPeriod,omitempty"`

		FailedPaymentBehaviour string `json:"failedPaymentBehaviour,omitempty"`

		FixedTermDefinitions []*MutableBillingEntity `json:"fixedTermDefinitions,omitempty"`

		ID *string `json:"id,omitempty"`

		InvoiceIssueType *string `json:"invoiceIssueType,omitempty"`

		IssueDuration int32 `json:"issueDuration,omitempty"`

		IssuePeriod *string `json:"issuePeriod,omitempty"`

		LocalisedTax bool `json:"localisedTax,omitempty"`

		MigrationBehaviour string `json:"migrationBehaviour,omitempty"`

		Name string `json:"name,omitempty"`

		NotificationObjectGraph *string `json:"notificationObjectGraph,omitempty"`

		ProRataMode string `json:"proRataMode,omitempty"`

		Product *Product `json:"product,omitempty"`

		ProductID string `json:"productID,omitempty"`

		ProductType *string `json:"productType,omitempty"`

		PublicName *string `json:"publicName,omitempty"`

		RecursionType *string `json:"recursionType,omitempty"`

		Status *string `json:"status,omitempty"`

		TaxStatus string `json:"taxStatus,omitempty"`

		Taxation []*MutableBillingEntity `json:"taxation,omitempty"`

		Trial int32 `json:"trial,omitempty"`

		TrialPeriod *string `json:"trialPeriod,omitempty"`

		Updated strfmt.DateTime `json:"updated,omitempty"`

		ValidFrom strfmt.DateTime `json:"validFrom,omitempty"`

		ValidTill strfmt.DateTime `json:"validTill,omitempty"`
	}

	if err := json.Unmarshal(raw, &data); err != nil {
		return err
	}

	var pricingComponents []PricingComponent
	untypedObj := make(map[string]interface{})
	if err := json.Unmarshal(raw, &untypedObj); err != nil {
		return err
	}
	if untypedPricingComponents, ok := untypedObj["pricingComponents"]; ok {
		if slcPricingComponents, ok := untypedPricingComponents.([]interface{}); ok {
			for _, slcEl := range slcPricingComponents {
				slcJSON, _ := json.Marshal(slcEl)
				slcObj, err := UnmarshalPricingComponent(bytes.NewBuffer(slcJSON), httpkit.JSONConsumer())
				if err != nil {
					return err
				}
				pricingComponents = append(pricingComponents, slcObj)
			}
		}
	}

	var result ProductRatePlan
	result.AggregatingComponents = data.AggregatingComponents
	result.BillingEntity = data.BillingEntity
	result.ChangedBy = data.ChangedBy
	result.CreateZeroValuedInvoices = data.CreateZeroValuedInvoices
	result.Created = data.Created
	result.Crmid = data.Crmid
	result.Currency = data.Currency
	result.DisplayName = data.DisplayName
	result.Duration = data.Duration
	result.DurationPeriod = data.DurationPeriod
	result.FailedPaymentBehaviour = data.FailedPaymentBehaviour
	result.FixedTermDefinitions = data.FixedTermDefinitions
	result.ID = data.ID
	result.InvoiceIssueType = data.InvoiceIssueType
	result.IssueDuration = data.IssueDuration
	result.IssuePeriod = data.IssuePeriod
	result.LocalisedTax = data.LocalisedTax
	result.MigrationBehaviour = data.MigrationBehaviour
	result.Name = data.Name
	result.NotificationObjectGraph = data.NotificationObjectGraph
	result.PricingComponents = pricingComponents
	result.ProRataMode = data.ProRataMode
	result.Product = data.Product
	result.ProductID = data.ProductID
	result.ProductType = data.ProductType
	result.PublicName = data.PublicName
	result.RecursionType = data.RecursionType
	result.Status = data.Status
	result.TaxStatus = data.TaxStatus
	result.Taxation = data.Taxation
	result.Trial = data.Trial
	result.TrialPeriod = data.TrialPeriod
	result.Updated = data.Updated
	result.ValidFrom = data.ValidFrom
	result.ValidTill = data.ValidTill
	*m = result
	return nil
}
Exemplo n.º 28
0
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")
	})

}
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))
}
Exemplo n.º 30
0
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))
}