LoginSignup
7

More than 5 years have passed since last update.

GoでQRコードを出力するサービスを作ってみる

Posted at

あるページにアクセスしたらQRコードを表示させる機能を作る必要があったので、Goで簡単に作れないか無いか調べたら以下を見つけたので、net/httpを使って簡単にQRコードを生成できるサービスを作ってみます。

サンプルコード

package main

import (
    "fmt"
    "github.com/boombuler/barcode"
    "github.com/boombuler/barcode/qr"
    "image/png"
    "net/http"
)

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8082", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    messages, ok := r.URL.Query()["m"]
    if(!ok || len(messages[0]) < 1) {
        fmt.Fprintln(w, "Missing needed parameter 'm'.")
        return
    }
    qrCode, _ := qr.Encode(messages[0], qr.L, qr.Auto)
    qrCode, _ = barcode.Scale(qrCode, 512, 512)
    png.Encode(w, qrCode)
}

使い方

パラメータmに好きな文字を入れるとその文字のQRコードを生成して表示してくれます。

http://localhost:8082/?m=hoge

スクリーンショット 2018-09-29 21.05.14.png

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
7