code.gitea.io/gitea@v1.19.3/modules/context/form.go (about)

     1  // Copyright 2021 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package context
     5  
     6  import (
     7  	"strconv"
     8  	"strings"
     9  
    10  	"code.gitea.io/gitea/modules/util"
    11  )
    12  
    13  // FormString returns the first value matching the provided key in the form as a string
    14  func (ctx *Context) FormString(key string) string {
    15  	return ctx.Req.FormValue(key)
    16  }
    17  
    18  // FormStrings returns a string slice for the provided key from the form
    19  func (ctx *Context) FormStrings(key string) []string {
    20  	if ctx.Req.Form == nil {
    21  		if err := ctx.Req.ParseMultipartForm(32 << 20); err != nil {
    22  			return nil
    23  		}
    24  	}
    25  	if v, ok := ctx.Req.Form[key]; ok {
    26  		return v
    27  	}
    28  	return nil
    29  }
    30  
    31  // FormTrim returns the first value for the provided key in the form as a space trimmed string
    32  func (ctx *Context) FormTrim(key string) string {
    33  	return strings.TrimSpace(ctx.Req.FormValue(key))
    34  }
    35  
    36  // FormInt returns the first value for the provided key in the form as an int
    37  func (ctx *Context) FormInt(key string) int {
    38  	v, _ := strconv.Atoi(ctx.Req.FormValue(key))
    39  	return v
    40  }
    41  
    42  // FormInt64 returns the first value for the provided key in the form as an int64
    43  func (ctx *Context) FormInt64(key string) int64 {
    44  	v, _ := strconv.ParseInt(ctx.Req.FormValue(key), 10, 64)
    45  	return v
    46  }
    47  
    48  // FormBool returns true if the value for the provided key in the form is "1", "true" or "on"
    49  func (ctx *Context) FormBool(key string) bool {
    50  	s := ctx.Req.FormValue(key)
    51  	v, _ := strconv.ParseBool(s)
    52  	v = v || strings.EqualFold(s, "on")
    53  	return v
    54  }
    55  
    56  // FormOptionalBool returns an OptionalBoolTrue or OptionalBoolFalse if the value
    57  // for the provided key exists in the form else it returns OptionalBoolNone
    58  func (ctx *Context) FormOptionalBool(key string) util.OptionalBool {
    59  	value := ctx.Req.FormValue(key)
    60  	if len(value) == 0 {
    61  		return util.OptionalBoolNone
    62  	}
    63  	s := ctx.Req.FormValue(key)
    64  	v, _ := strconv.ParseBool(s)
    65  	v = v || strings.EqualFold(s, "on")
    66  	return util.OptionalBoolOf(v)
    67  }