Serve image in Go that was just created -
No image is present when I'm dynamically creating an image IE example_t500.jpg when requested. Will be made from jpg The problem I've encountered is displaying the created image, when the request is requested before the image is being hidden. Package main import ( "image / jpeg" "net / http" "Login" "OS", "strings" "Fmti" "Strenco" resizer ""
Github.com/nfnt/resize ") func WebHandler (w http.ResponseWriter, r * http.Request) {var path = "../../static/img/photos/2014/11/4/test.jpg" ResizeImage (path, 500) http.Handle ( " / ", http.FileServer (http.Dir (" example_t500.jpg ")))} func ResizeImage (path string, width UIT) {var image = extension cords." .jpg ") var ImageNum = string.plit (ImageExtension [ 0], "/") var ImageName = ImageNum [len (ImageNum) -1] fmt.println (ImageName) file, err: = os.Open (path) that mistake! = null This is my first time that I am trying to go and I am having trouble rendering the image. Any help is appreciated.
There are some things you need to do.
First of all, you must remove this line from your WebHandler
function:
http.Handle ("/", http.FileServer ( Http.Dir ("example_t500.jpg")))
The default service mix is set to handle the root route - but you already have your main
function This is done in:
http.HandleFunc ("/", WebHandler)
Every time you press the root route, you are effective By the way, the service is just saying to handle it again .. But differently.
What you want to do .. The response is set to content-type
. Then copy the contents of the file in the feedback section. Something like this:
Funk webhandler (w http.ResponseWriter, r * http.Request) {var path = "../../static/img/photos/2014/11/" 4 /test.jpg "ResizeImage (path, 500) img, err: = os.Open (" example_t500.jpg ") if err! = Nil {log.Fatal (err) / / perhaps handle it well} defer img.Close () W.Header (). Set ("content-type", "image / jpeg") // & lt; - Content-Type Header io.Copy (w, img)}
Set is the manual version.
Edit:
In response to your comment - If you do not want to write the file at all and only work dynamically, then all you have to do is Pass the code from http.ResponseWriter
to encoding
. jpeg.Encode
takes a io.Writer
. Just as io.Copy
does in my original example:
// Reply Sample (image extension [0], "/") Var ImageName = ImageNum [len (ImageNum) -1] fmt.Println (ImageName) file, err: = os.Open (path) if err! = Nil {log.Fatal (err)} img, err: = Jpeg.Decode (file) if err! = Nil {log.Fatal (err)} file.Close () m: = resizer.Resize (width, 0, img, resizer.Lanczos3) // Do not write file / * out, err: = os.Create (ImageName + "_t" + strconv.Itoa (int (width)) ".jpg") If mistake! = Zero {log.Fatal (err)} Extrusion. Please accept () * / Jpeg.Encode (w, m, zero) // ResponseWriter}}
accept io.Writer
in the method. Then change it to symbolic words then you can call your method like this:
Funk webhandler (w http.ResponseWriter, r * http.Request) {var path = ". ./../static/img/photos/ "
Comments
Post a Comment