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:])) } }
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) }
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) } }
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) }
// 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 }
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:])) } }
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:]) }
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") }) }
// 处理请求 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 }
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") } }
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 }
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) }
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) }
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) }
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) }
func main() { sqlrepositories.Connect(config.DatabaseConnectionString()) defer sqlrepositories.Cleanup() sessions.Enable() setupDependencies() http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("./assets")))) http.HandleFunc("/favicon.ico", func(req http.ResponseWriter, res *http.Request) { http.ServeFile(req, res, "./assets/images/favicon.png") }) http.HandleFunc("/robots.txt", func(req http.ResponseWriter, res *http.Request) { http.ServeFile(req, res, "./assets/robots.txt") }) setupRouting() http.Handle("/", r) port := portFromEnvOrDefault() log.Println("Starting server on port", port) log.Fatal(http.ListenAndServe(":"+port, nil)) }
func makeIndexHandler(root, cache string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var ( path = filepath.Join(root, r.URL.Path) baseName = filepath.Base(path) ) switch baseName { case "Packages", "Packages.gz", "Packages.stamps": var cachedPath = filepath.Join(cache, r.URL.Path) http.ServeFile(w, r, cachedPath) return } var fi os.FileInfo var err error if fi, err = os.Stat(path); err != nil { http.NotFound(w, r) return } if fi.IsDir() { renderIndex(w, r, root, cache) return } http.ServeFile(w, r, path) }) }
func main() { var err error // Setup the database if mongoSession, err = mgo.Dial("localhost"); err != nil { panic(err) } log.Println("Connected to mongodb") database = mongoSession.DB("mgo_examples_06") repo.Collection = database.C("todos") // Setup the web server and handlers // START OMIT route("/todos/{id}/complete", handleTodoComplete) route("/todos/{id}/complete", handleTodoComplete) route("/todos/{id}/uncomplete", handleTodoUncomplete) route("/todos/{id}", handleTodoDestroy).Methods("DELETE") route("/todos/{id}", handleTodoUpdate).Methods("PUT") route("/todos", handleTodoCreate).Methods("POST") route("/todos", handleTodos).Methods("GET") route("/timeago.js", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "./timeago.js") }) route("/", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "./index.html") }) // END OMIT http.Handle("/", router) log.Printf("Starting webserver http://localhost:8080") panic(http.ListenAndServe(":8080", nil)) }
func (p *Page) handleStatic() { StaticHtmlDir := p.Config.SiteRoot + p.Config.HtmlDirectory http.HandleFunc(StaticHtmlDir, func(w http.ResponseWriter, r *http.Request) { if p.UrlManage.Manage() { newUrl := p.UrlManage.ReWrite(w, r) if newUrl == "redirect" { p.site.base.mutex.Unlock() return } else { r.URL, _ = url.Parse(newUrl) } } staticPath := p.Config.AssetsDirectory + p.Config.HtmlDirectory + r.URL.Path[len(StaticHtmlDir):] if r.URL.RawQuery != "" { staticPath += "?" + r.URL.RawQuery } log.Debug("<Page.handleStatic> ", "staticPath:", staticPath) http.ServeFile(w, r, staticPath) }) http.HandleFunc(p.Document.Static, func(w http.ResponseWriter, r *http.Request) { staticPath := p.Config.AssetsDirectory + p.Config.StaticDirectory + r.URL.Path[len(p.Document.Static):] log.Debug("<Page.handleStatic> ", "staticPath:", staticPath) http.ServeFile(w, r, staticPath) }) }
func imagesHandler(w http.ResponseWriter, r *http.Request) { if r.URL.Path == imgDirpath { http.ServeFile(w, r, imgDirpath[1:]) } else if r.URL.Path == imgFilepath { http.ServeFile(w, r, imgFilepath[1:]) } }
func main() { rand.Seed(time.Now().UnixNano()) m := martini.Classic() // Handles uploading of images m.Post("/upload_image", func(response http.ResponseWriter, request *http.Request) { imgName := saveImage(request) response.Write([]byte(BASE_URL + "i/" + imgName)) }) m.Get("/i/:id", func(response http.ResponseWriter, request *http.Request, params martini.Params) { id := params["id"] fileName := "image/" + id + ".png" if _, err := os.Open(fileName); os.IsNotExist(err) { response.WriteHeader(404) http.ServeFile(response, request, "404.html") return } response.Header().Set("Content-Type", "image/png") http.ServeFile(response, request, fileName) }) m.NotFound(func(response http.ResponseWriter, request *http.Request) { http.ServeFile(response, request, "404.html") }) m.RunOnAddr(":80") }
func router(rw http.ResponseWriter, req *http.Request) { urlPath := req.URL.Path println(urlPath) logger.Debugln(urlPath) switch { case rootUrl == urlPath || strings.HasPrefix(urlPath, friendsUrl): friends := &controllers.Friends{} friends.Handler(rw, req) case strings.HasPrefix(urlPath, accountUrl): account := &controllers.Account{} account.Handler(rw, req) case strings.HasPrefix(urlPath, adminUrl): admin := &controllers.Admin{} admin.Handler(rw, req) case strings.HasPrefix(urlPath, wsUrl): ws := &controllers.Ws{} ws.Handler(rw, req) case strings.HasPrefix(urlPath, "public/"): //static files http.ServeFile(rw, req, urlPath) case urlPath == "/favicon.ico": //the request which browser send automatically http.ServeFile(rw, req, "public/images/favicon.ico") default: controllers.NotFoundHandler(rw, req) } }
func StaticHandler(w http.ResponseWriter, r *http.Request) { if r.URL.Path[:7] == "/static" { http.ServeFile(w, r, staticFile(r.URL.Path[7:])) } else { http.ServeFile(w, r, staticFile(r.URL.Path)) } }
func (d *directory) Serve(w http.ResponseWriter, r *http.Request, name string) error { if strings.Contains(name, "/") || name == "" { return errors.New("Invalid file name") } d.RLock() constraints, ok := d.files[name] d.RUnlock() if !ok { return errors.New("File not stored") } constraints.RLock() if constraints.expired() { return errors.New("File recently expired") } if constraints.Downloads > 0 { // have to modify the value constraints.RUnlock() constraints.Lock() switch constraints.Downloads { case 1: constraints.Downloads = -1 defer d.remove(name) case -1: constraints.Unlock() return errors.New("Download limit exceeded") default: constraints.Downloads-- } http.ServeFile(w, r, path.Join(d.name, name)) constraints.Unlock() return nil } http.ServeFile(w, r, path.Join(d.name, name)) constraints.RUnlock() return nil }
func (b *blog) ServeHTTP(w http.ResponseWriter, r *http.Request) { path := r.URL.Path // If it's a raw file, just serve it. fi, err := os.Stat(path[1:]) if err == nil && !fi.IsDir() { http.ServeFile(w, r, path[1:]) return } // If it's an image request, but not found on-disk, serve a default image. if strings.HasSuffix(path, ".jpg") { log.Printf(">>> " + path) http.ServeFile(w, r, "pub/img/blog.png") return } // Otherwise, assume it refers to an article. w.Header().Set("Content-Type", "text/html") _, exists := b.articleIndex[path] if !exists { newUrl, exists := reverseUrls[path] if exists { http.Redirect(w, r, newUrl, 301) } else { http.NotFound(w, r) } return } err = b.renderArticle(path, w) if err != nil { http.Error(w, err.Error(), 500) } }
func (handler *RequestHandler) HandleGet(w http.ResponseWriter, r *http.Request) { if len(r.URL.Path) <= 1 { id := <-handler.newIds fmt.Println("Redirecting") af := &AsmFile{id, make([]byte, 0)} err := af.Save() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/files/"+id, http.StatusFound) return } id := IdFromPath(r.URL.Path) fmt.Println("Id: " + id) af, err := LoadAsmFile(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } if strings.HasPrefix(r.URL.Path, "get") { // raw data wanted "get" fmt.Println("serving a get!") http.ServeFile(w, r, af.GetPath()) return } // pretty fmt.Println("serving file.html") http.ServeFile(w, r, "static/file.html") }
func handFile(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { http.ServeFile(w, r, "./index.html") } else { http.ServeFile(w, r, "."+r.URL.Path) } }
func main() { service := web.NewService( web.Name("go.micro.web.dashboard"), web.Version("latest"), ) service.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { log.Infof("%s '%s' for %s", r.Method, r.URL, r.RemoteAddr) http.ServeFile(w, r, "../dist/index.html") }) service.HandleFunc("/app.js", func(w http.ResponseWriter, r *http.Request) { log.Infof("%s '%s' for %s", r.Method, r.URL, r.RemoteAddr) http.ServeFile(w, r, "../dist/app.js") }) if err := service.Init(); err != nil { log.Fatal(err) } if err := service.Run(); err != nil { log.Fatal(err) } }
func handler(w http.ResponseWriter, r *http.Request) { params := string(r.URL.Path[1:]) if params == "" { http.ServeFile(w, r, "views/layouts/home.html") } else { arr := strings.Split(params, "/") m := make(map[string]controllers.ControllerInterface) m["users"] = controllers.NewUsersController() count := len(arr) if count > 0 { if arr[0] == "images" { buffer := bytes.NewBufferString("views/") buffer.WriteString(string(params)) http.ServeFile(w, r, buffer.String()) } else { m[arr[0]].Init(r, w) action := "index" if count > 1 { if arr[1] == "mobile" { m[arr[0]].MobileServe(action) } else { action = arr[1] m[arr[0]].Serve(action) } } else { m[arr[0]].Serve(action) } } } } }
/* 对所有的URL进行注册 */ func router(rw http.ResponseWriter, req *http.Request) { urlPath := req.URL.Path log.Println(urlPath) logger.Debugln(urlPath) switch { case rootUrl == urlPath || strings.HasPrefix(urlPath, articlesUrl): friends := controllers.NewArticles() friends.Handler(rw, req) case strings.HasPrefix(urlPath, adminUrl): admin := controllers.NewAdmin() admin.Handler(rw, req) case strings.HasPrefix(urlPath, wsUrl): ws := controllers.NewWS() ws.Handler(rw, req) case strings.HasPrefix(urlPath, contactUrl): contact := controllers.NewContact() contact.Handler(rw, req) case strings.HasPrefix(urlPath, aboutUrl): //about := controllers.NewAbout() //about.Handler(rw, req) case strings.HasPrefix(urlPath, "/bootstrap"): //static files http.ServeFile(rw, req, "libs"+urlPath) case strings.HasPrefix(urlPath, "public/"): //static files http.ServeFile(rw, req, urlPath) case urlPath == "/favicon.ico": //the request which browser send automatically http.ServeFile(rw, req, "public/images/favicon.ico") default: controllers.NotFoundHandler(rw, req) } }