本文整理匯總了Golang中http.ServeFile函數的典型用法代碼示例。如果您正苦於以下問題:Golang ServeFile函數的具體用法?Golang ServeFile怎麽用?Golang ServeFile使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了ServeFile函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: resourceHandler
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)
}
}
示例2: init
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))
}
示例3: Home
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")
}
示例4: main
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())
}
}
示例5: RenderTiles
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")
}
示例6: FileServer
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:])
}
示例7: File
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)
}
示例8: serveBin
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)
}
}
}
}
示例9: ServeHTTP
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)
}
}
示例10: main
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))
}
示例11: EmbellishFrame
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")
}
示例12: Redirect
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)
}
}
示例13: DrawSkel
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")
}
示例14: httpHandler
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)
}
}
示例15: StaticFile
// 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)
}