mirror of
https://github.com/hanzoai/ai.git
synced 2026-11-21 11:09:56 +00:00
Replaces beego's ControllerRegister, filter chain and context with the native web package end to end. The controllers, filters and routes are retyped from beego.Context/beego.Controller to their web equivalents (web.Context mirrors beego's API, so the swap is mechanical), and the 307 explicit routes register on a shared routers.App (web.Router). The dead NSInclude namespace is dropped: without a generated commentsRouter it registered nothing. - controllers/base.go embeds web.Controller; the 4 streaming/util controllers, the 17 filters, util/cookie.go and object/record.go take *web.Context. - routers.InstallFilters inserts the 14 BeforeRouter + 2 AfterExec filters on App in the same order the standalone used; bootstrap and the route tests share it. - The session provider binds through App.UseSessions (its Store matches web.Store); Bootstrap publishes App as the request handler instead of beego.BeeApp.Handlers. - web gains the Controller compatibility surface the handlers use: EnableRender, GetFile, Context.SetCookie/Output.Cookie; RunMode defaults to prod (compact ServeJSON), matching the runtime default. The /swagger static (beego SetStaticPath) is dropped — the edge serves statics. Verified on SQLite (UseMemoryDB): /v1/cloud/* rewrites and dispatches, the /v1/iam/* alias is selective (in-set dispatches, out-of-set 404s), an unauthenticated gated /v1/cloud/get-providers is denied 401/403 before dispatch, and the real filter chain short-circuits on auth-reject in order. go build ./... and the web/routers/controllers/route tests are green; the beego module stays until the session and lifecycle cuts.
175 lines
5.1 KiB
Go
175 lines
5.1 KiB
Go
// Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.
|
|
// Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
package routers
|
|
|
|
import (
|
|
"compress/gzip"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"runtime"
|
|
"strings"
|
|
|
|
"github.com/hanzoai/ai/conf"
|
|
"github.com/hanzoai/ai/log"
|
|
"github.com/hanzoai/ai/util"
|
|
"github.com/hanzoai/ai/web"
|
|
)
|
|
|
|
var frontendBaseDir = conf.GetConfigString("frontendBaseDir")
|
|
|
|
func getWebBuildFolder() string {
|
|
path := "web/build"
|
|
if util.FileExist(filepath.Join(path, "index.html")) || frontendBaseDir == "" {
|
|
return path
|
|
}
|
|
|
|
if util.FileExist(filepath.Join(frontendBaseDir, "index.html")) {
|
|
return frontendBaseDir
|
|
}
|
|
|
|
path = filepath.Join(frontendBaseDir, "web/build")
|
|
return path
|
|
}
|
|
|
|
func StaticFilter(ctx *web.Context) {
|
|
urlPath := ctx.Request.URL.Path
|
|
if strings.HasPrefix(urlPath, "/v1/") || strings.HasPrefix(urlPath, "/v1/") {
|
|
return
|
|
}
|
|
|
|
landingFolder := conf.GetConfigString("landingFolder")
|
|
if landingFolder != "" {
|
|
if urlPath == "" || urlPath == "/" || urlPath == "/about" {
|
|
makeGzipResponse(ctx.ResponseWriter, ctx.Request, fmt.Sprintf("../%s/web/build/index.html", landingFolder))
|
|
return
|
|
}
|
|
|
|
landingPath := fmt.Sprintf("../%s/web/build%s", landingFolder, urlPath)
|
|
if util.FileExist(landingPath) {
|
|
makeGzipResponse(ctx.ResponseWriter, ctx.Request, landingPath)
|
|
return
|
|
}
|
|
}
|
|
|
|
if strings.HasPrefix(urlPath, "/storage") {
|
|
// Check if user is authenticated
|
|
user := GetSessionUser(ctx)
|
|
if user == nil {
|
|
denyForbidden(ctx, "auth:Unauthorized operation")
|
|
return
|
|
}
|
|
|
|
// Use the requesting origin if it is on the static allowlist;
|
|
// otherwise omit CORS headers entirely (the browser will block).
|
|
storageOrigin := ctx.Input.Header(headerOrigin)
|
|
if storageOrigin != "" && isStaticAllowedOrigin(storageOrigin) {
|
|
ctx.Output.Header(headerAllowOrigin, storageOrigin)
|
|
ctx.Output.Header(headerAllowMethods, "POST, GET, OPTIONS, DELETE")
|
|
ctx.Output.Header(headerAllowHeaders, "Content-Type, Authorization")
|
|
ctx.Output.Header(headerAllowCredentials, "true")
|
|
}
|
|
|
|
if runtime.GOOS == "windows" {
|
|
urlPath = strings.TrimPrefix(urlPath, "/storage/")
|
|
} else {
|
|
urlPath = strings.TrimPrefix(urlPath, "/storage")
|
|
}
|
|
|
|
urlPath = strings.Replace(urlPath, "|", ":", 1)
|
|
makeGzipResponse(ctx.ResponseWriter, ctx.Request, urlPath)
|
|
return
|
|
}
|
|
|
|
webBuildFolder := getWebBuildFolder()
|
|
path := webBuildFolder
|
|
if urlPath == "/" {
|
|
path += "/index.html"
|
|
} else {
|
|
path += urlPath
|
|
}
|
|
|
|
if strings.Contains(path, "/../") || !util.FileExist(path) {
|
|
path = webBuildFolder + "/index.html"
|
|
}
|
|
if util.FileExist(path) {
|
|
makeGzipResponse(ctx.ResponseWriter, ctx.Request, path)
|
|
} else {
|
|
err := util.AppendWebConfigCookie(ctx)
|
|
if err != nil {
|
|
log.Error("AppendWebConfigCookie: %v", err)
|
|
}
|
|
makeGzipResponse(ctx.ResponseWriter, ctx.Request, "web/build/index.html")
|
|
}
|
|
}
|
|
|
|
type gzipResponseWriter struct {
|
|
io.Writer
|
|
http.ResponseWriter
|
|
}
|
|
|
|
func (w gzipResponseWriter) Write(b []byte) (int, error) {
|
|
return w.Writer.Write(b)
|
|
}
|
|
|
|
func makeGzipResponse(w http.ResponseWriter, r *http.Request, path string) {
|
|
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
|
serveFileWithReplace(w, r, path)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Encoding", "gzip")
|
|
gz := gzip.NewWriter(w)
|
|
defer gz.Close()
|
|
gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w}
|
|
serveFileWithReplace(gzw, r, path)
|
|
}
|
|
|
|
func serveFileWithReplace(w http.ResponseWriter, r *http.Request, path string) {
|
|
if !regexp.MustCompile(`/static/js/main\.[a-f0-9]+\.js$`).MatchString(path) {
|
|
http.ServeFile(w, r, path)
|
|
return
|
|
}
|
|
|
|
f, err := os.Open(filepath.Clean(path))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
defer f.Close()
|
|
|
|
d, err := f.Stat()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
oldContent := util.ReadStringFromPath(path)
|
|
newContent := oldContent
|
|
|
|
serverUrl := conf.GetConfigString("IAM_URL")
|
|
clientId := conf.GetConfigString("IAM_CLIENT_ID")
|
|
appName := conf.GetConfigString("IAM_APP_NAME")
|
|
organizationName := conf.GetConfigString("IAM_ORG")
|
|
|
|
newContent = regexp.MustCompile(`serverUrl:"[^"]*"`).ReplaceAllString(newContent, fmt.Sprintf(`serverUrl:"%s"`, serverUrl))
|
|
newContent = regexp.MustCompile(`clientId:"[^"]*"`).ReplaceAllString(newContent, fmt.Sprintf(`clientId:"%s"`, clientId))
|
|
newContent = regexp.MustCompile(`appName:"[^"]*"`).ReplaceAllString(newContent, fmt.Sprintf(`appName:"%s"`, appName))
|
|
newContent = regexp.MustCompile(`organizationName:"[^"]*"`).ReplaceAllString(newContent, fmt.Sprintf(`organizationName:"%s"`, organizationName))
|
|
|
|
http.ServeContent(w, r, d.Name(), d.ModTime(), strings.NewReader(newContent))
|
|
}
|