Rendering CSS in a Go Web Application

前端 未结 1 1556
离开以前
离开以前 2020-12-13 19:35

I wrote a very basic web application, following this tutorial. I want to add css rules in an external stylesheet, but it\'s not working - when the HTML templates are rendere

1条回答
  •  情深已故
    2020-12-13 19:49

    Add a handler to handle serving static files from a specified directory.

    eg. create {server.go directory}/resources/ and use

    http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources")))) 
    

    along with /resources/somethingsomething.css

    The reason for using StripPrefix is that you can change the served directory as you please, but keep the reference in HTML the same.

    eg. to serve from /home/www/

    http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("/home/www/"))))
    

    Note that this will leave the resources directory listing open. If you want to prevent that, there is a good snippet on the go snippet blog:

    http://gosnip.posterous.com/disable-directory-listing-with-httpfileserver

    Edit: Posterous is now gone, so I just pulled the code off of the golang mailing list and will post it here.

    type justFilesFilesystem struct {
        fs http.FileSystem
    }
    
    func (fs justFilesFilesystem) Open(name string) (http.File, error) {
        f, err := fs.fs.Open(name)
        if err != nil {
            return nil, err
        }
        return neuteredReaddirFile{f}, nil
    }
    
    type neuteredReaddirFile struct {
        http.File
    }
    
    func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {
        return nil, nil
    }
    

    Original post discussing it: https://groups.google.com/forum/#!topic/golang-nuts/bStLPdIVM6w

    And use it like this in place of the line above:

     fs := justFilesFilesystem{http.Dir("resources/")}
     http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(fs)))
    

    0 讨论(0)
提交回复
热议问题