api.go 1.7 KB

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