func main() { c := 0 webl := func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Hello Avatar") log.Printf("Page Visited\n") } countr := func(w http.ResponseWriter, req *http.Request) { c++ fmt.Fprintf(w, "Hi there<br/>You're visiter #%v", c) log.Printf("Countr visited %v times\n", c) } sfile := func(w http.ResponseWriter, req *http.Request) { http.ServeFile(w, req, "test2") log.Printf("Served File\n") } echoUrlInfo := func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Hi there<br/>The URL you're visiting is made up of these component parts!<br/>Gocode!:<br/>%T<br/>%#v", req, req) log.Printf("Hit URL Info page\n") } http.HandleFunc("/hello", webl) http.HandleFunc("/counter", countr) http.HandleFunc("/fileTest", sfile) http.HandleFunc("/urlInfo", echoUrlInfo) err := http.ListenAndServe(":12345", nil) if err != nil { log.Fatalf("ListenAndServe: ", err.String()) } }
func RenderTiles(w http.ResponseWriter, req *http.Request) { e := os.Remove("svg/test-surface.svg") if e != nil { os.Stderr.WriteString(e.String() + "\n") } if CurrentTiling == nil { EmptySvg(w, req) return } style := req.FormValue("style") image := cairo.NewSurface("svg/test-surface.svg", 72*4, 72*4) image.SetSourceRGB(0., 0., 0.) image.SetLineWidth(.1) image.Translate(72*2., 72*2.) image.Scale(4., 4.) if style == "edges" { image.SetSourceRGBA(0., 0., 0., 1.) CurrentTiling.DrawEdges(image) } else if style == "plain" { CurrentTiling.ColourFaces(image, zellij.OrangeBlueBrush) } else { CurrentTiling.ColourDebugFaces(image) CurrentTiling.DrawDebugEdges(image) } image.Finish() http.ServeFile(w, req, "svg/test-surface.svg") }
func init() { fmt.Println("Selog filekkkk") http.Handle("/index", http.HandlerFunc(Render)) http.Handle("/index.ghtml", http.HandlerFunc(RenderGoPagesForbidden)) http.Handle("/", http.HandlerFunc(func(conn http.ResponseWriter, request *http.Request) { if request.URL.Path == "/" { defaultPage := "index" if strings.TrimSpace(defaultPage) != "" { http.Redirect(conn, defaultPage, 307) } return } val := "src" + request.URL.Path input, err := os.OpenFile(val, os.O_RDONLY, 0666) // input,err := os.Open(val) if err != nil { conn.WriteHeader(404) conn.Write([]byte("<h1>404 Not Found</h1>")) return } s, _ := input.Stat() conn.Header.Set("Content-Length", fmt.Sprintf("%d(MISSING)", s.Size)) // conn.SetHeader("Content-Type", mime.TypeByExtension(strings.ToLower(path.Ext(val)))) fmt.Sprintf("%d(MISSING)", s.Size) mime.TypeByExtension(strings.ToLower(path.Ext(val))) conn.WriteHeader(200) http.ServeFile(conn, request, val) })) http.Handle("/src", http.HandlerFunc(RenderGoPagesForbidden)) http.Handle("/pages", http.HandlerFunc(RenderGoPagesForbidden)) }
func FileServer(c *http.Conn, req *http.Request) { if req.URL.Path == "/" { http.Redirect(c, "index.html", 307) return } else if strings.HasSuffix(req.URL.Path, "html") { data, _ := ioutil.ReadFile(req.URL.Path[1:]) io.WriteString(c, string(data)) return } http.ServeFile(c, req, req.URL.Path[1:]) }
func File(w http.ResponseWriter, r *http.Request) { fn := *root + r.URL.Path[len(filePrefix):] fi, err := os.Stat(fn) if err != nil { http.Error(w, err.String(), http.StatusNotFound) return } if fi.IsDirectory() { serveDirectory(fn, w, r) return } http.ServeFile(w, r, fn) }
func serveBin(name string) func(w http.ResponseWriter, req *http.Request) { return func(w http.ResponseWriter, req *http.Request) { me, _ := os.Readlink("/proc/self/exe") d, _ := filepath.Split(me) for _, n := range []string{ filepath.Join(d, name), filepath.Join(d, fmt.Sprintf("../%s/%s", name, name)), } { if fi, _ := os.Lstat(n); fi != nil && fi.IsRegular() { http.ServeFile(w, req, n) } } } }
func (h *CgiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { path := r.URL.Path var isCGI bool file := filepath.FromSlash(path) if len(file) > 0 && os.IsPathSeparator(file[len(file)-1]) { file = file[:len(file)-1] } ext := filepath.Ext(file) bin, isCGI := h.LangMap[ext] file = filepath.Join(h.Root, file) f, e := os.Stat(file) if e != nil || f.IsDirectory() { if len(h.DefaultApp) > 0 { file = h.DefaultApp } ext := filepath.Ext(file) bin, isCGI = h.LangMap[ext] } if isCGI { var cgih cgi.Handler if h.UseLangMap { cgih = cgi.Handler{ Path: bin, Dir: h.Root, Root: h.Root, Args: []string{file}, Env: []string{"SCRIPT_FILENAME=" + file}, } } else { cgih = cgi.Handler{ Path: file, Root: h.Root, } } cgih.ServeHTTP(w, r) } else { if (f != nil && f.IsDirectory()) || file == "" { tmp := filepath.Join(file, "index.html") f, e = os.Stat(tmp) if e == nil { file = tmp } } http.ServeFile(w, r, file) } }
func main() { flag.Parse() // source of unique numbers go func() { for i := 0; ; i++ { uniq <- i } }() // set archChar var err os.Error archChar, err = build.ArchChar(runtime.GOARCH) if err != nil { log.Fatal(err) } // find and serve the go tour files t, _, err := build.FindTree(basePkg) if err != nil { log.Fatalf("Couldn't find tour files: %v", err) } root := filepath.Join(t.SrcDir(), basePkg) root := basePkg log.Println("Serving content from", root) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/favicon.ico" || r.URL.Path == "/" { fn := filepath.Join(root, "static", r.URL.Path[1:]) http.ServeFile(w, r, fn) return } http.Error(w, "not found", 404) }) http.Handle("/static/", http.FileServer(http.Dir(root))) http.HandleFunc("/kill", kill) // set include path for ld and gc pkgDir = t.PkgDir() if !strings.HasPrefix(*httpListen, "127.0.0.1") && !strings.HasPrefix(*httpListen, "localhost") { log.Print(localhostWarning) } log.Printf("Serving at http://%s/", *httpListen) log.Fatal(http.ListenAndServe(*httpListen, nil)) }
func EmbellishFrame(w http.ResponseWriter, req *http.Request) { e := os.Remove("svg/embellishment.svg") if e != nil { os.Stderr.WriteString(e.String() + "\n") } frame := quadratic.NewMap() jsonErr := json.NewDecoder(strings.NewReader(req.FormValue("frame"))).Decode(frame) if jsonErr != nil { os.Stderr.WriteString("json error: " + jsonErr.String() + "\n") return } zig, err := zellij.Embellish(frame, MotifDatabase) if err != nil { os.Stderr.WriteString(err.String() + "\n") return } fmt.Fprintf(os.Stderr, "embellishment has %v faces\n", zig.Faces.Len()) bx := zig.Verticies.At(0).(*quadratic.Vertex).Point tx := zig.Verticies.At(0).(*quadratic.Vertex).Point by := zig.Verticies.At(0).(*quadratic.Vertex).Point ty := zig.Verticies.At(0).(*quadratic.Vertex).Point for i := 1; i < zig.Verticies.Len(); i++ { v := zig.Verticies.At(i).(*quadratic.Vertex).Point if v.Y().Float64() < by.Y().Float64() { by = v } else if v.Y().Float64() > ty.Y().Float64() { ty = v } if v.X().Float64() < bx.X().Float64() { bx = v } else if v.X().Float64() > tx.X().Float64() { tx = v } } xwidth := math.Floor(tx.X().Float64() - bx.X().Float64() + 20.0) ywidth := math.Floor(ty.Y().Float64() - by.Y().Float64() + 20.0) image := cairo.NewSurface("svg/embellishment.svg", xwidth*4, ywidth*4) image.SetSourceRGB(0., 0., 0.) image.SetLineWidth(.1) image.Translate(-bx.X().Float64()*4.+40, -by.Y().Float64()*4.+40) image.Scale(4., 4.) zig.ColourFaces(image, zellij.OrangeBlueBrush) image.Finish() http.ServeFile(w, req, "svg/embellishment.svg") }
func Redirect(w http.ResponseWriter, r *http.Request) { key := r.URL.Path[1:] if key == "favicon.ico" { http.NotFound(w, r) } else if key == "" { logo := &Title{Logo: "You.RL"} tpl, _ := template.ParseFile("index.html", nil) tpl.Execute(w, logo) } else if key == "index.js" { http.ServeFile(w, r, "index.js") } else { var url string store.Get(&key, &url) http.Redirect(w, r, url, http.StatusFound) } }
func DrawSkel(w http.ResponseWriter, req *http.Request) { e := os.Remove("svg/test-surface.svg") if e != nil { os.Stderr.WriteString(e.String() + "\n") } skeleton := req.FormValue("skeleton") image := cairo.NewSurface("svg/test-surface.svg", 72*4, 72*4) image.SetSourceRGB(0., 0., 0.) image.SetLineWidth(.1) image.Translate(72*2., 72*2.) image.Scale(4., 4.) skel, ok := zellij.SkeletonMap(skeleton) if ok != nil { os.Stderr.WriteString(ok.String() + "\n") } skel.DrawEdges(image) image.Finish() http.ServeFile(w, req, "svg/test-surface.svg") }
func httpHandler(c *http.Conn, req *http.Request) { path := req.URL.Path //try to serve a static file if strings.HasPrefix(path, "/static/") { staticFile := path[8:] if len(staticFile) > 0 { http.ServeFile(c, req, "static/"+staticFile) return } } req.ParseForm() resp := routeHandler((*Request)(req)) c.WriteHeader(resp.StatusCode) if resp.Body != nil { body, _ := ioutil.ReadAll(resp.Body) c.Write(body) } }
// Server static files, like CSS and JS directly func StaticFile(response http.ResponseWriter, request *http.Request) { url := request.URL.Path // remove the beginning slash so we don't look in the FS root for the file if url[0] == '/' { url = url[1:] } if strings.Contains(url, "../") { log.Println("Attempt to traverse outside of static folders.") http.Error(response, "Stop it.", http.StatusInternalServerError) return } // Log that a static file was served log.Print("Serving static file ", url) // serve the file http.ServeFile(response, request, url) }
func MotifScreen(w http.ResponseWriter, req *http.Request) { http.ServeFile(w, req, "ui/ui.html") }
func MainScreen(w http.ResponseWriter, req *http.Request) { http.ServeFile(w, req, "ui/skeleton.html") }
func raw(c *http.Conn, req *http.Request, id string) { http.ServeFile(c, req, "pastes/"+id) }
func jQuery(c *http.Conn, req *http.Request) { http.ServeFile(c, req, "jquery.js") }
func EmptySvg(w http.ResponseWriter, req *http.Request) { http.ServeFile(w, req, "svg/empty") }
/* * Handle static files */ func staticHandler(w http.ResponseWriter, r *http.Request) { fileName := r.URL.Path[8:] http.ServeFile(w, r, StaticDir+fileName) }
/* * Display image */ func imgHandler(w http.ResponseWriter, r *http.Request) { fileName := r.URL.Path[5:] w.Header().Set("Content-Type", "image") http.ServeFile(w, r, "img/"+fileName) }
// Start will start service. func (s *HTTPServer) Start(port int) { http.HandleFunc("/", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { log.Println("access /") params := new(struct{}) tmpl := getTemplate("index.html") err := tmpl.Execute(params, rw) if err != nil { log.Exit("%v", err) } })) http.HandleFunc("/put", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { log.Println("access /put") req.ParseForm() x, _ := strconv.Atoi(req.Form["x"][0]) y, _ := strconv.Atoi(req.Form["y"][0]) m := s.currentMatch() if hp, ok := m.CurrentPlayer().(*http_player.HttpPlayer); ok { hp.SetNext(x, y) } matchStatus, playerResponse := m.Next() switch playerResponse.Type { case match.PUT: fmt.Fprint(rw, m.Json()) case match.KO: fmt.Fprint(rw, "({'message':'コウです'})") case match.FORBIDDEN: fmt.Fprint(rw, "({'message':'着手禁止です'})") case match.PASS: if matchStatus == match.FINISH { fmt.Fprint(rw, "({'message':'終了しました'})") } else { fmt.Fprint(rw, "({'message':'パスしました'})") } case match.GIVEUP: fmt.Fprint(rw, "({'message':'終了しました'})") } })) http.HandleFunc("/get", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { //log.Println("access /get") m := s.currentMatch() if _, ok := m.CurrentPlayer().(*http_player.HttpPlayer); !ok { m.Next() } fmt.Fprint(rw, m.Json()) })) http.Handle("/css/", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { http.ServeFile(rw, req, "./htdocs/"+req.URL.Path) })) http.Handle("/js/", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { http.ServeFile(rw, req, "./htdocs/"+req.URL.Path) })) err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil) if err != nil { log.Exit("ListenAndServe: ", err.String()) } }
func serveIndex(res http.ResponseWriter, req *http.Request) { log.Println("Serving index file for request ", req.URL.Path) http.ServeFile(res, req, "www/index.html") }
func serveStaticFile(res http.ResponseWriter, req *http.Request) { log.Println("Serving static file ", req.URL.Path) http.ServeFile(res, req, "www"+req.URL.Path) }
func Static(w http.ResponseWriter, r *http.Request) { logResponse(w, r) f := r.URL.Path[1:] http.ServeFile(w, r, f) }
func main() { sqlite3.Initialize() defer func() { log.Stdout("closing sqlite3") sqlite3.Shutdown() }() dbh := new(sqlite3.Handle) dbh.Open("bbs.db") defer dbh.Close() InitTables(dbh) flag.Parse() templ := func() *template.Template { templateStr, err := io.ReadFile("tmpl/top.tmpl") if err != nil { log.Exit(err) } return template.MustParse(string(templateStr), nil) }() http.Handle("/", http.HandlerFunc(func(c *http.Conn, req *http.Request) { params := new(struct{ msgs []string }) storage := new(vector.StringVector) func() { st, err := dbh.Prepare("SELECT * from entry ORDER BY id DESC limit 30;") func() { if err != "" { log.Exit(err) } for { rv := st.Step() switch { case rv == sqlite3.SQLITE_DONE: return case rv == sqlite3.SQLITE_ROW: body := st.ColumnText(1) storage.Push(body) default: println(rv) log.Exit(dbh.ErrMsg()) } } }() if st.Finalize() != sqlite3.SQLITE_OK { log.Exit(dbh.ErrMsg()) } }() params.msgs = storage.Data() err := templ.Execute(params, c) if err != nil { log.Exit("templ.Execute:", err) } })) http.Handle("/post", http.HandlerFunc(func(c *http.Conn, req *http.Request) { req.ParseForm() body := req.Form["body"][0] st, err := dbh.Prepare("INSERT INTO entry (body) VALUES (?)") if err != "" { log.Exit(err) } if st.BindText(1, body) != sqlite3.SQLITE_OK { log.Exit("cannot bind: ", dbh.ErrMsg()) } if st.Step() != sqlite3.SQLITE_DONE { log.Exit(dbh.ErrMsg()) } if st.Finalize() != sqlite3.SQLITE_OK { log.Exit(dbh.ErrMsg()) } http.Redirect(c, "/", 302) })) http.Handle("/css/", http.HandlerFunc(func(c *http.Conn, req *http.Request) { http.ServeFile(c, req, "."+req.URL.Path) })) // run httpd func() { fmt.Printf("http://%s/\n", *addr) err := http.ListenAndServe(*addr, nil) if err != nil { log.Exit("ListenAndServe:", err) } }() }
func cssFile(c *http.Conn, req *http.Request, file string) { http.ServeFile(c, req, "css/"+file+".css") }
func js(c *http.Conn, req *http.Request) { http.ServeFile(c, req, "paste.js") }
func Home(w http.ResponseWriter, r *http.Request) { if r.RawURL == "/favicon.ico" { return } fmt.Fprintf(os.Stdout, "%s %s\n", r.Method, r.RawURL) http.ServeFile(w, r, "templates/index.html") }
func Static(w http.ResponseWriter, r *http.Request) { filename := r.URL.Path[1:] if filename == "" { filename = "index.html" } else if filename[:6] != "flotr/" { http.NotFound(w, r) return } http.ServeFile(w, r, "static/"+filename) }
func resourceHandler(w http.ResponseWriter, req *http.Request) { if req.Method == "GET" { log.Printf("Serving up path %s", req.URL.Path) if req.URL.Path == "/" { log.Printf("...redirecting to [resources/index.html]") http.ServeFile(w, req, "resources/index.html") } else { http.ServeFile(w, req, "resources/"+req.URL.Path) } } else { w.WriteHeader(400) } }