Golang实现简单的HTTP服务,响应RESTful请求判断形状大小

题目要求:

题目

1.shape 接口有面积Area() float64和 周长Perimeter()fioat64 两个法。为`Circle` `Rectangle`实现`shape` 接口。

2.实现isGreater(shape1,shape2 shape)boo1 函数,用于比较两个形状的大小,并使用单元测试验证

3.实现http.Handler,作为HTTP服务比较Circle与 Rectangle 的大小。并使用香户端验证

请求示例:

bash 复制代码
curl --request POST \
--url http://localhost:8080/shape/isGreater \
--header 'content-type: application/json' \
--data '{"Shape1": {"Radius": 3}, "Shape2": {"Width": 2, "Height": 3}}'

代码

Go 复制代码
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))
}

结果:

相关推荐
xiezhr1 天前
接口设计18条军规:写给那些半夜被“502”叫醒的人
java·api·restful
moonless02222 天前
FastAPI框架,这一小篇就能搞懂精髓。
http·fastapi
葡萄城技术团队3 天前
REST API 设计最佳实践指南 - 如何用 JavaScript、Node.js 和 Express.js 构建 REST API
restful
FPGA_Linuxer3 天前
FPGA 40 DAC线缆和光模块带光纤实现40G UDP差异
网络协议·fpga开发·udp
real 13 天前
传输层协议UDP
网络·网络协议·udp
ftpeak3 天前
从零开始使用 axum-server 构建 HTTP/HTTPS 服务
网络·http·https·rust·web·web app
hsjkdhs4 天前
网络编程之UDP广播与粘包问题
网络·网络协议·udp
yzx9910134 天前
接口协议全解析:从HTTP到gRPC,如何选择适合你的通信方案?
网络·人工智能·网络协议·flask·pygame
板鸭〈小号〉4 天前
UDP-Server(3)chat聊天室
网络·网络协议·udp
weixin_456904274 天前
使用HTTPS 服务在浏览器端使用摄像头的方式解析
网络协议·http·https