本文整理汇总了Golang中github.com/goadesign/goa.Service类的典型用法代码示例。如果您正苦于以下问题:Golang Service类的具体用法?Golang Service怎么用?Golang Service使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Service类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
}
}
示例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")
}
示例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)
}
}
}
示例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,
}
}
示例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
}
示例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
}
示例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)
}
}
}
示例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)
}
}
}
示例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")
}
示例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")
}
示例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/")
}
示例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))
}
}
}
示例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}
}
示例14: NewUsersController
// NewUsersController creates a users controller.
func NewUsersController(service *goa.Service, db application.DB) *UsersController {
return &UsersController{Controller: service.NewController("UsersController"), db: db}
}
示例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}
}