123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- package middleware
- import (
- "log"
- "net/http"
- "path"
- "runtime"
- "strings"
- "github.com/go-martini/martini"
- "github.com/gogits/gogs/modules/setting"
- )
- type StaticOptions struct {
-
- Prefix string
-
- SkipLogging bool
-
- IndexFile string
-
-
- Expires func() string
- }
- func prepareStaticOptions(options []StaticOptions) StaticOptions {
- var opt StaticOptions
- if len(options) > 0 {
- opt = options[0]
- }
-
- if len(opt.IndexFile) == 0 {
- opt.IndexFile = "index.html"
- }
-
- if opt.Prefix != "" {
-
- if opt.Prefix[0] != '/' {
- opt.Prefix = "/" + opt.Prefix
- }
-
- opt.Prefix = strings.TrimRight(opt.Prefix, "/")
- }
- return opt
- }
- func Static(directory string, staticOpt ...StaticOptions) martini.Handler {
- if runtime.GOOS == "windows" {
- if len(directory) < 2 || directory[1] != ':' {
- directory = path.Join(setting.StaticRootPath, directory)
- }
- } else if !path.IsAbs(directory) {
- directory = path.Join(setting.StaticRootPath, directory)
- }
- dir := http.Dir(directory)
- opt := prepareStaticOptions(staticOpt)
- return func(res http.ResponseWriter, req *http.Request, log *log.Logger) {
- if req.Method != "GET" && req.Method != "HEAD" {
- return
- }
- file := req.URL.Path
-
- if opt.Prefix != "" {
- if !strings.HasPrefix(file, opt.Prefix) {
- return
- }
- file = file[len(opt.Prefix):]
- if file != "" && file[0] != '/' {
- return
- }
- }
- f, err := dir.Open(file)
- if err != nil {
-
- return
- }
- defer f.Close()
- fi, err := f.Stat()
- if err != nil {
- return
- }
-
- if fi.IsDir() {
-
- if !strings.HasSuffix(req.URL.Path, "/") {
- http.Redirect(res, req, req.URL.Path+"/", http.StatusFound)
- return
- }
- file = path.Join(file, opt.IndexFile)
- f, err = dir.Open(file)
- if err != nil {
- return
- }
- defer f.Close()
- fi, err = f.Stat()
- if err != nil || fi.IsDir() {
- return
- }
- }
- if !opt.SkipLogging {
- log.Println("[Static] Serving " + file)
- }
-
- if opt.Expires != nil {
- res.Header().Set("Expires", opt.Expires())
- }
- http.ServeContent(res, req, file, fi.ModTime(), f)
- }
- }
|