Golang笔记

一个golang http 实现图片服务的例子

一个golang http 实现图片服务

package main

import (
    "bytes"
    "encoding/base64"
    "flag"
    "html/template"
    "image"
    "image/color"
    "image/draw"
    "image/jpeg"
    "log"
    "net/http"
    "strconv"
)

var root = flag.String("root", ".", "file system path")

func main() {
    http.HandleFunc("/blue/", blueHandler)
    http.HandleFunc("/red/", redHandler)
    http.Handle("/", http.FileServer(http.Dir(*root)))
    log.Println("Listening on 8080")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}

func blueHandler(w http.ResponseWriter, r *http.Request) {
    m := image.NewRGBA(image.Rect(0, 0, 240, 240))
    blue := color.RGBA{0, 0, 255, 255}
    draw.Draw(m, m.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src)

    var img image.Image = m
    writeImage(w, &img)
}

func redHandler(w http.ResponseWriter, r *http.Request) {
    m := image.NewRGBA(image.Rect(0, 0, 240, 240))
    blue := color.RGBA{255, 0, 0, 255}
    draw.Draw(m, m.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src)

    var img image.Image = m
    writeImageWithTemplate(w, &img)
}

var ImageTemplate string = `<!DOCTYPE html>
<html lang="en"><head></head>
<body><img src="data:image/jpg;base64,{{.Image}}"></body>`

// Writeimagewithtemplate encodes an image 'img' in jpeg format and writes it into ResponseWriter using a template.
func writeImageWithTemplate(w http.ResponseWriter, img *image.Image) {

    buffer := new(bytes.Buffer)
    if err := jpeg.Encode(buffer, *img, nil); err != nil {
        log.Fatalln("unable to encode image.")
    }

    str := base64.StdEncoding.EncodeToString(buffer.Bytes())
    if tmpl, err := template.New("image").Parse(ImageTemplate); err != nil {
        log.Println("unable to parse image template.")
    } else {
        data := map[string]interface{}{"Image": str}
        if err = tmpl.Execute(w, data); err != nil {
            log.Println("unable to execute template.")
        }
    }
}

// writeImage encodes an image 'img' in jpeg format and writes it into ResponseWriter.
func writeImage(w http.ResponseWriter, img *image.Image) {

    buffer := new(bytes.Buffer)
    if err := jpeg.Encode(buffer, *img, nil); err != nil {
        log.Println("unable to encode image.")
    }

    w.Header().Set("Content-Type", "image/jpeg")
    w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes())))
    if _, err := w.Write(buffer.Bytes()); err != nil {
        log.Println("unable to write image.")
    }
}

来源 https://gist.github.com/santiaago/d6d681d14c5f3b3f5d69 38

本文网址: https://golangnote.com/topic/110.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles