当前位置: 首页>>代码示例>>Golang>>正文


Golang Context.Response方法代码示例

本文整理汇总了Golang中github.com/labstack/echo.Context.Response方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.Response方法的具体用法?Golang Context.Response怎么用?Golang Context.Response使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/labstack/echo.Context的用法示例。


在下文中一共展示了Context.Response方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: httpTimeline

func httpTimeline(c *echo.Context) error {
	r := c.Request()
	w := c.Response()
	e := c.Get("engine").(storage.Engine)

	domain := c.Param("domain")

	iter, code, err := domainIteratorResource(domain, r, e)

	if err != nil {
		return c.JSON(code, map[string]interface{}{
			"error": fmt.Sprint(err),
		})
	}

	events, err := view.Timeline(iter, view.Descending)

	if err != nil {
		return c.JSON(code, map[string]interface{}{
			"error": fmt.Sprint(err),
		})
	}

	return json.NewEncoder(w).Encode(events)
}
开发者ID:glycerine,项目名称:origins,代码行数:25,代码来源:resources.go

示例2: CustomHTTPErrorHandler

func CustomHTTPErrorHandler(err error, c echo.Context) {
	code := http.StatusInternalServerError
	response := ErrResponse{}

	switch v := err.(type) {
	case types.ErrNotFound:
		code = http.StatusNotFound
		response = ErrResponse{"error": v.Error()}
	case types.ErrConflict:
		code = http.StatusConflict
		response = ErrResponse{"error": v.Error()}
	case types.ErrValidation:
		code = http.StatusUnprocessableEntity
		response = ErrResponse{"error": v.Errors}
	case *echo.HTTPError:
		response = ErrResponse{"error": v.Message}
	default:
		response = ErrResponse{"error": v.Error()}
	}

	if !c.Response().Committed {
		if c.Request().Method == echo.HEAD { // Issue #608
			c.NoContent(code)
		} else {
			c.JSON(code, response)
		}
	}
}
开发者ID:luizbafilho,项目名称:fusis,代码行数:28,代码来源:error.go

示例3: DeleteSession

// DeleteSession delete session by name.
func DeleteSession(ctx *echo.Context, sessionName string) error {
	ss, err := store.Get(ctx.Request(), sessionName)
	if err != nil {
		return err
	}
	return store.Delete(ctx.Request(), ctx.Response(), ss)
}
开发者ID:jwulf,项目名称:zedlist,代码行数:8,代码来源:utils.go

示例4: apiHandler

func apiHandler(c *echo.Context) error {
	i := 0
	response := c.Response()

	// ustawiamy header na event-stream rozpoznawalny przez przeglądarkę
	response.Header().Set(echo.ContentType, "text/event-stream")
	response.WriteHeader(http.StatusOK) // 200

	for {
		location := locations[i]
		response.Write([]byte("data: "))

		if err := json.NewEncoder(response).Encode(location); err != nil {
			return err
		}

		response.Write([]byte("\n\n"))
		response.Flush()
		time.Sleep(100 * time.Millisecond)

		i++
		if i >= len(locations) {
			i = 0
		}

	}

	return nil
}
开发者ID:exu,项目名称:go-workshops,代码行数:29,代码来源:app.go

示例5: httpLog

func httpLog(c *echo.Context) error {
	r := c.Request()
	w := c.Response()
	e := c.Get("engine").(storage.Engine)

	domain := c.Param("domain")

	iter, code, err := domainIteratorResource(domain, r, e)

	if err != nil {
		return c.JSON(code, map[string]interface{}{
			"error": fmt.Sprint(err),
		})
	}

	facts, err := origins.ReadAll(iter)

	if err != nil {
		return c.JSON(code, map[string]interface{}{
			"error": fmt.Sprint(err),
		})
	}

	return json.NewEncoder(w).Encode(facts)
}
开发者ID:glycerine,项目名称:origins,代码行数:25,代码来源:resources.go

示例6: IndexHandler

func (rc *ResourceController) IndexHandler(c *echo.Context) error {
	defer func() error {
		if r := recover(); r != nil {
			switch x := r.(type) {
			case search.Error:
				return c.JSON(x.HTTPStatus, x.OperationOutcome)
			default:
				outcome := models.NewOperationOutcome("fatal", "exception", "")
				return c.JSON(http.StatusInternalServerError, outcome)
			}
		}
		return nil
	}()

	searchQuery := search.Query{Resource: rc.Name, Query: c.Request().URL.RawQuery}
	baseURL := responseURL(c.Request(), rc.Name)
	bundle, err := rc.DAL.Search(*baseURL, searchQuery)
	if err != nil {
		return err
	}

	c.Set("bundle", bundle)
	c.Set("Resource", rc.Name)
	c.Set("Action", "search")

	c.Response().Header().Set("Access-Control-Allow-Origin", "*")
	return c.JSON(http.StatusOK, bundle)
}
开发者ID:intervention-engine,项目名称:riskservice,代码行数:28,代码来源:resource_controller.go

示例7: getFeeds

func (s *APIServer) getFeeds(c echo.Context) error {
	dbuser := c.Get("dbuser").(*db.User)
	b := new(feedsReqBinder)

	if err := c.Bind(b); err != nil {
		return newError(c, "Unable to parse request", err)
	}

	var feeds []*db.FeedInfo
	var err error
	if b.Name != "" {
		feeds, err = s.DBH.GetUsersFeedsByName(dbuser, b.Name)
	} else {
		feeds, err = s.DBH.GetUsersFeeds(dbuser)
	}
	if err != nil {
		return newError(c, "Unable to get feeds", err)
	}

	feedInterface := make([]interface{}, len(feeds))

	for i, f := range feeds {
		feedInterface[i] = f
	}

	c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
	c.Response().WriteHeader(http.StatusOK)
	return jsonapi.MarshalManyPayload(c.Response(), feedInterface)
}
开发者ID:hobeone,项目名称:rss2go,代码行数:29,代码来源:server.go

示例8: success

func success(ctx echo.Context, data interface{}) error {
	result := map[string]interface{}{
		"ok":   1,
		"msg":  "操作成功",
		"data": data,
	}

	b, err := json.Marshal(result)
	if err != nil {
		return err
	}

	go func(b []byte) {
		if cacheKey := ctx.Get(nosql.CacheKey); cacheKey != nil {
			nosql.DefaultLRUCache.CompressAndAdd(cacheKey, b, nosql.NewCacheData())
		}
	}(b)

	if ctx.Response().Committed() {
		getLogger(ctx).Flush()
		return nil
	}

	return ctx.JSONBlob(http.StatusOK, b)
}
开发者ID:studygolang,项目名称:studygolang,代码行数:25,代码来源:base.go

示例9: echov2Handler

// echov2-standard
func echov2Handler(c echov2.Context) error {
	if sleepTime > 0 {
		time.Sleep(sleepTimeDuration)
	}
	c.Response().Write(message)
	return nil
}
开发者ID:cokeboL,项目名称:go-web-framework-benchmark,代码行数:8,代码来源:server.go

示例10: handleDownloadTarFunc

func (h *handler) handleDownloadTarFunc(c echo.Context) error {
	pathToSend := c.QueryParam("path")
	fileFilter := c.QueryParam("file-filter")
	if strings.TrimSpace(pathToSend) == "" {
		return fmt.Errorf("Request does not contain query 'path' value")
	}

	var tarProvider tar_io.TarProvider
	if isDir, err := path_utils.DirectoryExists(pathToSend); err != nil {
		return fmt.Errorf("Unable to determine if path '%s' is a directory, error: %s", pathToSend, err.Error())
	} else if isDir {
		tarProvider = tar_io.Factories.TarProvider.Dir(pathToSend, fileFilter)
		h.logger.Infof("Now starting to send dir '%s'", pathToSend)
	} else if isFile, err := path_utils.FileExists(pathToSend); err != nil {
		return fmt.Errorf("Unable to determine if path '%s' is a file, error: %s", pathToSend, err.Error())
	} else if isFile {
		tarProvider = tar_io.Factories.TarProvider.File(pathToSend)
		h.logger.Infof("Now starting to send file '%s'", pathToSend)
	} else {
		return fmt.Errorf("Path '%s' is not an existing file or directory", pathToSend)
	}

	handler := &sendTarHandler{writer: c.Response()}
	err := tar_io.UploadProvider(tarProvider, handler)
	if err != nil {
		return fmt.Errorf("Unable to send file, error: %s", err.Error())
	}

	return nil
}
开发者ID:golang-devops,项目名称:go-psexec,代码行数:30,代码来源:handle_download_tar.go

示例11: FileServerHandler

// FileServerHandler function
func FileServerHandler(c *echo.Context) error {
	fileType := mime.TypeByExtension(filepath.Ext(filepath.Base(c.Request().URL.String())))
	log.Println(c.Request().URL.String()[1:])
	c.Response().Header().Set("Content-Type", fileType)
	io.Copy(c.Response(), bytes.NewReader(staticFiles.Get(c.Request().URL.String()[1:])))
	return nil
}
开发者ID:go-experimental,项目名称:mongo-me,代码行数:8,代码来源:main.go

示例12: Index

func Index(c *echo.Context) error {

	authCookie, err := c.Request().Cookie("testcook")
	logrus.Infof(">>> cooki: %+v, err: %+v", authCookie, err)

	dbconn := c.Get("db").(*mgo.Database)
	counts := dbconn.C("counts")

	if err := counts.Insert(&models.TestStruct{"index"}); err != nil {
		c.String(500, fmt.Sprintf("broken: %s", err.Error()))
		return nil
	}

	t, err := template.ParseFiles("static/html/layout.html", "static/html/greet.html", "static/html/mainPage.html")
	if err != nil {
		c.String(500, fmt.Sprintf("broken: %s", err.Error()))
		return nil
	}

	loggedIn := false
	user, ok := c.Get("user").(models.Account)
	if ok {
		loggedIn = user.Username != ""
	}
	args := map[string]interface{}{
		"Username": user.Username,
		"LoggedIn": loggedIn,
		"Logout":   fmt.Sprintf("http://username:[email protected]%s", viper.GetString("base_uri"))}
	t.Execute(c.Response(), args)
	return nil
}
开发者ID:mikerjacobi,项目名称:echomongo,代码行数:31,代码来源:common.go

示例13: getVersion

func getVersion(ctx *echo.Context) error {
	ctx.Response().Header().Set(echo.ContentType, echo.ApplicationJSON)
	return ctx.JSON(http.StatusOK, VersionInfo{
		Name:    APP_NAME,
		Version: APP_VERSION,
		Author:  APP_AUTHOR,
	})
}
开发者ID:jalateras,项目名称:version,代码行数:8,代码来源:version.go

示例14: SendProto

// 将结果写入到http请求(ProtoBuffer 格式)
func SendProto(c echo.Context, code int, data proto.Message) error {
	resp := c.Response()
	err := utils.SendFrame(resp, data)
	if err != nil {
		return err
	}
	resp.WriteHeader(code)
	return nil
}
开发者ID:asyoume,项目名称:paas_srv,代码行数:10,代码来源:utils.go

示例15: sendJSONResponse

func sendJSONResponse(toMarshal interface{}, c echo.Context) error {
	b, err := json.Marshal(toMarshal)
	if err != nil {
		return err
	}

	c.Response().Write(b)
	return nil
}
开发者ID:xuther,项目名称:pricetracker,代码行数:9,代码来源:handlers.go


注:本文中的github.com/labstack/echo.Context.Response方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。