api.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. }
  17. // Error responses error message to client with given message.
  18. // If status is 500, also it prints error to log.
  19. func (ctx *APIContext) Error(status int, title string, obj interface{}) {
  20. var message string
  21. if err, ok := obj.(error); ok {
  22. message = err.Error()
  23. } else {
  24. message = obj.(string)
  25. }
  26. if status == 500 {
  27. log.Error(4, "%s: %s", title, message)
  28. }
  29. ctx.JSON(status, map[string]string{
  30. "message": message,
  31. "url": base.DOC_URL,
  32. })
  33. }
  34. func (ctx *APIContext) SetLinkHeader(total, pageSize int) {
  35. page := paginater.New(total, pageSize, ctx.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, ctx.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, ctx.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, ctx.Req.URL.Path[1:]))
  45. }
  46. if page.HasPrevious() {
  47. links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"prev\"", setting.AppUrl, ctx.Req.URL.Path[1:], page.Previous()))
  48. }
  49. if len(links) > 0 {
  50. ctx.Header().Set("Link", strings.Join(links, ","))
  51. }
  52. }
  53. func APIContexter() macaron.Handler {
  54. return func(c *Context) {
  55. ctx := &APIContext{
  56. Context: c,
  57. }
  58. c.Map(ctx)
  59. }
  60. }