Skip to content

Commit

Permalink
Properly handle serving renamed files
Browse files Browse the repository at this point in the history
This fixes a regression introduced by #3588 that broke the
generation of file servers when the served filename differs
from the request path filename, .e.g:

Files(/index.html, /www/data/another.html)
  • Loading branch information
raphael committed Sep 18, 2024
1 parent 4c72084 commit 3ec6491
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
15 changes: 14 additions & 1 deletion http/codegen/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,20 @@ func serverFile(genpkg string, svc *expr.HTTPServiceExpr) *codegen.File {
sections = append(sections, &codegen.SectionTemplate{Name: "server-handler-init", Source: readTemplate("server_handler_init"), FuncMap: funcs, Data: e})
}
if len(data.FileServers) > 0 {
sections = append(sections, &codegen.SectionTemplate{Name: "append-fs", Source: readTemplate("append_fs"), FuncMap: funcs, Data: data})
mappedFiles := make(map[string]string)
for _, fs := range data.FileServers {
if !fs.IsDir {
for _, p := range fs.RequestPaths {
baseFilePath := "/" + filepath.Base(fs.FilePath)
baseRequestPath := "/" + filepath.Base(p)
if baseFilePath == baseRequestPath {
continue
}
mappedFiles[baseRequestPath] = baseFilePath
}
}
}
sections = append(sections, &codegen.SectionTemplate{Name: "append-fs", Source: readTemplate("append_fs"), FuncMap: funcs, Data: mappedFiles})
}
for _, s := range data.FileServers {
sections = append(sections, &codegen.SectionTemplate{Name: "server-files", Source: readTemplate("file_server"), FuncMap: funcs, Data: s})
Expand Down
6 changes: 6 additions & 0 deletions http/codegen/templates/append_fs.go.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ type appendFS struct {
// Open opens the named file, appending the prefix to the file path before
// passing it to the underlying fs.FS.
func (s appendFS) Open(name string) (http.File, error) {
switch name {
{{- range $requested, $embedded := . }}
case {{ printf "%q" $requested }}:
name = {{ printf "%q" $embedded }}
{{- end }}
}
return s.fs.Open(path.Join(s.prefix, name))
}

Expand Down

0 comments on commit 3ec6491

Please sign in to comment.