Home >Backend Development >Golang >Project examples based on golang custom functions
Custom functions allow extending functionality in Go applications. To create a custom function, use the func keyword and declare its name, parameters, and return type. To register a function for use, use http.HandleFunc to intercept the URL path and call the function. This tutorial demonstrates an example of a custom function that calculates the square of a given number, which can be used by sending a GET request to the /square URL path containing the query parameter x.
Project example based on Go language custom function implementation
Introduction
Custom functions allow you to extend the functionality of your Go application. This tutorial will guide you through a practical example of how to create and use custom functions.
Create a custom function
Use the func
keyword to create a custom function. Function names, parameters, and return types must be declared as valid types.
// 返回给定数字的平方 func square(x int) int { return x * x }
Register a custom function
To use a custom function, you must register it in your application. Use http.HandleFunc
to intercept a specific URL path and call a function.
package main import ( "net/http" ) func main() { // 注册 square 函数来处理 "/square" URL 路径 http.HandleFunc("/square", squareHandler) // 启动 HTTP 服务器 http.ListenAndServe(":8080", nil) } func squareHandler(w http.ResponseWriter, r *http.Request) { x := r.URL.Query().Get("x") result, err := strconv.Atoi(x) if err != nil { w.Write([]byte("Invalid input")) return } w.Write([]byte(strconv.Itoa(square(result)))) }
Practical case
In this example, the custom function square
is used to calculate the square of a given number.
To use this function, send a GET request to the "/square" URL path, including a query parameter named "x" that specifies the number whose square is to be calculated.
For example, enter the following URL into your browser:
http://localhost:8080/square?x=5
This will return the response:
25
Note:
Make sure Your custom function will not have side effects, such as modifying global variables or the file system. This ensures the security and consistency of your application.
The above is the detailed content of Project examples based on golang custom functions. For more information, please follow other related articles on the PHP Chinese website!