api.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. log "gopkg.in/clog.v1"
  10. "gopkg.in/macaron.v1"
  11. "github.com/gogits/gogs/pkg/setting"
  12. )
  13. type APIContext struct {
  14. *Context
  15. Org *APIOrganization
  16. }
  17. // FIXME: move to github.com/gogits/go-gogs-client
  18. const DOC_URL = "https://github.com/gogits/go-gogs-client/wiki"
  19. // Error responses error message to client with given message.
  20. // If status is 500, also it prints error to log.
  21. func (c *APIContext) Error(status int, title string, obj interface{}) {
  22. var message string
  23. if err, ok := obj.(error); ok {
  24. message = err.Error()
  25. } else {
  26. message = obj.(string)
  27. }
  28. if status == 500 {
  29. log.Error(3, "%s: %s", title, message)
  30. }
  31. c.JSON(status, map[string]string{
  32. "message": message,
  33. "url": DOC_URL,
  34. })
  35. }
  36. // SetLinkHeader sets pagination link header by given totol number and page size.
  37. func (c *APIContext) SetLinkHeader(total, pageSize int) {
  38. page := paginater.New(total, pageSize, c.QueryInt("page"), 0)
  39. links := make([]string, 0, 4)
  40. if page.HasNext() {
  41. links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", setting.AppURL, c.Req.URL.Path[1:], page.Next()))
  42. }
  43. if !page.IsLast() {
  44. links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"last\"", setting.AppURL, c.Req.URL.Path[1:], page.TotalPages()))
  45. }
  46. if !page.IsFirst() {
  47. links = append(links, fmt.Sprintf("<%s%s?page=1>; rel=\"first\"", setting.AppURL, c.Req.URL.Path[1:]))
  48. }
  49. if page.HasPrevious() {
  50. links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"prev\"", setting.AppURL, c.Req.URL.Path[1:], page.Previous()))
  51. }
  52. if len(links) > 0 {
  53. c.Header().Set("Link", strings.Join(links, ","))
  54. }
  55. }
  56. func APIContexter() macaron.Handler {
  57. return func(ctx *Context) {
  58. c := &APIContext{
  59. Context: ctx,
  60. }
  61. ctx.Map(c)
  62. }
  63. }