api.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. }