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

add example for serve file #3193

Merged
merged 5 commits into from
Jan 2, 2024
Merged
Changes from 2 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
55 changes: 55 additions & 0 deletions example/httpserver/serve_file/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package main

import (
"net/http"
"os"
"strings"

"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)

var pathMap = map[string]string{
"/aaa/": "./",
}

// ServeFile serves the file to the response.
func ServeFile(r *ghttp.Request) {
truePath := r.URL.Path
// Replace the path prefix.
for k, v := range pathMap {
if strings.HasPrefix(truePath, k) {
truePath = strings.Replace(truePath, k, v, 1)
break
}
}

// Use file from dist.
file, err := os.Open(truePath)
if err != nil {
r.Response.WriteStatus(http.StatusForbidden)
return
}
defer file.Close()

// Clear the response buffer before file serving.
// It ignores all custom buffer content and uses the file content.
r.Response.ClearBuffer()

info, _ := file.Stat()
if info.IsDir() {
r.Response.WriteStatus(http.StatusForbidden)
} else {
r.Response.ServeContent(info.Name(), info.ModTime(), file)
}
hailaz marked this conversation as resolved.
Show resolved Hide resolved
}

func main() {
s := g.Server()
s.Use(ghttp.MiddlewareHandlerResponse)
s.BindHandler("/*", ServeFile)
s.SetPort(8080)
s.Run()
}

// http://127.0.0.1:8080/aaa/main.go
Loading