题目要求:
题目
1.shape 接口有面积Area() float64和 周长Perimeter()fioat64 两个法。为`Circle` `Rectangle`实现`shape` 接口。
2.实现isGreater(shape1,shape2 shape)boo1 函数,用于比较两个形状的大小,并使用单元测试验证
3.实现http.Handler,作为HTTP服务比较Circle与 Rectangle 的大小。并使用香户端验证
请求示例:
curl --request POST \
--url http://localhost:8080/shape/isGreater \
--header 'content-type: application/json' \
--data '{"Shape1": {"Radius": 3}, "Shape2": {"Width": 2, "Height": 3}}'
代码
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
const pi = 3.14
type Shape interface {
Area() float64
Perimeter() float64
}
type Circle struct {
Radius float64
}
type Rectangle struct {
Height float64
Width float64
}
func (c Circle) Area() float64 {
return pi * c.Radius * c.Radius
}
func (c Circle) Perimeter() float64 {
return 2 * pi * c.Radius
}
func (r Rectangle) Area() float64 {
return r.Height * r.Width
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Height + r.Width)
}
func isGreater(s1, s2 Shape) bool {
if s1.Area() > s2.Area() {
fmt.Println("C1:%v is greater than C2:%v", s1, s2)
return true
}
fmt.Println("C1:%v is less than C2:%v", s1, s2)
return false
}
type RequestData struct {
Shape1 Circle `json:"Shape1"`
Shape2 Rectangle `json:"Shape2"`
}
// CompareHandler 处理比较两个形状面积的HTTP请求
func CompareHandler(w http.ResponseWriter, r *http.Request) {
var data RequestData
// 从请求体中解码JSON数据到RequestData结构体中
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
// 如果解码失败,返回400 Bad Request错误
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// 比较两个形状的面积
if isGreater(data.Shape1, data.Shape2) {
// 如果圆形面积较大,返回 "Circle is larger"
fmt.Fprintf(w, "Circle is larger")
} else {
// 否则,返回 "Rectangle is larger"
fmt.Fprintf(w, "Rectangle is larger")
}
}
func main() {
http.HandleFunc("/shape/isGreater", CompareHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
结果: