feat(server): 初始化HTTP服务器并添加产品数据结构

- 创建基础HTTP服务器,监听localhost:5000
- 实现StringHandle结构体处理HTTP请求
- 添加请求日志打印功能
- 忽略/favicon.ico请求并返回404状态
- 定义Product结构体及示例数据
- 实现产品税费计算和折扣应用方法
This commit is contained in:
2025-10-24 22:01:49 +08:00
parent 51c7ed5cbf
commit 84f29e3d48
4 changed files with 87 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
module httpserver
go 1.22

View File

@@ -0,0 +1,46 @@
package main
import (
"io"
"net/http"
)
type StringHandle struct {
message string
}
func (sh *StringHandle) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
Printfln("\n----------\nMethod: %v Protocol: %v Host: %v URL: %v URL.Host: %v RequestURI: %v",
request.Method, request.Proto, request.Host,
request.URL.String(), request.URL.Host, request.RequestURI)
for name, val := range request.Header {
Printfln("Header: %v = %v", name, val)
}
Printfln("RemoteAddr: %v", request.RemoteAddr)
Printfln("ContentLength: %v", request.ContentLength)
Printfln("Body: %v", request.Body)
Printfln("TLS: %v", request.TLS)
Printfln("--------------")
if request.URL.Path == "/favicon.ico" {
Printfln("Request for favicon.ico detected - returning 404")
Printfln("--------------\n")
writer.WriteHeader(http.StatusNotFound)
return
}
writeLen, err := io.WriteString(writer, sh.message)
if err != nil {
Printfln("ServeHTTP Error: %v", err)
return
}
Printfln("ServeHTTP Wrote %d bytes", writeLen)
Printfln("--------------\n")
}
func main() {
err := http.ListenAndServe("localhost:5000", &StringHandle{message: "Hello World!"})
if err != nil {
Printfln("ListenAndServe Error: %v", err)
return
}
}

View File

@@ -0,0 +1,7 @@
package main
import "fmt"
func Printfln(template string, values ...interface{}) {
fmt.Printf(template+"\n", values...)
}

View File

@@ -0,0 +1,31 @@
package main
type Product struct {
Name, Category string
Price float64
}
var Kayak = Product{
Name: "Kayak",
Category: "Watersports",
Price: 279,
}
var ProductList = []Product{
{"Kayak", "Watersports", 279},
{"LifeJacket", "Watersports", 49.95},
{"Soccer Ball", "Soccer", 19.50},
{"Corner Flags", "Soccer", 34.95},
{"Stadium", "Soccer", 79500},
{"Thinking Cap", "Chess", 16},
{"Unsteady Chair", "Chess", 75},
{"Bling-Bling King", "Chess", 1200},
}
func (p *Product) AddTax() float64 {
return p.Price * 1.2
}
func (p *Product) ApplyDiscount(amount float64) float64 {
return p.Price - amount
}