go-lang simple webserver : serve static image -


i want write simple webserver in go following: when go http://example.go:8080/image, returns static image. i'm following example found here. in example implement method:

func handler(w http.responsewriter, r *http.request) {     fmt.fprintf(w, "hi there, love %s!", r.url.path[1:]) } 

and refer here :

... ... http.handlefunc("/", handler) 

now, wanna serve image instead of writing string. how go that?

you can serve static files using http.fileserver function.

package main  import (     "log"     "net/http" )  func main() {     http.handle("/", http.stripprefix("/", http.fileserver(http.dir("path/to/file"))))     if err := http.listenandserve(":8080", nil); err != nil {         log.fatal("listenandserve: ", err)     } } 

edit: more idiomatic code.

edit 2: code above return image image.png when browser requests http://example.go/image.png

the http.stripprefix function here strictly unnecessary in case path being handled web root. if images served path http://example.go/images/image.png line above need http.handle("/images/", http.stripprefix("/images/", http.fileserver(http.dir("path/to/file")))).

playground


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -