api.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package context
  5. import (
  6. "fmt"
  7. "strings"
  8. "github.com/Unknwon/paginater"
  9. "gopkg.in/macaron.v1"
  10. "github.com/gogits/gogs/modules/base"
  11. "github.com/gogits/gogs/modules/log"
  12. "github.com/gogits/gogs/modules/setting"
  13. )
  14. type APIContext struct {
  15. *Context
  16. Org *APIOrganization
  17. }
  18. // Error responses error message to client with given message.
  19. // If status is 500, also it prints error to log.
  20. func (ctx *APIContext) Error(status int, title string, obj interface{}) {
  21. var message string
  22. if err, ok := obj.(error); ok {
  23. message = err.Error()
  24. } else {
  25. message = obj.(string)
  26. }
  27. if status == 500 {
  28. log.Error(4, "%s: %s", title, message)
  29. }
  30. ctx.JSON(status, map[string]string{
  31. "message": message,
  32. "url": base.DOC_URL,
  33. })
  34. }
  35. // SetLinkHeader sets pagination link header by given totol number and page size.
  36. func (ctx *APIContext) SetLinkHeader(total, pageSize int) {
  37. page := paginater.New(total, pageSize, ctx.QueryInt("page"), 0)
  38. links := make([]string, 0, 4)
  39. if page.HasNext() {
  40. links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", setting.AppUrl, ctx.Req.URL.Path[1:], page.Next()))
  41. }
  42. if !page.IsLast() {
  43. links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"last\"", setting.AppUrl, ctx.Req.URL.Path[1:], page.TotalPages()))
  44. }
  45. if !page.IsFirst() {
  46. links = append(links, fmt.Sprintf("<%s%s?page=1>; rel=\"first\"", setting.AppUrl, ctx.Req.URL.Path[1:]))
  47. }
  48. if page.HasPrevious() {
  49. links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"prev\"", setting.AppUrl, ctx.Req.URL.Path[1:], page.Previous()))
  50. }
  51. if len(links) > 0 {
  52. ctx.Header().Set("Link", strings.Join(links, ","))
  53. }
  54. }
  55. func APIContexter() macaron.Handler {
  56. return func(c *Context) {
  57. ctx := &APIContext{
  58. Context: c,
  59. }
  60. c.Map(ctx)
  61. }
  62. }