func main() { statikFS, err := fs.New() file, err := statikFS.Open("/templates/template.html") if err != nil { log.Fatalf("Templates could not be read: %s", err) } tmpl, err := ioutil.ReadAll(file) if err != nil { log.Fatal("Tempalte could not be read from: %s", err) } indextemplate, err := template.New("template.html").Parse(string(tmpl)) if err != nil { log.Fatalf("Tempalte could ne be initiliazed: %s", err) } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { indextemplate.Execute(w, nil) }) http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(wrappedfs.New(statikFS, "/public/")))) log.Fatal(http.ListenAndServe("localhost:8080", nil)) }
// getBoneRouter returns mux for admin interface func getBoneRouter(d DBClient) *bone.Mux { mux := bone.New() mux.Get("/records", http.HandlerFunc(d.AllRecordsHandler)) mux.Delete("/records", http.HandlerFunc(d.DeleteAllRecordsHandler)) mux.Post("/records", http.HandlerFunc(d.ImportRecordsHandler)) mux.Get("/count", http.HandlerFunc(d.RecordsCount)) mux.Get("/stats", http.HandlerFunc(d.StatsHandler)) mux.Get("/statsws", http.HandlerFunc(d.StatsWSHandler)) mux.Get("/state", http.HandlerFunc(d.CurrentStateHandler)) mux.Post("/state", http.HandlerFunc(d.StateHandler)) if d.Cfg.Development { // since hoverfly is not started from cmd/hoverfly/hoverfly // we have to target to that directory log.Warn("Hoverfly is serving files from /static/dist instead of statik binary!") mux.Handle("/*", http.FileServer(http.Dir("../../static/dist"))) } else { // preparing static assets for embedded admin statikFS, err := fs.New() if err != nil { log.WithFields(log.Fields{ "Error": err.Error(), }).Error("Failed to load statikFS, admin UI might not work :(") } mux.Handle("/*", http.FileServer(statikFS)) } return mux }
func (self *Manager) ServeHTTP(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET": if "/status" == r.URL.Path { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(self.Stats()) return } if nil == self.fs { statikFS, err := fs.New() if err != nil { w.WriteHeader(http.StatusInternalServerError) io.WriteString(w, err.Error()) return } //http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(statikFS))) self.fs = http.StripPrefix("/", http.FileServer(statikFS)) } self.fs.ServeHTTP(w, r) return case "POST": ss := strings.Split(strings.Trim(r.URL.Path, "/"), "/") if 2 == len(ss) { switch strings.ToLower(ss[1]) { case "restart": if e := self.retry(ss[0]); nil != e { w.WriteHeader(http.StatusInternalServerError) io.WriteString(w, e.Error()) } else { w.WriteHeader(http.StatusOK) io.WriteString(w, "OK") } return case "start": if e := self.start(ss[0]); nil != e { w.WriteHeader(http.StatusInternalServerError) io.WriteString(w, e.Error()) } else { w.WriteHeader(http.StatusOK) io.WriteString(w, "OK") } return case "stop": if e := self.stop(ss[0]); nil != e { w.WriteHeader(http.StatusInternalServerError) io.WriteString(w, e.Error()) } else { w.WriteHeader(http.StatusOK) io.WriteString(w, "OK") } return } } } http.NotFound(w, r) }
// Before buildling, run go generate. // Then, run the main program and visit http://localhost:8080/public/hello.txt func main() { statikFS, err := fs.New() if err != nil { log.Fatalf(err.Error()) } http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(statikFS))) http.ListenAndServe(":8080", nil) }
// getBoneRouter returns mux for admin interface func (this *AdminApi) getBoneRouter(d *Hoverfly) *bone.Mux { mux := bone.New() authHandler := &handlers.AuthHandler{ d.Authentication, d.Cfg.SecretKey, d.Cfg.JWTExpirationDelta, d.Cfg.AuthEnabled, } authHandler.RegisterRoutes(mux) handlers := GetAllHandlers(d) for _, handler := range handlers { handler.RegisterRoutes(mux, authHandler) } if d.Cfg.Development { // since hoverfly is not started from cmd/hoverfly/hoverfly // we have to target to that directory log.Warn("Hoverfly is serving files from /static/admin/dist instead of statik binary!") mux.Handle("/js/*", http.StripPrefix("/js/", http.FileServer(http.Dir("../../static/admin/dist/js")))) mux.HandleFunc("/*", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "../../static/admin/dist/index.html") }) } else { // preparing static assets for embedded admin statikFS, err := fs.New() if err != nil { log.WithFields(log.Fields{ "Error": err.Error(), }).Error("Failed to load statikFS, admin UI might not work :(") } mux.Handle("/js/*", http.FileServer(statikFS)) mux.Handle("/app.32dc9945fd902da8ed2cccdc8703129f.css", http.FileServer(statikFS)) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { file, err := statikFS.Open("/index.html") if err != nil { w.WriteHeader(500) log.WithFields(log.Fields{ "error": err, }).Error("got error while opening index file") return } io.Copy(w, file) w.WriteHeader(200) }) } return mux }
// serve serves the handler from the listener. func (s *Service) serve() { // Instantiate file system from embedded admin. statikFS, err := fs.New() if err != nil { panic(err) } // Run file system handler on listener. err = http.Serve(s.listener, http.FileServer(statikFS)) if err != nil && !strings.Contains(err.Error(), "closed") { s.err <- fmt.Errorf("listener error: addr=%s, err=%s", s.Addr(), err) } }
func ServStatic(router *mux.Router) { statikFS, se := fs.New() if se != nil { log.Fatalf(se.Error()) } // statikFS := http.Dir(filepath.Join(Settings.Root, "htdocs")) ss := http.FileServer(statikFS) router.PathPrefix("/static/").Handler(ss).Methods("GET", "HEAD") router.Path("/favicon.ico").Handler(ss).Methods("GET", "HEAD") router.Path("/robots.txt").Handler(ss).Methods("GET", "HEAD") }
// Before buildling, run `statik -src=./data` // to generate the statik package. // Note! when updating contents of ./data delete the ./statik dir so it can be recreated func main() { statikFS, err := fs.New() if err != nil { log.Fatalf(err.Error()) } // Serve the data from the root http.Handle("/", http.FileServer(statikFS)) // Serve the data from the ./assets/ here as an example http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(statikFS))) if nope := 1; nope != 1 { openURL("http://localhost:8080/") } fmt.Println("listening on TCP:8080") http.ListenAndServe("0.0.0.0:8080", nil) }
func (self *HttpServer) ListenAndServe() { if self.port == "" { return } self.closed = false var err error self.listener, err = net.Listen("tcp", self.port) if err != nil { panic(err) } statikFS, _ := fs.New() err = http.Serve(self.listener, http.FileServer(statikFS)) if !strings.Contains(err.Error(), "closed") { panic(err) } }
func main() { router := web.MainRouter() statikFS, se := fs.New() if se != nil { log.Fatalf(se.Error()) } ss := http.FileServer(statikFS) router.Path("/favicon.ico").Handler(ss).Methods("GET", "HEAD") router.Path("/robots.txt").Handler(ss).Methods("GET", "HEAD") fmt.Printf("Start service %s at addr %s\nRoot: %s\n", Settings.Version, Settings.HttpListen, Settings.Root) err := http.ListenAndServe(Settings.HttpListen, router) // Start the server! if err != nil { log.Fatal("ListenAndServe: ", err) } }
// Initialize the package func Init() { /* fmt.Println(packages) // Create the header template header = template.New("header") header, _ = header.Parse(templateSource(pages)) */ // Static files statikFS, err := fs.New() if err != nil { log.Fatalf(err.Error()) } // Create additional HTTP handlers http.HandleFunc("/ws", webSocketHandler.ServeWS) http.Handle("/css/", http.FileServer(statikFS)) http.Handle("/js/", http.FileServer(statikFS)) }
// serve serves the handler from the listener. func (s *Service) serve() { addVersionHeaderThenServe := func(h http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Add("X-InfluxDB-Version", s.version) h.ServeHTTP(w, r) } } // Instantiate file system from embedded admin. statikFS, err := fs.New() if err != nil { panic(err) } // Run file system handler on listener. err = http.Serve(s.listener, addVersionHeaderThenServe(http.FileServer(statikFS))) if err != nil && !strings.Contains(err.Error(), "closed") { s.err <- fmt.Errorf("listener error: addr=%s, err=%s", s.Addr(), err) } }
func main() { accountSid := fatalIfEmpty("TWILIO_ACCOUNT_SID") authToken := fatalIfEmpty("TWILIO_AUTH_TOKEN") phoneNumber := fatalIfEmpty("PHONE_NUMBER") baseUrl := fatalIfEmpty("BASE_URL") port := fatalIfEmpty("PORT") doorman := doorman.NewDoorman(accountSid, authToken, phoneNumber, timeLayout, baseUrl) statikFS, err := fs.New() if err != nil { log.Fatalf(err.Error()) } mux := http.NewServeMux() mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(statikFS))) mux.HandleFunc("/open", doorman.Open) mux.HandleFunc("/door", doorman.Door) mux.HandleFunc("/callme", doorman.CallMe) mux.HandleFunc("/sms", doorman.Sms) mux.HandleFunc("/dummy", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") fmt.Fprintf(w, "nothing") }) fmt.Println("Starting scheduler") ticker := time.NewTicker(1 * time.Minute) go func() { for { select { case <-ticker.C: resp, _ := http.Get(fmt.Sprintf("%s/dummy", baseUrl)) defer resp.Body.Close() } } }() log.Printf("Listening on %s...", port) log.Fatal(http.ListenAndServe(":"+port, mux)) }
// getBoneRouter returns mux for admin interface func getBoneRouter(d DBClient) *bone.Mux { mux := bone.New() // preparing static assets for embedded admin statikFS, err := fs.New() if err != nil { log.WithFields(log.Fields{ "Error": err.Error(), }).Error("Failed to load statikFS, admin UI might not work :(") } mux.Get("/records", http.HandlerFunc(d.AllRecordsHandler)) mux.Delete("/records", http.HandlerFunc(d.DeleteAllRecordsHandler)) mux.Post("/records", http.HandlerFunc(d.ImportRecordsHandler)) mux.Get("/count", http.HandlerFunc(d.RecordsCount)) mux.Get("/state", http.HandlerFunc(d.CurrentStateHandler)) mux.Post("/state", http.HandlerFunc(d.StateHandler)) mux.Handle("/*", http.FileServer(statikFS)) return mux }
func (self *webFront) ServeHTTP(w http.ResponseWriter, r *http.Request) { backend := self.dbBackend fmt.Println(r.Method, r.URL.Path) switch r.Method { case "GET": switch r.URL.Path { case "/all": allHandler(w, r, backend) return case "/failed": failedHandler(w, r, backend) return case "/queued": queuedHandler(w, r, backend) return case "/active": activeHandler(w, r, backend) return case "/counts": countsHandler(w, r, backend) return case "/settings_file", "/delayed_jobs/settings_file", "/delayed_job/settings_file": readSettingsFileHandler(w, r, backend) return default: if nil == self.fs { statikFS, err := fs.New() if err != nil { w.WriteHeader(http.StatusInternalServerError) io.WriteString(w, err.Error()) return } //http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(statikFS))) self.fs = http.StripPrefix("/", http.FileServer(statikFS)) } self.fs.ServeHTTP(w, r) return } case "PUT": switch r.URL.Path { case "/test", "/delayed_jobs/test", "/delayed_job/test": testJobHandler(w, r, backend) return case "/push": pushHandler(w, r, backend) return case "/pushAll": pushAllHandler(w, r, backend) return case "/settings_file", "/delayed_jobs/settings_file", "/delayed_job/settings_file": settingsFileHandler(w, r, backend) return } case "POST": switch r.URL.Path { case "/test", "/delayed_jobs/test": testJobHandler(w, r, backend) return case "/push": pushHandler(w, r, backend) return case "/pushAll": pushAllHandler(w, r, backend) return case "/settings_file", "/delayed_jobs/settings_file", "/delayed_job/settings_file": settingsFileHandler(w, r, backend) return } for _, retry := range retry_list { if retry.MatchString(r.URL.Path) { ss := strings.Split(r.URL.Path, "/") id, e := strconv.ParseInt(ss[len(ss)-2], 10, 0) if nil != e { w.WriteHeader(http.StatusBadRequest) io.WriteString(w, e.Error()) return } e = backend.retry(id) if nil == e { w.WriteHeader(http.StatusOK) io.WriteString(w, "The job has been queued for a re-run") } else { w.WriteHeader(http.StatusInternalServerError) io.WriteString(w, e.Error()) } return } } for _, job_id := range delete_by_id_list { if job_id.MatchString(r.URL.Path) { ss := strings.Split(r.URL.Path, "/") id, e := strconv.ParseInt(ss[len(ss)-2], 10, 0) if nil != e { w.WriteHeader(http.StatusBadRequest) io.WriteString(w, e.Error()) return } e = backend.destroy(id) if nil == e { w.WriteHeader(http.StatusOK) io.WriteString(w, "The job was deleted") } else { w.WriteHeader(http.StatusInternalServerError) io.WriteString(w, e.Error()) } return } } case "DELETE": for _, job_id := range job_id_list { if job_id.MatchString(r.URL.Path) { ss := strings.Split(r.URL.Path, "/") id, e := strconv.ParseInt(ss[len(ss)-1], 10, 0) if nil != e { w.WriteHeader(http.StatusBadRequest) io.WriteString(w, e.Error()) return } e = backend.destroy(id) if nil == e { w.WriteHeader(http.StatusOK) io.WriteString(w, "The job was deleted") } else { w.WriteHeader(http.StatusInternalServerError) io.WriteString(w, e.Error()) } return } } } w.WriteHeader(http.StatusNotFound) }
func main() { flag.Parse() // stats is a proxifying target/debug/pprofstats. // TODO(jbd): If the UI frontend knows about the target, we // might have eliminated the proxy handler. http.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) { url := fmt.Sprintf("%s/debug/pprofstats", *target) resp, err := http.Get(url) if err != nil { log.Print(err) w.WriteHeader(500) fmt.Fprintf(w, "%v", err) return } defer resp.Body.Close() all, err := ioutil.ReadAll(resp.Body) if err != nil { w.WriteHeader(500) fmt.Fprintf(w, "%v", err) return } if resp.StatusCode != http.StatusOK { w.WriteHeader(500) fmt.Fprintf(w, "%s", all) return } w.Header().Set("Content-Type", "application/json") fmt.Fprintf(w, "%s", all) }) // p responds back with a profile report. http.HandleFunc("/p", func(w http.ResponseWriter, r *http.Request) { profile := r.FormValue("profile") filter := r.FormValue("filter") img, _ := strconv.ParseBool(r.FormValue("img")) cumsort, _ := strconv.ParseBool(r.FormValue("cumsort")) force, _ := strconv.ParseBool(r.FormValue("force")) rpt, ok := reports[profile] if !ok { w.WriteHeader(404) fmt.Fprintf(w, "Profile not found.") return } if !rpt.Inited() || force { if err := rpt.Fetch(0); err != nil { w.WriteHeader(500) fmt.Fprintf(w, "%v", err) return } } var re *regexp.Regexp var err error if filter != "" { re, err = regexp.Compile(filter) } if err != nil { w.WriteHeader(400) fmt.Fprintf(w, "%v", err) return } if img { w.Header().Set("Content-Type", "image/svg+xml") rpt.Draw(w, cumsort, re) return } w.Header().Set("Content-Type", "application/json") rpt.Filter(w, cumsort, re) }) statikFS, err := fs.New() if err != nil { log.Fatal(err) } http.Handle("/", http.FileServer(statikFS)) host, port, err := net.SplitHostPort(*listen) if err != nil { log.Fatal(err) } if host == "" { host = "localhost" } log.Printf("Point your browser to http://%s", net.JoinHostPort(host, port)) log.Fatal(http.ListenAndServe(*listen, nil)) }
func init() { StatikFS, _ = fs.New() }
// getBoneRouter returns mux for admin interface func getBoneRouter(d *Hoverfly) *bone.Mux { mux := bone.New() // getting auth controllers and middleware ac := controllers.GetNewAuthenticationController( d.Authentication, d.Cfg.SecretKey, d.Cfg.JWTExpirationDelta, d.Cfg.AuthEnabled) am := authentication.GetNewAuthenticationMiddleware( d.Authentication, d.Cfg.SecretKey, d.Cfg.JWTExpirationDelta, d.Cfg.AuthEnabled) mux.Post("/api/token-auth", http.HandlerFunc(ac.Login)) mux.Get("/api/refresh-token-auth", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(ac.RefreshToken), )) mux.Get("/api/logout", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(ac.Logout), )) mux.Get("/api/users", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(ac.GetAllUsersHandler), )) mux.Get("/api/records", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.AllRecordsHandler), )) mux.Delete("/api/records", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.DeleteAllRecordsHandler), )) mux.Post("/api/records", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.ImportRecordsHandler), )) mux.Get("/api/templates", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.GetAllTemplatesHandler), )) mux.Delete("/api/templates", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.DeleteAllTemplatesHandler), )) mux.Post("/api/templates", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.ImportTemplatesHandler), )) mux.Get("/api/metadata", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.AllMetadataHandler), )) mux.Put("/api/metadata", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.SetMetadataHandler), )) mux.Delete("/api/metadata", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.DeleteMetadataHandler), )) mux.Get("/api/count", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.RecordsCount), )) mux.Get("/api/stats", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.StatsHandler), )) // TODO: check auth for websocket connection mux.Get("/api/statsws", http.HandlerFunc(d.StatsWSHandler)) mux.Get("/api/state", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.CurrentStateHandler), )) mux.Post("/api/state", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.StateHandler), )) mux.Get("/api/middleware", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.CurrentMiddlewareHandler), )) mux.Post("/api/middleware", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.MiddlewareHandler), )) mux.Post("/api/add", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.ManualAddHandler), )) mux.Get("/api/health", negroni.New( negroni.HandlerFunc(d.HealthHandler), )) mux.Get("/api/delays", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.GetResponseDelaysHandler), )) mux.Put("/api/delays", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.UpdateResponseDelaysHandler), )) mux.Delete("/api/delays", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(d.DeleteAllResponseDelaysHandler), )) if d.Cfg.Development { // since hoverfly is not started from cmd/hoverfly/hoverfly // we have to target to that directory log.Warn("Hoverfly is serving files from /static/admin/dist instead of statik binary!") mux.Handle("/js/*", http.StripPrefix("/js/", http.FileServer(http.Dir("../../static/admin/dist/js")))) mux.HandleFunc("/*", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "../../static/admin/dist/index.html") }) } else { // preparing static assets for embedded admin statikFS, err := fs.New() if err != nil { log.WithFields(log.Fields{ "Error": err.Error(), }).Error("Failed to load statikFS, admin UI might not work :(") } mux.Handle("/js/*", http.FileServer(statikFS)) mux.Handle("/app.32dc9945fd902da8ed2cccdc8703129f.css", http.FileServer(statikFS)) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { file, err := statikFS.Open("/index.html") if err != nil { w.WriteHeader(500) log.WithFields(log.Fields{ "error": err, }).Error("got error while opening index file") return } io.Copy(w, file) w.WriteHeader(200) }) } return mux }