package main import ( "fmt" "net/http" "reflect" "strconv" ) type Calc struct{} // Add 加法运算 func (calc *Calc) Add(num1 float64, num2 float64) (op string, result float64) { op = "+" result = num1 + num2 return } // Subtract 减法运算 func (calc *Calc) Subtract(num1 float64, num2 float64) (op string, result float64) { op = "-" result = num1 - num2 return } // Multiply 乘法运算 func (calc *Calc) Multiply(num1 float64, num2 float64) (op string, result float64) { op = "*" result = num1 * num2 return } // Divide 除法运算 func (calc *Calc) Divide(num1 float64, num2 float64) (op string, result float64) { op = "/" result = num1 / num2 return } func main() { http.HandleFunc("/calc.html", func(writer http.ResponseWriter, request *http.Request) { query := request.URL.Query() op := query.Get("op") // 运算符,可选值:Add(加)、Subtract(减)、Multiply(乘)、Divide(除) num1, _ := strconv.ParseFloat(query.Get("num1"), 64) // 第1个操作数 num2, _ := strconv.ParseFloat(query.Get("num2"), 64) // 第2个操作数 calc := &Calc{} value := reflect.ValueOf(calc) method := value.MethodByName(op) // 根据接收到的op参数选择对应的方法 if method.IsValid() { // 设置方法参数 var input []reflect.Value input = append(input, reflect.ValueOf(num1)) // 第1个操作数 input = append(input, reflect.ValueOf(num2)) // 第2个操作数 ret := method.Call(input) // 调用方法 str := fmt.Sprintf("%+v %+v %+v = %+v", num1, ret[0], num2, ret[1]) _, _ = writer.Write([]byte(str)) } else { _, _ = writer.Write([]byte("op参数错误,只能为:Add(加)、Subtract(减)、Multiply(乘)、Divide(除)")) } }) err := http.ListenAndServe(":8080", nil) if err != nil { panic("启动HTTP服务器失败") } } // ========== 测试地址 ========== // // http://localhost:8080/calc.html?op=Add&num1=5&num2=2 5 + 2 = 7 // http://localhost:8080/calc.html?op=Subtract&num1=5&num2=2 5 - 2 = 3 // http://localhost:8080/calc.html?op=Multiply&num1=5&num2=2 5 * 2 = 10 // http://localhost:8080/calc.html?op=Divide&num1=5&num2=2 5 / 2 = 2.5 // http://localhost:8080/calc.html?op=Mod&num1=5&num2=2 op参数错误,只能为:Add(加)、Subtract(减)、Multiply(乘)、Divide(除)
Copyright © 2024 码农人生. All Rights Reserved