Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

安全代码优化:日志中间件、防止XSS攻击、更改相应内容防止泄露内部错误细节、 #223

Open
1 task done
lhy8888 opened this issue Jul 12, 2024 · 0 comments
Labels
feature New feature or request

Comments

@lhy8888
Copy link

lhy8888 commented Jul 12, 2024

⚠️ 确认 issue 是否已存在 ⚠️

  • 我已经搜索了现有的问题,没有找到相关 issue。

功能描述 📝

1. main.go 文件优化

package main

import (
"log"
"net/http"
"os"

"github.com/gorilla/mux"
"github.com/joho/godotenv"

)

func main() {
// 加载环境变量
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file")
}

// 初始化路由
r := mux.NewRouter()

// 定义路由
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/api/v1/resource", ResourceHandler).Methods("GET")

// 添加中间件
r.Use(loggingMiddleware)

// 启动服务器
port := os.Getenv("PORT")
if port == "" {
    port = "8000"
}
log.Printf("Starting server on port %s...", port)
log.Fatal(http.ListenAndServe(":"+port, r))

}

// 日志中间件
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Request URI: %s, Method: %s", r.RequestURI, r.Method)
next.ServeHTTP(w, r)
})
}

func HomeHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Welcome to GeekAI"))
}

func ResourceHandler(w http.ResponseWriter, r *http.Request) {
// Dummy handler
w.Write([]byte("This is a resource"))
}

优化点

  • 增加了请求日志记录的中间件。
  • 为资源路由指定了 GET 方法,增加了安全性。

2. captcha_handler.go文件优化

package handler

import (
"net/http"
"github.com/dchest/captcha"
)

func CaptchaHandler(w http.ResponseWriter, r *http.Request) {
length := 6
captchaId := captcha.NewLen(length)

w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Write([]byte(captchaId))

}

优化点

  • 设置了适当的响应头以防止 XSS 攻击。

3. chat_model_handler.go 文件优化

package handler

import (
"encoding/json"
"net/http"
"github.com/your_project/model"
)

func ChatModelHandler(w http.ResponseWriter, r *http.Request) {
models, err := model.GetChatModels()
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(models)

}

优化点

  • 修改了错误信息,避免泄露内部错误细节。
  • 设置了响应头的内容类型。

示例 🌈

No response

动机 🔦

No response

@lhy8888 lhy8888 added the feature New feature or request label Jul 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant