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))
}

结果:

相关推荐
哈里谢顿6 小时前
no_proxy介绍
网络协议
Oflycomm9 小时前
工业以太网四大主流协议(EtherCAT/PROFINET/EtherNet/IP/Modbus)技术参数深度对比
网络·网络协议·tcp/ip·欧飞信·plc模组
wangl_9211 小时前
Modbus RTU 与 Modbus TCP 深入指南-现代替代协议
网络·网络协议·tcp/ip·tcp·modbus·rtu
七夜zippoe13 小时前
Python RESTful API设计终极指南:从理论到企业级实战
开发语言·python·http·pandas·restful api
霸道流氓气质14 小时前
SpringAIAlibaba整合 Streamable HTTP 调用免费 MCP Server 实战全解
网络·网络协议·http
winlife_14 小时前
在 Unity Editor 里跑 HTTP MCP server:主线程边界与请求 marshal 的实现要点
http·unity·游戏引擎·多线程·mcp
上海云盾-小余16 小时前
网站木马植入原理与彻底清除、长效防御方案
网络·网络协议·tcp/ip·系统安全
源远流长jerry17 小时前
TCP 三次握手深度解析:从内核源码到生产实践
linux·运维·网络·网络协议·tcp/ip
加号317 小时前
【Python】 实现 HTTP 网络请求功能入门指南
网络·python·http
xlq2232219 小时前
53.tcp socket
linux·服务器·开发语言·网络·网络协议·tcp/ip