本文整理汇总了Golang中github.com/goadesign/goa.Service类的典型用法代码示例。如果您正苦于以下问题:Golang Service类的具体用法?Golang Service怎么用?Golang Service使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Service类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: RequireHeader
// RequireHeader requires a request header to match a value pattern. If the
// header is missing or does not match then the failureStatus is the response
// (e.g. http.StatusUnauthorized). If pathPattern is nil then any path is
// included. If requiredHeaderValue is nil then any value is accepted so long as
// the header is non-empty.
func RequireHeader(
service *goa.Service,
pathPattern *regexp.Regexp,
requiredHeaderName string,
requiredHeaderValue *regexp.Regexp,
failureStatus int) goa.Middleware {
return func(h goa.Handler) goa.Handler {
return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) (err error) {
if pathPattern == nil || pathPattern.MatchString(req.URL.Path) {
matched := false
headerValue := req.Header.Get(requiredHeaderName)
if len(headerValue) > 0 {
if requiredHeaderValue == nil {
matched = true
} else {
matched = requiredHeaderValue.MatchString(headerValue)
}
}
if matched {
err = h(ctx, rw, req)
} else {
err = service.Send(ctx, failureStatus, http.StatusText(failureStatus))
}
} else {
err = h(ctx, rw, req)
}
return
}
}
}
开发者ID:ajoulie,项目名称:goa,代码行数:36,代码来源:required_header.go
示例2: MountAeController
// MountAeController "mounts" a Ae resource controller on the given service.
func MountAeController(service *goa.Service, ctrl AeController) {
initService(service)
var h goa.Handler
h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
// Check if there was an error loading the request
if err := goa.ContextError(ctx); err != nil {
return err
}
// Build the context
rctx, err := NewHealthAeContext(ctx, service)
if err != nil {
return err
}
return ctrl.Health(rctx)
}
service.Mux.Handle("GET", "/_ah/health", ctrl.MuxHandler("Health", h, nil))
service.LogInfo("mount", "ctrl", "Ae", "action", "Health", "route", "GET /_ah/health")
h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
// Check if there was an error loading the request
if err := goa.ContextError(ctx); err != nil {
return err
}
// Build the context
rctx, err := NewStartAeContext(ctx, service)
if err != nil {
return err
}
return ctrl.Start(rctx)
}
service.Mux.Handle("GET", "/_ah/start", ctrl.MuxHandler("Start", h, nil))
service.LogInfo("mount", "ctrl", "Ae", "action", "Start", "route", "GET /_ah/start")
}
开发者ID:goadesign,项目名称:swagger-service,代码行数:35,代码来源:controllers.go
示例3: ErrorHandler
// ErrorHandler turns a Go error into an HTTP response. It should be placed in the middleware chain
// below the logger middleware so the logger properly logs the HTTP response. ErrorHandler
// understands instances of goa.Error and returns the status and response body embodied in them,
// it turns other Go error types into a 500 internal error response.
// If verbose is false the details of internal errors is not included in HTTP responses.
func ErrorHandler(service *goa.Service, verbose bool) goa.Middleware {
return func(h goa.Handler) goa.Handler {
return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
e := h(ctx, rw, req)
if e == nil {
return nil
}
status := http.StatusInternalServerError
var respBody interface{}
if err, ok := e.(*goa.Error); ok {
status = err.Status
respBody = err
goa.ContextResponse(ctx).ErrorCode = err.Code
rw.Header().Set("Content-Type", goa.ErrorMediaIdentifier)
} else {
respBody = e.Error()
rw.Header().Set("Content-Type", "text/plain")
}
if status >= 500 && status < 600 {
reqID := ctx.Value(reqIDKey)
if reqID == nil {
reqID = shortID()
ctx = context.WithValue(ctx, reqIDKey, reqID)
}
goa.LogError(ctx, "uncaught error", "id", reqID, "msg", respBody)
if !verbose {
rw.Header().Set("Content-Type", goa.ErrorMediaIdentifier)
respBody = goa.ErrInternal("internal error [%s]", reqID)
}
}
return service.Send(ctx, status, respBody)
}
}
}
开发者ID:ajoulie,项目名称:goa,代码行数:40,代码来源:error_handler.go
示例4: NewWorkItemLinkController
// NewWorkItemLinkController creates a work-item-link controller.
func NewWorkItemLinkController(service *goa.Service, db application.DB) *WorkItemLinkController {
if db == nil {
panic("db must not be nil")
}
return &WorkItemLinkController{
Controller: service.NewController("WorkItemLinkController"),
db: db,
}
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:10,代码来源:work-item-link.go
示例5: unmarshalCreateBottlePayload
// unmarshalCreateBottlePayload unmarshals the request body into the context request data Payload field.
func unmarshalCreateBottlePayload(ctx context.Context, service *goa.Service, req *http.Request) error {
payload := &createBottlePayload{}
if err := service.DecodeRequest(req, payload); err != nil {
return err
}
if err := payload.Validate(); err != nil {
return err
}
goa.ContextRequest(ctx).Payload = payload.Publicize()
return nil
}
开发者ID:Rahmadkurniawan,项目名称:2016-talks,代码行数:12,代码来源:controllers.go
示例6: StartAeOK
// StartAeOK runs the method Start of the given controller with the given parameters.
// It returns the response writer so it's possible to inspect the response headers.
// If ctx is nil then context.Background() is used.
// If service is nil then a default service is created.
func StartAeOK(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.AeController) http.ResponseWriter {
// Setup service
var (
logBuf bytes.Buffer
resp interface{}
respSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }
)
if service == nil {
service = goatest.Service(&logBuf, respSetter)
} else {
logger := log.New(&logBuf, "", log.Ltime)
service.WithLogger(goa.NewLogger(logger))
newEncoder := func(io.Writer) goa.Encoder { return respSetter }
service.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder
service.Encoder.Register(newEncoder, "*/*")
}
// Setup request context
rw := httptest.NewRecorder()
u := &url.URL{
Path: fmt.Sprintf("/_ah/start"),
}
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
panic("invalid test " + err.Error()) // bug
}
prms := url.Values{}
if ctx == nil {
ctx = context.Background()
}
goaCtx := goa.NewContext(goa.WithAction(ctx, "AeTest"), rw, req, prms)
startCtx, err := app.NewStartAeContext(goaCtx, service)
if err != nil {
panic("invalid test data " + err.Error()) // bug
}
// Perform action
err = ctrl.Start(startCtx)
// Validate response
if err != nil {
t.Fatalf("controller returned %s, logs:\n%s", err, logBuf.String())
}
if rw.Code != 200 {
t.Errorf("invalid response status code: got %+v, expected 200", rw.Code)
}
// Return results
return rw
}
开发者ID:goadesign,项目名称:swagger-service,代码行数:55,代码来源:ae_testing.go
示例7: ErrorHandler
// ErrorHandler turns a Go error into an JSONAPI HTTP response. It should be placed in the middleware chain
// below the logger middleware so the logger properly logs the HTTP response. ErrorHandler
// understands instances of goa.ServiceError and returns the status and response body embodied in
// them, it turns other Go error types into a 500 internal error response.
// If verbose is false the details of internal errors is not included in HTTP responses.
// If you use github.com/pkg/errors then wrapping the error will allow a trace to be printed to the logs
func ErrorHandler(service *goa.Service, verbose bool) goa.Middleware {
return func(h goa.Handler) goa.Handler {
return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
e := h(ctx, rw, req)
if e == nil {
return nil
}
cause := errs.Cause(e)
status := http.StatusInternalServerError
var respBody interface{}
respBody, status = ErrorToJSONAPIErrors(e)
rw.Header().Set("Content-Type", ErrorMediaIdentifier)
if err, ok := cause.(goa.ServiceError); ok {
status = err.ResponseStatus()
//respBody = err
goa.ContextResponse(ctx).ErrorCode = err.Token()
//rw.Header().Set("Content-Type", ErrorMediaIdentifier)
} else {
//respBody = e.Error()
//rw.Header().Set("Content-Type", "text/plain")
}
if status >= 500 && status < 600 {
//reqID := ctx.Value(reqIDKey)
reqID := ctx.Value(1) // TODO remove this hack
if reqID == nil {
reqID = shortID()
//ctx = context.WithValue(ctx, reqIDKey, reqID)
ctx = context.WithValue(ctx, 1, reqID) // TODO remove this hack
}
log.Error(ctx, map[string]interface{}{
"msg": respBody,
"err": fmt.Sprintf("%+v", e),
}, "uncaught error detected in ErrorHandler")
if !verbose {
rw.Header().Set("Content-Type", goa.ErrorMediaIdentifier)
msg := errors.NewInternalError(fmt.Sprintf("%s [%s]", http.StatusText(http.StatusInternalServerError), reqID))
//respBody = goa.ErrInternal(msg)
respBody, status = ErrorToJSONAPIErrors(msg)
// Preserve the ID of the original error as that's what gets logged, the client
// received error ID must match the original
// TODO for JSONAPI this won't work I guess.
if origErrID := goa.ContextResponse(ctx).ErrorCode; origErrID != "" {
respBody.(*goa.ErrorResponse).ID = origErrID
}
}
}
return service.Send(ctx, status, respBody)
}
}
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:57,代码来源:error_handler.go
示例8: ErrorHandler
// ErrorHandler turns a Go error into an HTTP response. It should be placed in the middleware chain
// below the logger middleware so the logger properly logs the HTTP response. ErrorHandler
// understands instances of goa.ServiceError and returns the status and response body embodied in
// them, it turns other Go error types into a 500 internal error response.
// If verbose is false the details of internal errors is not included in HTTP responses.
// If you use github.com/pkg/errors then wrapping the error will allow a trace to be printed to the logs
func ErrorHandler(service *goa.Service, verbose bool) goa.Middleware {
return func(h goa.Handler) goa.Handler {
return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
e := h(ctx, rw, req)
if e == nil {
return nil
}
cause := errors.Cause(e)
status := http.StatusInternalServerError
var respBody interface{}
if err, ok := cause.(goa.ServiceError); ok {
status = err.ResponseStatus()
respBody = err
goa.ContextResponse(ctx).ErrorCode = err.Token()
rw.Header().Set("Content-Type", goa.ErrorMediaIdentifier)
} else {
respBody = e.Error()
rw.Header().Set("Content-Type", "text/plain")
}
if status >= 500 && status < 600 {
reqID := ctx.Value(reqIDKey)
if reqID == nil {
reqID = shortID()
ctx = context.WithValue(ctx, reqIDKey, reqID)
}
goa.LogError(ctx, "uncaught error", "err", fmt.Sprintf("%+v", e), "id", reqID, "msg", respBody)
if !verbose {
rw.Header().Set("Content-Type", goa.ErrorMediaIdentifier)
msg := fmt.Sprintf("%s [%s]", http.StatusText(http.StatusInternalServerError), reqID)
respBody = goa.ErrInternal(msg)
// Preserve the ID of the original error as that's what gets logged, the client
// received error ID must match the original
if origErrID := goa.ContextResponse(ctx).ErrorCode; origErrID != "" {
respBody.(*goa.ErrorResponse).ID = origErrID
}
}
}
return service.Send(ctx, status, respBody)
}
}
}
开发者ID:smessier,项目名称:goa,代码行数:47,代码来源:error_handler.go
示例9: MountSpecController
// MountSpecController "mounts" a Spec resource controller on the given service.
func MountSpecController(service *goa.Service, ctrl SpecController) {
initService(service)
var h goa.Handler
service.Mux.Handle("OPTIONS", "/swagger/spec", ctrl.MuxHandler("preflight", handleSpecOrigin(cors.HandlePreflight()), nil))
h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
// Check if there was an error loading the request
if err := goa.ContextError(ctx); err != nil {
return err
}
// Build the context
rctx, err := NewShowSpecContext(ctx, service)
if err != nil {
return err
}
return ctrl.Show(rctx)
}
h = handleSpecOrigin(h)
service.Mux.Handle("GET", "/swagger/spec", ctrl.MuxHandler("Show", h, nil))
service.LogInfo("mount", "ctrl", "Spec", "action", "Show", "route", "GET /swagger/spec")
}
开发者ID:goadesign,项目名称:swagger-service,代码行数:22,代码来源:controllers.go
示例10: MountBottleController
// MountBottleController "mounts" a Bottle resource controller on the given service.
func MountBottleController(service *goa.Service, ctrl BottleController) {
initService(service)
var h goa.Handler
h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
// Check if there was an error loading the request
if err := goa.ContextError(ctx); err != nil {
return err
}
// Build the context
rctx, err := NewCreateBottleContext(ctx, service)
if err != nil {
return err
}
// Build the payload
if rawPayload := goa.ContextRequest(ctx).Payload; rawPayload != nil {
rctx.Payload = rawPayload.(*CreateBottlePayload)
} else {
return goa.MissingPayloadError()
}
return ctrl.Create(rctx)
}
service.Mux.Handle("POST", "/bottles", ctrl.MuxHandler("Create", h, unmarshalCreateBottlePayload))
service.LogInfo("mount", "ctrl", "Bottle", "action", "Create", "route", "POST /bottles")
h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
// Check if there was an error loading the request
if err := goa.ContextError(ctx); err != nil {
return err
}
// Build the context
rctx, err := NewShowBottleContext(ctx, service)
if err != nil {
return err
}
return ctrl.Show(rctx)
}
service.Mux.Handle("GET", "/bottles/:id", ctrl.MuxHandler("Show", h, nil))
service.LogInfo("mount", "ctrl", "Bottle", "action", "Show", "route", "GET /bottles/:id")
}
开发者ID:Rahmadkurniawan,项目名称:2016-talks,代码行数:41,代码来源:controllers.go
示例11: MountSwaggerController
// MountSwaggerController "mounts" a Swagger resource controller on the given service.
func MountSwaggerController(service *goa.Service, ctrl SwaggerController) {
initService(service)
var h goa.Handler
h = ctrl.FileHandler("/swagger-ui/*filepath", "swagger-ui/")
service.Mux.Handle("GET", "/swagger-ui/*filepath", ctrl.MuxHandler("serve", h, nil))
service.LogInfo("mount", "ctrl", "Swagger", "files", "swagger-ui/", "route", "GET /swagger-ui/*filepath")
h = ctrl.FileHandler("/swagger.json", "swagger/swagger.json")
service.Mux.Handle("GET", "/swagger.json", ctrl.MuxHandler("serve", h, nil))
service.LogInfo("mount", "ctrl", "Swagger", "files", "swagger/swagger.json", "route", "GET /swagger.json")
h = ctrl.FileHandler("/swagger-ui/", "swagger-ui/index.html")
service.Mux.Handle("GET", "/swagger-ui/", ctrl.MuxHandler("serve", h, nil))
service.LogInfo("mount", "ctrl", "Swagger", "files", "swagger-ui/index.html", "route", "GET /swagger-ui/")
}
开发者ID:Rahmadkurniawan,项目名称:2016-talks,代码行数:17,代码来源:controllers.go
示例12: MountPreflightController
// MountPreflightController mounts the handlers for the CORS preflight requests onto service.
func MountPreflightController(service goa.Service, spec Specification) {
for _, res := range spec {
path := res.Path
if res.IsPathPrefix {
if strings.HasSuffix(path, "/") {
path += "*cors"
} else {
path += "/*cors"
}
}
handle := service.ServeMux().Lookup("OPTIONS", path)
if handle == nil {
h := func(ctx *goa.Context) error {
return ctx.Respond(200, nil)
}
ctrl := service.NewController("cors")
service.ServeMux().Handle("OPTIONS", path, ctrl.HandleFunc("preflight", h, nil))
}
}
}
开发者ID:jim-slattery-rs,项目名称:middleware,代码行数:21,代码来源:middleware.go
示例13: NewWorkItemCommentsController
// NewWorkItemCommentsController creates a work-item-relationships-comments controller.
func NewWorkItemCommentsController(service *goa.Service, db application.DB) *WorkItemCommentsController {
return &WorkItemCommentsController{Controller: service.NewController("WorkItemRelationshipsCommentsController"), db: db}
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:4,代码来源:work-item-comments.go
示例14: NewUsersController
// NewUsersController creates a users controller.
func NewUsersController(service *goa.Service, db application.DB) *UsersController {
return &UsersController{Controller: service.NewController("UsersController"), db: db}
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:4,代码来源:users.go
示例15: NewTrackerqueryController
// NewTrackerqueryController creates a trackerquery controller.
func NewTrackerqueryController(service *goa.Service, db application.DB, scheduler *remoteworkitem.Scheduler) *TrackerqueryController {
return &TrackerqueryController{Controller: service.NewController("TrackerqueryController"), db: db, scheduler: scheduler}
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:4,代码来源:trackerquery.go
示例16:
Describe("GetMany", func() {
It("returns nil if not initialized", func() {
Ω(ctx.GetMany("foo")).Should(BeNil())
})
})
Describe("RawPayload", func() {
It("returns nil if not initialized", func() {
Ω(ctx.RawPayload()).Should(BeNil())
})
})
Context("with a request response", func() {
const appName = "foo"
var app goa.Service
const resName = "res"
const actName = "act"
var handler, unmarshaler goa.Handler
const reqBody = `"body"`
const respStatus = 200
var respContent = []byte("response")
var handleFunc goa.HandleFunc
var rw http.ResponseWriter
var request *http.Request
var params url.Values
BeforeEach(func() {
app = goa.New(appName)
handler = func(c *goa.Context) error {
ctx = c
开发者ID:jianjunliu,项目名称:goa,代码行数:30,代码来源:context_test.go
示例17: MountAccountController
// MountAccountController "mounts" a Account resource controller on the given service.
func MountAccountController(service goa.Service, ctrl AccountController) {
// Setup encoders and decoders. This is idempotent and is done by each MountXXX function.
tmp15 := goa.GobEncoderFactory()
service.SetEncoder(tmp15, false, "application/gob", "application/x-gob")
tmp16 := goa.JSONEncoderFactory()
service.SetEncoder(tmp16, true, "application/json")
tmp17 := goa.XMLEncoderFactory()
service.SetEncoder(tmp17, false, "application/xml", "text/xml")
tmp18 := goa.GobDecoderFactory()
service.SetDecoder(tmp18, false, "application/gob", "application/x-gob")
tmp19 := goa.JSONDecoderFactory()
service.SetDecoder(tmp19, true, "application/json")
tmp20 := goa.XMLDecoderFactory()
service.SetDecoder(tmp20, false, "application/xml", "text/xml")
// Setup endpoint handler
var h goa.Handler
mux := service.ServeMux()
h = func(c *goa.Context) error {
ctx, err := NewCreateAccountContext(c)
ctx.Payload = ctx.RawPayload().(*CreateAccountPayload)
if err != nil {
return goa.NewBadRequestError(err)
}
return ctrl.Create(ctx)
}
mux.Handle("POST", "/cellar/accounts", ctrl.HandleFunc("Create", h, unmarshalCreateAccountPayload))
service.Info("mount", "ctrl", "Account", "action", "Create", "route", "POST /cellar/accounts")
h = func(c *goa.Context) error {
ctx, err := NewDeleteAccountContext(c)
if err != nil {
return goa.NewBadRequestError(err)
}
return ctrl.Delete(ctx)
}
mux.Handle("DELETE", "/cellar/accounts/:accountID", ctrl.HandleFunc("Delete", h, nil))
service.Info("mount", "ctrl", "Account", "action", "Delete", "route", "DELETE /cellar/accounts/:accountID")
h = func(c *goa.Context) error {
ctx, err := NewShowAccountContext(c)
if err != nil {
return goa.NewBadRequestError(err)
}
return ctrl.Show(ctx)
}
mux.Handle("GET", "/cellar/accounts/:accountID", ctrl.HandleFunc("Show", h, nil))
service.Info("mount", "ctrl", "Account", "action", "Show", "route", "GET /cellar/accounts/:accountID")
h = func(c *goa.Context) error {
ctx, err := NewUpdateAccountContext(c)
ctx.Payload = ctx.RawPayload().(*UpdateAccountPayload)
if err != nil {
return goa.NewBadRequestError(err)
}
return ctrl.Update(ctx)
}
mux.Handle("PUT", "/cellar/accounts/:accountID", ctrl.HandleFunc("Update", h, unmarshalUpdateAccountPayload))
service.Info("mount", "ctrl", "Account", "action", "Update", "route", "PUT /cellar/accounts/:accountID")
}
开发者ID:derekperkins,项目名称:gorma,代码行数:58,代码来源:controllers.go
示例18:
It("wraps it in a middleware", func() {
Ω(mErr).ShouldNot(HaveOccurred())
h := func(ctx *goa.Context) error { return nil }
Ω(middleware(h)(ctx)).ShouldNot(HaveOccurred())
Ω(ctx.ResponseStatus()).Should(Equal(200))
})
})
})
})
var _ = Describe("LogRequest", func() {
var handler *testHandler
var ctx *goa.Context
var service goa.Service
params := url.Values{"param": []string{"value"}}
payload := map[string]interface{}{"payload": 42}
BeforeEach(func() {
service = goa.New("test")
service.SetEncoder(goa.JSONEncoderFactory(), true, "*/*")
req, err := http.NewRequest("POST", "/goo", strings.NewReader(`{"payload":42}`))
Ω(err).ShouldNot(HaveOccurred())
rw := new(testResponseWriter)
ctx = goa.NewContext(nil, service, req, rw, params)
ctx.SetPayload(payload)
handler = new(testHandler)
logger := log15.New("test", "test")
logger.SetHandler(handler)
ctx.Logger = logger
开发者ID:jim-slattery-rs,项目名称:middleware,代码行数:30,代码来源:middleware_test.go
示例19: MountController
// MountController mounts the JavaScript example controller under "/js".
func MountController(service *goa.Service) {
// Serve static files under js
service.ServeFiles("/js/*filepath", "/Users/nii236/Go/src/github.com/nii236/go-react-webpack/js")
goa.Info(goa.RootContext, "mount", goa.KV{"ctrl", "JS"}, goa.KV{"action", "ServeFiles"}, goa.KV{"route", "GET /js/*"})
}
开发者ID:nii236,项目名称:go-react-webpack,代码行数:6,代码来源:example.go
示例20: initService
// initService sets up the service encoders, decoders and mux.
func initService(service *goa.Service) {
if inited {
return
}
inited = true
// Setup encoders and decoders
service.Encoder(goa.NewJSONEncoder, "application/json")
service.Decoder(goa.NewJSONDecoder, "application/json")
service.Decoder(goa.NewGobDecoder, "application/gob", "application/x-gob")
service.Decoder(goa.NewXMLDecoder, "application/xml")
// Setup default encoder and decoder
service.Encoder(goa.NewJSONEncoder, "*/*")
service.Decoder(goa.NewJSONDecoder, "*/*")
}
开发者ID:nii236,项目名称:go-react-webpack,代码行数:17,代码来源:controllers.go
注:本文中的github.com/goadesign/goa.Service类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论