yangjian102621 / geekai

AI 助手全套开源解决方案,自带运营管理后台,开箱即用。集成了 ChatGPT, Azure, ChatGLM,讯飞星火,文心一言等多个平台的大语言模型。支持 MJ AI 绘画,Stable Diffusion AI 绘画,微博热搜等插件工具。采用 Go + Vue3 + element-plus 实现。
https://chat.geekai.me
Apache License 2.0
3.65k stars 948 forks source link

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

Open lhy8888 opened 2 months ago

lhy8888 commented 2 months ago

⚠️ 确认 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")) }

优化点

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

}

优化点

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