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

feature: supports deploying memos to a subfolder of the domain name. #3845

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
all:
make build_frontend
make build_backend

build_init:
cd ./web/ && pnpm i --frozen-lockfile && cd ../

build_proto:
cd ./proto/ && npx buf generate && cd ../

build_frontend:
cd ./web/ && pnpm run build && cd ../
sed -i "s|<script type=\"module\" crossorigin src=\"|&{{ .baseurl }}|g" ./web/dist/index.html
sed -i "s|<link rel=\"stylesheet\" crossorigin href=\"|&{{ .baseurl }}|g" ./web/dist/index.html
rm -rf ./server/router/frontend/dist/*
cp -R ./web/dist/* ./server/router/frontend/dist/

build_backend:
CGO_ENABLED=0 go build -o memos ./bin/memos/main.go

build_backend_armv7l:
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -o memos.armv7l ./bin/memos/main.go

build_backend_arm64:
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o memos.arm64 ./bin/memos/main.go

clean_frontend:
rm -rf ./web/dist/
11 changes: 10 additions & 1 deletion bin/memos/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ var (
DSN: viper.GetString("dsn"),
InstanceURL: viper.GetString("instance-url"),
Version: version.GetCurrentVersion(viper.GetString("mode")),
BaseURL: viper.GetString("base-url"),
}
if err := instanceProfile.Validate(); err != nil {
panic(err)
Expand Down Expand Up @@ -110,6 +111,7 @@ func init() {
rootCmd.PersistentFlags().String("driver", "sqlite", "database driver")
rootCmd.PersistentFlags().String("dsn", "", "database source name(aka. DSN)")
rootCmd.PersistentFlags().String("instance-url", "", "the url of your memos instance")
rootCmd.PersistentFlags().String("base-url", "", "the base url of your memos instance")
eaglexmw-gmail marked this conversation as resolved.
Show resolved Hide resolved

if err := viper.BindPFlag("mode", rootCmd.PersistentFlags().Lookup("mode")); err != nil {
panic(err)
Expand All @@ -132,12 +134,18 @@ func init() {
if err := viper.BindPFlag("instance-url", rootCmd.PersistentFlags().Lookup("instance-url")); err != nil {
panic(err)
}
if err := viper.BindPFlag("base-url", rootCmd.PersistentFlags().Lookup("base-url")); err != nil {
panic(err)
}

viper.SetEnvPrefix("memos")
viper.AutomaticEnv()
if err := viper.BindEnv("instance-url", "MEMOS_INSTANCE_URL"); err != nil {
panic(err)
}
if err := viper.BindEnv("base-url", "MEMOS_BASE_URL"); err != nil {
panic(err)
}
}

func printGreetings(profile *profile.Profile) {
Expand All @@ -150,8 +158,9 @@ addr: %s
port: %d
mode: %s
driver: %s
baseurl: %s
---
`, profile.Version, profile.Data, profile.DSN, profile.Addr, profile.Port, profile.Mode, profile.Driver)
`, profile.Version, profile.Data, profile.DSN, profile.Addr, profile.Port, profile.Mode, profile.Driver, profile.BaseURL)

print(greetingBanner)
if len(profile.Addr) == 0 {
Expand Down
2 changes: 2 additions & 0 deletions server/profile/profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ type Profile struct {
Version string
// InstanceURL is the url of your memos instance.
InstanceURL string
// BaseURL is the base url of your memos instance.
BaseURL string
}

func (p *Profile) IsDev() bool {
Expand Down
61 changes: 57 additions & 4 deletions server/router/frontend/frontend.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package frontend
import (
"context"
"embed"
"html/template"
"io"
"io/fs"
"net/http"

Expand All @@ -29,18 +31,69 @@ func NewFrontendService(profile *profile.Profile, store *store.Store) *FrontendS
}
}

func (*FrontendService) Serve(_ context.Context, e *echo.Echo) {
var baseURL = ""

func indexHander(c echo.Context) error {
// open index.html
file, err := embeddedFiles.Open("dist/index.html")
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
defer file.Close()
// render it.
b, err := io.ReadAll(file)
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}

c.Response().WriteHeader(http.StatusOK)
tmpl, err := template.New("index.html").Parse(string(b))
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
err = tmpl.Execute(c.Response().Writer, map[string]any{
"baseurl": baseURL,
})
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}

return nil
}

func (f *FrontendService) Serve(_ context.Context, e *echo.Echo) {
skipper := func(c echo.Context) bool {
return util.HasPrefixes(c.Path(), "/api", "/memos.api.v1")
pathTmp := c.Path()
return pathTmp == "/" || pathTmp == "/index.html" || util.HasPrefixes(pathTmp, "/api", "/memos.api.v1")
}

e.GET("/", indexHander)
e.GET("/index.html", indexHander)
// save baseUrl from profile.
baseURL = f.Profile.BaseURL

// Use echo static middleware to serve the built dist folder.
// Reference: https://github.com/labstack/echo/blob/master/middleware/static.go
e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
HTML5: true,
HTML5: false,
Filesystem: getFileSystem("dist"),
Skipper: skipper,
}))
}), func(skipper middleware.Skipper) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
// skip
if skipper(c) {
return next(c)
}
// skip assets
if util.HasPrefixes(c.Path(), "/assets") {
return next(c)
}
// otherwise (NotFound), serve index.html
return indexHander(c)
}
}
}(skipper))
// Use echo gzip middleware to compress the response.
// Reference: https://echo.labstack.com/docs/middleware/gzip
e.Group("assets").Use(middleware.GzipWithConfig(middleware.GzipConfig{
Expand Down
2 changes: 1 addition & 1 deletion store/migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ func (s *Store) normalizedMigrationHistoryList(ctx context.Context) error {
}

schemaVersionMap := map[string]string{}
filePaths, err := fs.Glob(migrationFS, fmt.Sprintf("%s/*/*.sql", s.getMigrationBasePath()))
filePaths, err := fs.Glob(migrationFS, fmt.Sprintf("%s*/*.sql", s.getMigrationBasePath()))
if err != nil {
return errors.Wrap(err, "failed to read migration files")
}
Expand Down
10 changes: 7 additions & 3 deletions web/index.html
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
<!doctype html>
<html lang="en">
<head>
<base href="{{ .baseurl }}">
<meta charset="UTF-8" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
<link rel="icon" type="image/webp" href="/logo.webp" />
<link rel="manifest" href="/site.webmanifest" />
<link rel="apple-touch-icon" sizes="180x180" href="{{ .baseurl }}/apple-touch-icon.png" />
<link rel="icon" type="image/webp" href="{{ .baseurl }}/logo.webp" />
<link rel="manifest" href="{{ .baseurl }}/site.webmanifest" />
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#f4f4f5" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#18181b" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<!-- memos.metadata.head -->
<title>Memos</title>
<script>
window.globalConfig = { BaseUrl: "{{ .baseurl }}"};
</script>
<script>
// Prevent flash of light mode.
const appearance = localStorage.getItem("appearance");
Expand Down
2 changes: 1 addition & 1 deletion web/src/components/MemoActionMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const MemoActionMenu = (props: Props) => {
};

