本文整理汇总了Golang中net/http.ServeFile函数的典型用法代码示例。如果您正苦于以下问题:Golang ServeFile函数的具体用法?Golang ServeFile怎么用?Golang ServeFile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ServeFile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: index
func index(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.ServeFile(w, r, filepath.Join(config.Path.Client, "index.html"))
} else {
http.ServeFile(w, r, filepath.Join(config.Path.Client, r.URL.Path[1:]))
}
}
示例2: HttpWriteFile
func (cache *FileCache) HttpWriteFile(w http.ResponseWriter, r *http.Request) {
path, err := url.QueryUnescape(r.URL.String())
if err != nil {
http.ServeFile(w, r, r.URL.Path)
} else if len(path) > 1 {
path = path[1:len(path)]
} else {
http.ServeFile(w, r, ".")
return
}
if cache.InCache(path) {
itm := cache.items[path]
ctype := http.DetectContentType(itm.Access())
mtype := mime.TypeByExtension(filepath.Ext(path))
if mtype != "" && mtype != ctype {
ctype = mtype
}
w.Header().Set("content-length", fmt.Sprintf("%d", itm.Size))
w.Header().Set("content-disposition",
fmt.Sprintf("filename=%s", filepath.Base(path)))
w.Header().Set("content-type", ctype)
w.Write(itm.Access())
return
}
go cache.Cache(path)
http.ServeFile(w, r, path)
}
示例3: main
func main() {
if err := goa.Init(goa.Config{
LoginPage: "/login.html",
HashKey: []byte(hashKey),
EncryptionKey: []byte(cryptoKey),
CookieName: "session",
PQConfig: "user=test_user password=test_pass dbname=goa",
}); err != nil {
log.Println(err)
return
}
// public (no-auth-required) files
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
// protected files, only for logged-in users
http.Handle("/protected/", goa.NewHandler(http.StripPrefix("/protected/", http.FileServer(http.Dir("protected")))))
// home handler
http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
http.ServeFile(rw, req, "index.html")
})
http.HandleFunc("/login.html", func(rw http.ResponseWriter, req *http.Request) {
http.ServeFile(rw, req, "login.html")
})
http.HandleFunc("/register.html", func(rw http.ResponseWriter, req *http.Request) {
http.ServeFile(rw, req, "register.html")
})
if err := http.ListenAndServeTLS(":8080", "keys/cert.pem", "keys/key.pem", nil); err != nil {
log.Println(err)
}
}
示例4: init
func init() {
s := api.GetServeMux()
// Register static polymer assets
asset_repo := api.Dir{
http.Dir("html/bower_components/"),
http.Dir("html/custom_components/"),
}
s.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(asset_repo)))
// Register static html resources
s.Handle("/css", http.FileServer(http.Dir("html/www/css/")))
s.Handle("/js", http.FileServer(http.Dir("html/www/js/")))
s.Handle("/", http.FileServer(http.Dir("html/www/")))
// API for cluster
s.HandleFunc("/cluster/list", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "html/www/cluster-list.json")
})
// API for service
s.HandleFunc("/service/list", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "html/www/service-list.json")
})
s.HandleFunc("/info", dsc.Info)
}
示例5: Execute
// Execute write response
func (e *ErrorResult) Execute(ctx *HttpContext) error {
if ctx.Server.Config.ErrorPageEnable {
accetps := ctx.Accept()
if strings.Contains(accetps, "text/html") {
if f := ctx.Server.MapPath("public/error.html"); isFileExists(f) {
http.ServeFile(ctx.Resonse, ctx.Request, f)
return nil
}
if ctx.Server.Config.ViewEnable {
if f := ctx.Server.MapPath("views/error.html"); isFileExists(f) {
ctx.ViewData["ctx"] = ctx
ctx.ViewData["error"] = e
return executeViewFile("error.html", ctx)
}
}
}
if strings.Contains(accetps, "text/plain") {
if f := ctx.Server.MapPath("public/error.txt"); isFileExists(f) {
http.ServeFile(ctx.Resonse, ctx.Request, f)
return nil
}
}
}
http.Error(ctx.Resonse, e.Message, http.StatusInternalServerError)
return nil
}
示例6: root
func (ms MusicServer) root(response http.ResponseWriter, request *http.Request) {
if url := request.RequestURI; url == "/" {
http.ServeFile(response, request, filepath.Join(ms.webfolder, "music.html"))
} else {
http.ServeFile(response, request, filepath.Join(ms.webfolder, url[1:]))
}
}
示例7: assetsFlexHandler
func (n *node) assetsFlexHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
if r.URL.Path[1:len(n.u.conf.AdminPathPrefix)+1] == n.u.conf.AdminPathPrefix {
http.ServeFile(w, r, "front/assets/"+r.URL.Path[1+len(n.u.conf.AdminPathPrefix):])
return
}
http.ServeFile(w, r, "front/assets/"+r.URL.Path[1:])
}
示例8: setupHTTPHandlers
func setupHTTPHandlers(games map[string]gp.Game) {
for _, game := range games {
serveController(game)
func(name string) {
http.HandleFunc("/img/"+name+".png", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filepath.Join(gp.GamesDir, name, "screenshot.png"))
})
}(strings.ToLower(game.Name))
}
http.HandleFunc("/ws", hub.ServeWs)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
redirectToController(w, r)
})
http.HandleFunc("/hub.js", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "hub.js")
})
http.HandleFunc("/jquery.js", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "jquery.js")
})
http.HandleFunc("/phaser.js", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "phaser.js")
})
}
示例9: handler
// 处理请求
func handler(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Server", "GWS")
var url = req.FormValue("url")
var width = req.FormValue("width")
var height = req.FormValue("height")
var delay = req.FormValue("delay")
var flush = req.FormValue("flush")
var validURL = regexp.MustCompile(`^http(s)?://.*$`)
if ok := validURL.MatchString(url); !ok {
fmt.Fprintf(rw, "<html><body>请输入需要截图的网址:<form><input name=url><input type=submit value=shot></form></body></html>")
} else {
pic := GetPicPath(url)
// 如果有range,表明是分段请求,直接处理
if v := req.Header.Get("Range"); v != "" {
http.ServeFile(rw, req, pic)
}
// 判断图片是否重新生成
if i, _ := strconv.Atoi(flush); i == 1 || IsExist(pic) == false {
pic, err := exec(url, pic, width, height, delay)
if err != nil {
if conf.debug == true {
log.Println("Snapshot Error:", url, err.Error())
}
fmt.Fprintf(rw, "shot error: %s", err.Error())
return
}
if conf.debug == true {
log.Println("Snapshot Successful:", url, pic)
}
}
http.ServeFile(rw, req, pic)
}
return
}
示例10: handleHack
func handleHack(w http.ResponseWriter, r *http.Request) {
usageSemaphore <- struct{}{}
defer func() {
<-usageSemaphore
}()
if r.ParseForm() != nil {
http.ServeFile(w, r, "assets/invalid_form.html")
return
}
pin := strings.TrimSpace(r.PostFormValue("pin"))
nickname := r.PostFormValue("nickname")
gamePin, _ := strconv.Atoi(pin)
hackType := r.PostFormValue("hack")
var res bool
if hackType == "Flood" {
res = floodHack(gamePin, nickname)
} else if hackType == "HTML Hack" {
res = htmlHack(gamePin, nickname)
} else {
http.ServeFile(w, r, "assets/invalid_form.html")
return
}
if res {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
} else {
http.ServeFile(w, r, "assets/unknown_game.html")
}
}
示例11: tryServingStatic
func (s *Server) tryServingStatic(reqpath string, req *http.Request, w http.ResponseWriter) bool {
name := reqpath
if s.Config.StaticPerfix != "" {
name = strings.TrimPrefix(reqpath, s.Config.StaticPerfix)
if len(name) == len(reqpath) {
return false
}
}
//try to serve a static file
if s.Config.StaticDir != "" {
staticFile := path.Join(s.Config.StaticDir, name)
//fmt.Println("staticfile:", staticFile)
if fileExists(staticFile) {
http.ServeFile(w, req, staticFile)
return true
}
} else {
for _, staticDir := range defaultStaticDirs {
staticFile := path.Join(staticDir, name)
//fmt.Println("staticfile:", staticFile)
if fileExists(staticFile) {
http.ServeFile(w, req, staticFile)
return true
}
}
}
return false
}
示例12: getStream
func (l *Library) getStream(w http.ResponseWriter, r *http.Request) {
l.mutex.RLock()
defer l.mutex.RUnlock()
base := path.Base(r.URL.Path)
ext := path.Ext(base)
s, ok := l.SongsByID[strings.TrimSuffix(base, ext)]
if !ok {
httpError(w, http.StatusNotFound)
return
}
af, ok := afmts[ext]
if !ok {
httpError(w, http.StatusNotFound)
return
}
w.Header().Set("Content-Type", af.Mime)
absPath := l.absPath(s.Path)
if s.Fmt == af.Fmt && s.Codec == af.Codec {
http.ServeFile(w, r, absPath)
return
}
streamPath := streamPath(s, ext)
if l.enc.Encode(s, streamPath, absPath, af) != nil {
httpError(w, http.StatusInternalServerError)
return
}
http.ServeFile(w, r, streamPath)
}
示例13: router
func router(w http.ResponseWriter, r *http.Request) {
log.Printf("serving %s", r.RequestURI)
path := r.URL.Path
log.Print("path = ", path)
if "/" == path {
// log.Print("list dir")
http.ServeFile(w, r, root)
return
}
if path[0] == '/' {
local, err := url.QueryUnescape(root + "/" + path[1:])
if err != nil {
http.Error(w, path[1:], http.StatusNotFound)
return
}
log.Printf("serve file: %s", local)
http.ServeFile(w, r, local)
return
}
http.Error(w, fmt.Sprintf("Page not found: %s", r.RequestURI), http.StatusNotFound)
}
示例14: main
func main() {
messagesChan := make(chan Message)
addChan := make(chan Client)
removeChan := make(chan Client)
go handleMessages(messagesChan, addChan, removeChan)
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
http.ServeFile(writer, request, "static/index.html")
})
http.HandleFunc("/static/", func(writer http.ResponseWriter, request *http.Request) {
http.ServeFile(writer, request, request.URL.Path[1:])
})
http.HandleFunc("/stream", func(writer http.ResponseWriter, request *http.Request) {
handleStream(messagesChan, addChan, removeChan, writer, request)
})
http.HandleFunc("/messages", func(writer http.ResponseWriter, request *http.Request) {
handleMessage(messagesChan, writer, request)
})
port := "8080"
if portFromEnv := os.Getenv("PORT"); portFromEnv != "" {
port = portFromEnv
}
log.Print("Starting server on port ", port)
http.ListenAndServe(":"+port, nil)
}
示例15: init
func init() {
var err error
var d *Was
// Load the templates
templates = template.Must(template.ParseFiles("html/search.html"))
if templates == nil {
log.Println("Unable to parse templates")
panic(errors.New("Exiting application"))
}
// Load the db
if d, err = LoadDB(); err != nil {
log.Println("Unable to load db", err)
panic(errors.New("Exiting application"))
}
db = *d
// Set up default page data
p = &SearchPage{}
p.BackgroundImage = "images/default.jpg"
// Routing
http.HandleFunc("/", index)
http.HandleFunc("/search", search)
// Static files server
http.HandleFunc("/images/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
})
http.HandleFunc("/css/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
})
//log.Println("Running wahei at port 9000")
//http.ListenAndServe(":9000", nil)
}