github.com/gogf/gf/v2@v2.7.4/net/ghttp/ghttp_request_param_page.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package ghttp
     8  
     9  import (
    10  	"fmt"
    11  
    12  	"github.com/gogf/gf/v2/text/gregex"
    13  	"github.com/gogf/gf/v2/text/gstr"
    14  	"github.com/gogf/gf/v2/util/gpage"
    15  )
    16  
    17  // GetPage creates and returns the pagination object for given `totalSize` and `pageSize`.
    18  // NOTE THAT the page parameter name from clients is constantly defined as gpage.DefaultPageName
    19  // for simplification and convenience.
    20  func (r *Request) GetPage(totalSize, pageSize int) *gpage.Page {
    21  	// It must have Router object attribute.
    22  	if r.Router == nil {
    23  		panic("Router object not found")
    24  	}
    25  	var (
    26  		url            = *r.URL
    27  		urlTemplate    = url.Path
    28  		uriHasPageName = false
    29  	)
    30  	// Check the page variable in the URI.
    31  	if len(r.Router.RegNames) > 0 {
    32  		for _, name := range r.Router.RegNames {
    33  			if name == gpage.DefaultPageName {
    34  				uriHasPageName = true
    35  				break
    36  			}
    37  		}
    38  		if uriHasPageName {
    39  			if match, err := gregex.MatchString(r.Router.RegRule, url.Path); err == nil && len(match) > 0 {
    40  				if len(match) > len(r.Router.RegNames) {
    41  					urlTemplate = r.Router.Uri
    42  					for i, name := range r.Router.RegNames {
    43  						rule := fmt.Sprintf(`[:\*]%s|\{%s\}`, name, name)
    44  						if name == gpage.DefaultPageName {
    45  							urlTemplate, err = gregex.ReplaceString(rule, gpage.DefaultPagePlaceHolder, urlTemplate)
    46  						} else {
    47  							urlTemplate, err = gregex.ReplaceString(rule, match[i+1], urlTemplate)
    48  						}
    49  						if err != nil {
    50  							panic(err)
    51  						}
    52  					}
    53  				}
    54  			} else {
    55  				panic(err)
    56  			}
    57  		}
    58  	}
    59  	// Check the page variable in the query string.
    60  	if !uriHasPageName {
    61  		values := url.Query()
    62  		values.Set(gpage.DefaultPageName, gpage.DefaultPagePlaceHolder)
    63  		url.RawQuery = values.Encode()
    64  		// Replace the encoded "{.page}" to original "{.page}".
    65  		url.RawQuery = gstr.Replace(url.RawQuery, "%7B.page%7D", "{.page}")
    66  	}
    67  	if url.RawQuery != "" {
    68  		urlTemplate += "?" + url.RawQuery
    69  	}
    70  
    71  	return gpage.New(totalSize, pageSize, r.Get(gpage.DefaultPageName).Int(), urlTemplate)
    72  }