const handleCopyLink = () => {
copy(`${window.location.origin}/m/${memo.uid}`);
copy(`${window.location.origin}` + (window as any).globalConfig.BaseUrl + `/m/${memo.uid}`);
toast.success(t("message.succeed-copy-link"));
};

Expand Down
2 changes: 1 addition & 1 deletion web/src/components/UserAvatar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const UserAvatar = (props: Props) => {
<div className={clsx(`w-8 h-8 overflow-clip rounded-xl`, className)}>
<img
className="w-full h-auto shadow min-w-full min-h-full object-cover dark:opacity-80"
src={avatarUrl || "/full-logo.webp"}
src={avatarUrl || (window as any).globalConfig.BaseUrl + "/full-logo.webp"}
decoding="async"
loading="lazy"
alt=""
Expand Down
2 changes: 1 addition & 1 deletion web/src/components/UserBanner.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const UserBanner = (props: Props) => {
const navigateTo = useNavigateTo();
const user = useCurrentUser();
const title = user ? user.nickname || user.username : "Memos";
const avatarUrl = user ? user.avatarUrl : "/full-logo.webp";
const avatarUrl = user ? user.avatarUrl : (window as any).globalConfig.BaseUrl + "/full-logo.webp";

const handleSignOut = async () => {
await authServiceClient.signOut({});
Expand Down
2 changes: 1 addition & 1 deletion web/src/grpcweb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { WorkspaceServiceDefinition } from "./types/proto/api/v1/workspace_servi
import { WorkspaceSettingServiceDefinition } from "./types/proto/api/v1/workspace_setting_service";

const channel = createChannel(
window.location.origin,
window.location.origin + (window as any).globalConfig.BaseUrl,
FetchTransport({
credentials: "include",
}),
Expand Down
2 changes: 1 addition & 1 deletion web/src/layouts/RootLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const RootLayout = () => {
useEffect(() => {
if (!currentUser) {
if (([Routes.ROOT, Routes.RESOURCES, Routes.INBOX, Routes.ARCHIVED, Routes.SETTING] as string[]).includes(location.pathname)) {
window.location.href = Routes.EXPLORE;
window.location.href = (window as any).globalConfig.BaseUrl + Routes.EXPLORE;
return;
}
}
Expand Down
2 changes: 1 addition & 1 deletion web/src/pages/UserProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const UserProfile = () => {
return;
}

copy(`${window.location.origin}/u/${encodeURIComponent(user.username)}`);
copy(`${window.location.origin}` + (window as any).globalConfig.BaseUrl + `/u/${encodeURIComponent(user.username)}`);
toast.success(t("message.copied"));
};

Expand Down
Loading