企業(yè)建設(shè)網(wǎng)站的步驟是什么意思sem賬戶托管
題目要求:
題目
1.shape 接口有面積Area() float64和 周長(zhǎng)Perimeter()fioat64 兩個(gè)法。為`Circle` `Rectangle`實(shí)現(xiàn)`shape` 接口。
2.實(shí)現(xiàn)isGreater(shape1,shape2 shape)boo1 函數(shù),用于比較兩個(gè)形狀的大小,并使用單元測(cè)試驗(yàn)證
3.實(shí)現(xiàn)http.Handler,作為HTTP服務(wù)比較Circle與 Rectangle 的大小。并使用香戶端驗(yàn)證
請(qǐng)求示例:
curl --request POST \
--url http://localhost:8080/shape/isGreater \
--header 'content-type: application/json' \
--data '{"Shape1": {"Radius": 3}, "Shape2": {"Width": 2, "Height": 3}}'
代碼
package mainimport ("encoding/json""fmt""log""net/http"
)const pi = 3.14type Shape interface {Area() float64Perimeter() float64
}type Circle struct {Radius float64
}type Rectangle struct {Height float64Width 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 處理比較兩個(gè)形狀面積的HTTP請(qǐng)求
func CompareHandler(w http.ResponseWriter, r *http.Request) {var data RequestData// 從請(qǐng)求體中解碼JSON數(shù)據(jù)到RequestData結(jié)構(gòu)體中err := json.NewDecoder(r.Body).Decode(&data)if err != nil {// 如果解碼失敗,返回400 Bad Request錯(cuò)誤http.Error(w, err.Error(), http.StatusBadRequest)return}// 比較兩個(gè)形狀的面積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))
}
結(jié)果: