Files
Gogs/pkg/context/api.go

76 lines
1.9 KiB
Go
Raw Normal View History

2016-03-13 17:37:44 -04:00
// Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package context
import (
"fmt"
"strings"
"github.com/Unknwon/paginater"
2017-02-09 19:29:59 -05:00
log "gopkg.in/clog.v1"
2016-03-13 17:37:44 -04:00
"gopkg.in/macaron.v1"
2018-05-27 08:53:48 +08:00
"github.com/gogs/gogs/pkg/setting"
2016-03-13 17:37:44 -04:00
)
type APIContext struct {
*Context
Org *APIOrganization
2016-03-13 17:37:44 -04:00
}
2018-05-27 08:53:48 +08:00
// FIXME: move to github.com/gogs/go-gogs-client
const DOC_URL = "https://github.com/gogs/go-gogs-client/wiki"
2017-04-05 09:17:21 -04:00
// Error responses error message to client with given message.
// If status is 500, also it prints error to log.
2017-06-03 07:26:09 -04:00
func (c *APIContext) Error(status int, title string, obj interface{}) {
var message string
if err, ok := obj.(error); ok {
message = err.Error()
} else {
message = obj.(string)
}
if status == 500 {
log.Error(3, "%s: %s", title, message)
}
2017-06-03 07:26:09 -04:00
c.JSON(status, map[string]string{
"message": message,
2017-04-05 09:17:21 -04:00
"url": DOC_URL,
})
}
// SetLinkHeader sets pagination link header by given totol number and page size.
2017-06-03 07:26:09 -04:00
func (c *APIContext) SetLinkHeader(total, pageSize int) {
page := paginater.New(total, pageSize, c.QueryInt("page"), 0)
links := make([]string, 0, 4)
if page.HasNext() {
2017-06-03 07:26:09 -04:00
links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", setting.AppURL, c.Req.URL.Path[1:], page.Next()))
}
if !page.IsLast() {
2017-06-03 07:26:09 -04:00
links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"last\"", setting.AppURL, c.Req.URL.Path[1:], page.TotalPages()))
}
if !page.IsFirst() {
2017-06-03 07:26:09 -04:00
links = append(links, fmt.Sprintf("<%s%s?page=1>; rel=\"first\"", setting.AppURL, c.Req.URL.Path[1:]))
}
if page.HasPrevious() {
2017-06-03 07:26:09 -04:00
links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"prev\"", setting.AppURL, c.Req.URL.Path[1:], page.Previous()))
}
if len(links) > 0 {
2017-06-03 07:26:09 -04:00
c.Header().Set("Link", strings.Join(links, ","))
}
}
2016-03-13 17:37:44 -04:00
func APIContexter() macaron.Handler {
2017-06-03 07:26:09 -04:00
return func(ctx *Context) {
c := &APIContext{
Context: ctx,
2016-03-13 17:37:44 -04:00
}
2017-06-03 07:26:09 -04:00
ctx.Map(c)
2016-03-13 17:37:44 -04:00
}
}