Feat: 代码提交
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"computer-network/logger"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
rootDir string
|
||||
}
|
||||
|
||||
func NewHandler(rootDir string) *Handler {
|
||||
return &Handler{
|
||||
rootDir: rootDir,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) HandleConnection(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
|
||||
startTime := time.Now()
|
||||
clientIP := logger.GetClientIP(conn)
|
||||
|
||||
reader := bufio.NewReader(conn)
|
||||
req, err := ParseRequest(reader)
|
||||
if err != nil {
|
||||
response := BuildErrorResponse(StatusBadRequest, "", h.rootDir)
|
||||
SendResponse(conn, response)
|
||||
duration := time.Since(startTime)
|
||||
logger.Log(clientIP, "-", "-", "-", 400, duration)
|
||||
return
|
||||
}
|
||||
|
||||
var statusCode int
|
||||
var response *Response
|
||||
|
||||
if !req.IsGET() {
|
||||
statusCode = 501
|
||||
response = BuildErrorResponse(StatusNotImplemented, "/501.html", h.rootDir)
|
||||
} else {
|
||||
path := req.GetPath()
|
||||
data, contentType, err := ReadFile(h.rootDir, path)
|
||||
if err != nil {
|
||||
statusCode = 404
|
||||
response = BuildErrorResponse(StatusNotFound, "/404.html", h.rootDir)
|
||||
} else {
|
||||
statusCode = 200
|
||||
response = BuildOKResponse(data, contentType)
|
||||
}
|
||||
}
|
||||
|
||||
err = SendResponse(conn, response)
|
||||
if err != nil {
|
||||
fmt.Printf("Error sending response to %s: %v\n", clientIP, err)
|
||||
}
|
||||
|
||||
duration := time.Since(startTime)
|
||||
logger.Log(clientIP, req.Method, req.URL, req.HTTPVersion, statusCode, duration)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Request struct {
|
||||
Method string
|
||||
URL string
|
||||
HTTPVersion string
|
||||
Headers map[string]string
|
||||
Body string
|
||||
}
|
||||
|
||||
var (
|
||||
ErrMalformedRequest = errors.New("malformed HTTP request")
|
||||
ErrInvalidMethod = errors.New("invalid HTTP method")
|
||||
)
|
||||
|
||||
func ParseRequest(reader *bufio.Reader) (*Request, error) {
|
||||
requestLine, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return nil, ErrMalformedRequest
|
||||
}
|
||||
|
||||
requestLine = strings.TrimSpace(requestLine)
|
||||
if requestLine == "" {
|
||||
return nil, ErrMalformedRequest
|
||||
}
|
||||
|
||||
parts := strings.Fields(requestLine)
|
||||
if len(parts) != 3 {
|
||||
return nil, ErrMalformedRequest
|
||||
}
|
||||
|
||||
req := &Request{
|
||||
Method: parts[0],
|
||||
URL: parts[1],
|
||||
HTTPVersion: parts[2],
|
||||
Headers: make(map[string]string),
|
||||
}
|
||||
|
||||
for {
|
||||
headerLine, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
headerLine = strings.TrimSpace(headerLine)
|
||||
if headerLine == "" {
|
||||
break
|
||||
}
|
||||
|
||||
parts := strings.SplitN(headerLine, ":", 2)
|
||||
if len(parts) == 2 {
|
||||
key := strings.TrimSpace(parts[0])
|
||||
value := strings.TrimSpace(parts[1])
|
||||
req.Headers[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
return req, nil
|
||||
}
|
||||
|
||||
func (r *Request) IsValid() bool {
|
||||
switch r.Method {
|
||||
case "GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Request) IsGET() bool {
|
||||
return r.Method == "GET"
|
||||
}
|
||||
|
||||
func (r *Request) GetPath() string {
|
||||
if r.URL == "" || r.URL == "/" {
|
||||
return "/index.html"
|
||||
}
|
||||
|
||||
path := strings.SplitN(r.URL, "?", 2)[0]
|
||||
if path == "/" {
|
||||
return "/index.html"
|
||||
}
|
||||
|
||||
if strings.HasPrefix(path, "/") {
|
||||
return path
|
||||
}
|
||||
|
||||
return "/" + path
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
StatusOK = "200 OK"
|
||||
StatusNotFound = "404 Not Found"
|
||||
StatusNotImplemented = "501 Not Implemented"
|
||||
StatusInternalServerError = "500 Internal Server Error"
|
||||
StatusBadRequest = "400 Bad Request"
|
||||
)
|
||||
|
||||
type Response struct {
|
||||
StatusCode string
|
||||
Headers map[string]string
|
||||
Body string
|
||||
ContentType string
|
||||
}
|
||||
|
||||
func getContentType(filePath string) string {
|
||||
ext := strings.ToLower(filepath.Ext(filePath))
|
||||
switch ext {
|
||||
case ".html":
|
||||
return "text/html; charset=utf-8"
|
||||
case ".htm":
|
||||
return "text/html; charset=utf-8"
|
||||
case ".css":
|
||||
return "text/css; charset=utf-8"
|
||||
case ".js":
|
||||
return "application/javascript"
|
||||
case ".json":
|
||||
return "application/json"
|
||||
case ".jpg":
|
||||
return "image/jpeg"
|
||||
case ".jpeg":
|
||||
return "image/jpeg"
|
||||
case ".png":
|
||||
return "image/png"
|
||||
case ".gif":
|
||||
return "image/gif"
|
||||
case ".svg":
|
||||
return "image/svg+xml"
|
||||
case ".ico":
|
||||
return "image/x-icon"
|
||||
case ".txt":
|
||||
return "text/plain; charset=utf-8"
|
||||
case ".pdf":
|
||||
return "application/pdf"
|
||||
default:
|
||||
return "application/octet-stream"
|
||||
}
|
||||
}
|
||||
|
||||
func NewResponse(statusCode, body, contentType string) *Response {
|
||||
return &Response{
|
||||
StatusCode: statusCode,
|
||||
Body: body,
|
||||
ContentType: contentType,
|
||||
Headers: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Response) Build() []byte {
|
||||
var builder strings.Builder
|
||||
|
||||
builder.WriteString(fmt.Sprintf("HTTP/1.1 %s\r\n", r.StatusCode))
|
||||
builder.WriteString(fmt.Sprintf("Content-Type: %s\r\n", r.ContentType))
|
||||
builder.WriteString(fmt.Sprintf("Content-Length: %d\r\n", len(r.Body)))
|
||||
|
||||
for key, value := range r.Headers {
|
||||
builder.WriteString(fmt.Sprintf("%s: %s\r\n", key, value))
|
||||
}
|
||||
|
||||
builder.WriteString("\r\n")
|
||||
builder.WriteString(r.Body)
|
||||
|
||||
return []byte(builder.String())
|
||||
}
|
||||
|
||||
func ReadFile(rootDir, path string) ([]byte, string, error) {
|
||||
filePath := filepath.Join(rootDir, path)
|
||||
|
||||
filePath = filepath.Clean(filePath)
|
||||
|
||||
if strings.Contains(filePath, "..") {
|
||||
return nil, "", fmt.Errorf("invalid path")
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(filePath)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
contentType := getContentType(filePath)
|
||||
return data, contentType, nil
|
||||
}
|
||||
|
||||
func BuildOKResponse(body []byte, contentType string) *Response {
|
||||
return &Response{
|
||||
StatusCode: StatusOK,
|
||||
Body: string(body),
|
||||
ContentType: contentType,
|
||||
Headers: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
func BuildErrorResponse(statusCode, htmlPath, rootDir string) *Response {
|
||||
body := getErrorHTML(statusCode)
|
||||
|
||||
if htmlPath != "" && rootDir != "" {
|
||||
data, contentType, err := ReadFile(rootDir, htmlPath)
|
||||
if err == nil {
|
||||
return &Response{
|
||||
StatusCode: statusCode,
|
||||
Body: string(data),
|
||||
ContentType: contentType,
|
||||
Headers: make(map[string]string),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &Response{
|
||||
StatusCode: statusCode,
|
||||
Body: body,
|
||||
ContentType: "text/html; charset=utf-8",
|
||||
Headers: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
func getErrorHTML(statusCode string) string {
|
||||
statusNum := strings.Split(statusCode, " ")[0]
|
||||
var title, message string
|
||||
|
||||
switch statusCode {
|
||||
case StatusNotFound:
|
||||
title = "404 Not Found"
|
||||
message = "The requested resource could not be found."
|
||||
case StatusNotImplemented:
|
||||
title = "501 Not Implemented"
|
||||
message = "The requested method is not supported by this server. Only GET method is supported."
|
||||
case StatusInternalServerError:
|
||||
title = "500 Internal Server Error"
|
||||
message = "An internal server error occurred."
|
||||
case StatusBadRequest:
|
||||
title = "400 Bad Request"
|
||||
message = "The request could not be understood by the server."
|
||||
default:
|
||||
title = statusCode
|
||||
message = "An error occurred while processing your request."
|
||||
}
|
||||
|
||||
html := fmt.Sprintf(`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>%s</title>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
text-align: center;
|
||||
background-color: #f0f0f0;
|
||||
margin: 0;
|
||||
padding: 50px;
|
||||
}
|
||||
.error-container {
|
||||
background-color: white;
|
||||
border-radius: 10px;
|
||||
padding: 40px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
max-width: 500px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
h1 {
|
||||
color: #e74c3c;
|
||||
font-size: 72px;
|
||||
margin: 0 0 20px 0;
|
||||
}
|
||||
p {
|
||||
color: #333;
|
||||
font-size: 18px;
|
||||
margin: 0 0 20px 0;
|
||||
}
|
||||
.back-link {
|
||||
color: #3498db;
|
||||
text-decoration: none;
|
||||
}
|
||||
.back-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="error-container">
|
||||
<h1>%s</h1>
|
||||
<p>%s</p>
|
||||
<a href="/" class="back-link">返回首页</a>
|
||||
</div>
|
||||
</body>
|
||||
</html>`, title, statusNum, message)
|
||||
|
||||
return html
|
||||
}
|
||||
|
||||
func SendResponse(conn io.Writer, response *Response) error {
|
||||
data := response.Build()
|
||||
_, err := conn.Write(data)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"computer-network/admin"
|
||||
"computer-network/config"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
listener net.Listener
|
||||
config *config.Config
|
||||
handler *Handler
|
||||
mu sync.RWMutex
|
||||
running bool
|
||||
stopChan chan struct{}
|
||||
}
|
||||
|
||||
func NewServer(cfg *config.Config) *Server {
|
||||
return &Server{
|
||||
config: cfg,
|
||||
handler: NewHandler(cfg.GetRootDir()),
|
||||
stopChan: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Start() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.running {
|
||||
return fmt.Errorf("server is already running")
|
||||
}
|
||||
|
||||
var err error
|
||||
addr := fmt.Sprintf(":%d", s.config.GetPort())
|
||||
s.listener, err = net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to listen on port %d: %v", s.config.GetPort(), err)
|
||||
}
|
||||
|
||||
s.running = true
|
||||
fmt.Printf("Web Server started on port %d\n", s.config.GetPort())
|
||||
fmt.Printf("Root directory: %s\n", s.config.GetRootDir())
|
||||
fmt.Printf("Admin console: http://localhost:%d\n", s.config.GetAdminPort())
|
||||
|
||||
go s.acceptConnections()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) acceptConnections() {
|
||||
for {
|
||||
select {
|
||||
case <-s.stopChan:
|
||||
return
|
||||
default:
|
||||
conn, err := s.listener.Accept()
|
||||
if err != nil {
|
||||
select {
|
||||
case <-s.stopChan:
|
||||
return
|
||||
default:
|
||||
fmt.Printf("Error accepting connection: %v\n", err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
go s.handler.HandleConnection(conn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Stop() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if !s.running {
|
||||
return fmt.Errorf("server is not running")
|
||||
}
|
||||
|
||||
close(s.stopChan)
|
||||
s.running = false
|
||||
|
||||
if s.listener != nil {
|
||||
err := s.listener.Close()
|
||||
if err != nil {
|
||||
fmt.Printf("Error closing listener: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("Web Server stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) IsRunning() bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.running
|
||||
}
|
||||
|
||||
func (s *Server) GetPort() int {
|
||||
return s.config.GetPort()
|
||||
}
|
||||
|
||||
func (s *Server) UpdateConfig(cfg *config.Config) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.config = cfg
|
||||
s.handler = NewHandler(cfg.GetRootDir())
|
||||
}
|
||||
|
||||
type AdminServer struct {
|
||||
listener net.Listener
|
||||
config *config.Config
|
||||
adminHandler *admin.AdminHandler
|
||||
webServer *Server
|
||||
mu sync.RWMutex
|
||||
running bool
|
||||
stopChan chan struct{}
|
||||
}
|
||||
|
||||
func NewAdminServer(cfg *config.Config) *AdminServer {
|
||||
return &AdminServer{
|
||||
config: cfg,
|
||||
adminHandler: admin.NewAdminHandler(),
|
||||
stopChan: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func (as *AdminServer) SetWebServer(ws *Server) {
|
||||
as.mu.Lock()
|
||||
defer as.mu.Unlock()
|
||||
as.webServer = ws
|
||||
}
|
||||
|
||||
func (as *AdminServer) Start() error {
|
||||
as.mu.Lock()
|
||||
defer as.mu.Unlock()
|
||||
|
||||
if as.running {
|
||||
return fmt.Errorf("admin server is already running")
|
||||
}
|
||||
|
||||
var err error
|
||||
addr := fmt.Sprintf(":%d", as.config.GetAdminPort())
|
||||
as.listener, err = net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to listen on admin port %d: %v", as.config.GetAdminPort(), err)
|
||||
}
|
||||
|
||||
as.running = true
|
||||
fmt.Printf("Admin server started on port %d\n", as.config.GetAdminPort())
|
||||
|
||||
go as.acceptConnections()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (as *AdminServer) acceptConnections() {
|
||||
for {
|
||||
select {
|
||||
case <-as.stopChan:
|
||||
return
|
||||
default:
|
||||
conn, err := as.listener.Accept()
|
||||
if err != nil {
|
||||
select {
|
||||
case <-as.stopChan:
|
||||
return
|
||||
default:
|
||||
fmt.Printf("Error accepting admin connection: %v\n", err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
go as.handleAdminConnection(conn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (as *AdminServer) handleAdminConnection(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
|
||||
reader := bufio.NewReader(conn)
|
||||
req, err := ParseRequest(reader)
|
||||
if err != nil {
|
||||
response := BuildErrorResponse(StatusBadRequest, "", as.config.GetRootDir())
|
||||
SendResponse(conn, response)
|
||||
return
|
||||
}
|
||||
|
||||
if !req.IsGET() && req.Method != "DELETE" {
|
||||
response := BuildErrorResponse(StatusNotImplemented, "", as.config.GetRootDir())
|
||||
SendResponse(conn, response)
|
||||
return
|
||||
}
|
||||
|
||||
path := req.GetPath()
|
||||
var response *Response
|
||||
|
||||
switch path {
|
||||
case "/", "/index.html":
|
||||
httpResp := as.adminHandler.GetIndexPage()
|
||||
response = convertAdminResponse(httpResp)
|
||||
case "/api/logs":
|
||||
if req.IsGET() {
|
||||
httpResp := as.adminHandler.GetLogsJSON()
|
||||
response = convertAdminResponse(httpResp)
|
||||
} else if req.Method == "DELETE" {
|
||||
httpResp := as.adminHandler.ClearLogs()
|
||||
response = convertAdminResponse(httpResp)
|
||||
} else {
|
||||
response = BuildErrorResponse(StatusNotImplemented, "", as.config.GetRootDir())
|
||||
}
|
||||
case "/logs":
|
||||
httpResp := as.adminHandler.GetLogsPage()
|
||||
response = convertAdminResponse(httpResp)
|
||||
case "/api/status":
|
||||
webServerRunning := as.webServer != nil && as.webServer.IsRunning()
|
||||
webServerPort := 9000
|
||||
if as.webServer != nil {
|
||||
webServerPort = as.webServer.GetPort()
|
||||
}
|
||||
|
||||
statusBody := fmt.Sprintf(`{"running":%t,"port":%d}`, webServerRunning, webServerPort)
|
||||
response = NewResponse("200 OK", statusBody, "application/json")
|
||||
default:
|
||||
response = BuildErrorResponse(StatusNotFound, "", as.config.GetRootDir())
|
||||
}
|
||||
|
||||
SendResponse(conn, response)
|
||||
}
|
||||
|
||||
func (as *AdminServer) Stop() error {
|
||||
as.mu.Lock()
|
||||
defer as.mu.Unlock()
|
||||
|
||||
if !as.running {
|
||||
return fmt.Errorf("admin server is not running")
|
||||
}
|
||||
|
||||
close(as.stopChan)
|
||||
as.running = false
|
||||
|
||||
if as.listener != nil {
|
||||
err := as.listener.Close()
|
||||
if err != nil {
|
||||
fmt.Printf("Error closing admin listener: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("Admin server stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (as *AdminServer) IsRunning() bool {
|
||||
as.mu.RLock()
|
||||
defer as.mu.RUnlock()
|
||||
return as.running
|
||||
}
|
||||
|
||||
func convertAdminResponse(resp *admin.HTTPResponse) *Response {
|
||||
return NewResponse(resp.StatusCode, resp.Body, resp.ContentType)
|
||||
}
|
||||
Reference in New Issue
Block a user