gf/net/ghttp/ghttp_request_param_page.go

73 lines
2.1 KiB
Go
Raw Normal View History

2021-01-17 21:46:25 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
2020-03-06 11:01:03 +08:00
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package ghttp
import (
"fmt"
2021-11-13 23:23:55 +08:00
2021-10-11 21:41:56 +08:00
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gpage"
2020-03-06 11:01:03 +08:00
)
// GetPage creates and returns the pagination object for given `totalSize` and `pageSize`.
// NOTE THAT the page parameter name from client is constantly defined as gpage.DefaultPageName
2020-03-06 11:01:03 +08:00
// for simplification and convenience.
func (r *Request) GetPage(totalSize, pageSize int) *gpage.Page {
// It must have Router object attribute.
2020-03-06 11:01:03 +08:00
if r.Router == nil {
panic("Router object not found")
}
var (
url = *r.URL
urlTemplate = url.Path
uriHasPageName = false
)
2020-03-06 11:01:03 +08:00
// Check the page variable in the URI.
if len(r.Router.RegNames) > 0 {
for _, name := range r.Router.RegNames {
if name == gpage.DefaultPageName {
2020-03-06 11:01:03 +08:00
uriHasPageName = true
break
}
}
if uriHasPageName {
if match, err := gregex.MatchString(r.Router.RegRule, url.Path); err == nil && len(match) > 0 {
if len(match) > len(r.Router.RegNames) {
urlTemplate = r.Router.Uri
for i, name := range r.Router.RegNames {
rule := fmt.Sprintf(`[:\*]%s|\{%s\}`, name, name)
if name == gpage.DefaultPageName {
urlTemplate, err = gregex.ReplaceString(rule, gpage.DefaultPagePlaceHolder, urlTemplate)
2020-03-06 11:01:03 +08:00
} else {
urlTemplate, err = gregex.ReplaceString(rule, match[i+1], urlTemplate)
}
if err != nil {
panic(err)
2020-03-06 11:01:03 +08:00
}
}
}
} else {
panic(err)
2020-03-06 11:01:03 +08:00
}
}
}
// Check the page variable in the query string.
if !uriHasPageName {
values := url.Query()
values.Set(gpage.DefaultPageName, gpage.DefaultPagePlaceHolder)
2020-03-06 11:01:03 +08:00
url.RawQuery = values.Encode()
2020-03-21 23:13:31 +08:00
// Replace the encoded "{.page}" to original "{.page}".
2020-03-06 11:01:03 +08:00
url.RawQuery = gstr.Replace(url.RawQuery, "%7B.page%7D", "{.page}")
}
if url.RawQuery != "" {
urlTemplate += "?" + url.RawQuery
}
2021-09-27 21:27:24 +08:00
return gpage.New(totalSize, pageSize, r.Get(gpage.DefaultPageName).Int(), urlTemplate)
2020-03-06 11:01:03 +08:00
}