This commit is contained in:
Dominic Wong
2021-09-20 11:15:52 +01:00
committed by GitHub
parent 0ab4b37981
commit 4319f7bf4c
14 changed files with 514 additions and 0 deletions

1
go.mod
View File

@@ -40,6 +40,7 @@ require (
github.com/pquerna/otp v1.3.0
github.com/sendgrid/rest v2.6.4+incompatible // indirect
github.com/sendgrid/sendgrid-go v3.10.0+incompatible
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/stoewer/go-strcase v1.2.0
github.com/stretchr/testify v1.7.0
github.com/teris-io/shortid v0.0.0-20171029131806-771a37caa5cf

2
go.sum
View File

@@ -443,6 +443,8 @@ github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeV
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
github.com/skratchdot/open-golang v0.0.0-20160302144031-75fb7ed4208c/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=

2
qr/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
qr

3
qr/Dockerfile Normal file
View File

@@ -0,0 +1,3 @@
FROM alpine
ADD qr /qr
ENTRYPOINT [ "/qr" ]

28
qr/Makefile Normal file
View File

@@ -0,0 +1,28 @@
GOPATH:=$(shell go env GOPATH)
.PHONY: init
init:
go get -u github.com/golang/protobuf/proto
go get -u github.com/golang/protobuf/protoc-gen-go
go get github.com/micro/micro/v3/cmd/protoc-gen-micro
go get github.com/micro/micro/v3/cmd/protoc-gen-openapi
.PHONY: api
api:
protoc --openapi_out=. --proto_path=. proto/qr.proto
.PHONY: proto
proto:
protoc --proto_path=. --micro_out=. --go_out=:. proto/qr.proto
.PHONY: build
build:
go build -o qr *.go
.PHONY: test
test:
go test -v ./... -cover
.PHONY: docker
docker:
docker build . -t qr:latest

6
qr/README.md Normal file
View File

@@ -0,0 +1,6 @@
Quickly generate QR Codes with a single call
# QR Code Service
Generate QR codes for whatever you like. Typically, used for website URLs but could be any text like email addresses, phone numbers, addresses etc.

13
qr/examples.json Normal file
View File

@@ -0,0 +1,13 @@
{
"generate": [{
"title": "Generate a QR code",
"run_check": false,
"request": {
"text": "https://m3o.com/qr",
"size": 300
},
"response": {
"qr": "http://cdn.m3ocontent.com/micro/qr/micro/dom/9bb3ca11-3641-4f59-967f-6a81158350d9.png"
}
}]
}

2
qr/generate.go Normal file
View File

@@ -0,0 +1,2 @@
package main
//go:generate make proto

92
qr/handler/qr.go Normal file
View File

@@ -0,0 +1,92 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"github.com/micro/micro/v3/service/config"
"github.com/micro/micro/v3/service/errors"
log "github.com/micro/micro/v3/service/logger"
"github.com/micro/micro/v3/service/store"
"github.com/micro/services/pkg/tenant"
qr "github.com/micro/services/qr/proto"
"github.com/skip2/go-qrcode"
)
const (
prefixByTenant = "qrByTenant"
defaultCodeSize = 256
)
type QrCode struct {
Filename string `json:"filename"`
Created int64 `json:"created"`
Text string `json:"text"`
}
type Qr struct {
cdnPrefix string
}
func New() *Qr {
v, err := config.Get("micro.qr.cdnprefix")
if err != nil {
log.Fatalf("Failed to get CDN prefix %s", err)
}
pref := v.String("")
if len(pref) == 0 {
log.Fatalf("Failed to get CDN prefix")
}
return &Qr{cdnPrefix: pref}
}
func (q *Qr) Generate(ctx context.Context, request *qr.GenerateRequest, response *qr.GenerateResponse) error {
if len(request.Text) == 0 {
return errors.BadRequest("qr.generate", "Missing parameter text")
}
ten, ok := tenant.FromContext(ctx)
if !ok {
log.Errorf("Error retrieving tenant")
return errors.Unauthorized("qr.generate", "Unauthorized")
}
size := defaultCodeSize
if request.Size > 0 {
size = int(request.Size)
}
qrc, err := qrcode.Encode(request.Text, qrcode.Medium, size)
if err != nil {
log.Errorf("Error generating QR code %s", err)
return errors.InternalServerError("qr.generate", "Error while generating QR code")
}
nsPrefix := "micro/qr/" + ten
fileName := fmt.Sprintf("%s.png", uuid.New().String())
if err := store.DefaultBlobStore.Write(
fileName, bytes.NewBuffer(qrc),
store.BlobContentType("image/png"),
store.BlobPublic(true),
store.BlobNamespace(nsPrefix)); err != nil {
log.Errorf("Error saving QR code to blob store %s", err)
return errors.InternalServerError("qr.generate", "Error while generating QR code")
}
// store record of it
rec := QrCode{
Filename: fileName,
Created: time.Now().Unix(),
Text: request.Text,
}
b, _ := json.Marshal(&rec)
if err := store.Write(&store.Record{
Key: fmt.Sprintf("%s/%s/%s", prefixByTenant, nsPrefix, fileName),
Value: b,
}); err != nil {
log.Errorf("Error saving QR code record %s", err)
return errors.InternalServerError("qr.generate", "Error while generating QR code")
}
response.Qr = fmt.Sprintf("%s/%s/%s", q.cdnPrefix, nsPrefix, rec.Filename)
return nil
}

25
qr/main.go Normal file
View File

@@ -0,0 +1,25 @@
package main
import (
"github.com/micro/services/qr/handler"
pb "github.com/micro/services/qr/proto"
"github.com/micro/micro/v3/service"
"github.com/micro/micro/v3/service/logger"
)
func main() {
// Create service
srv := service.New(
service.Name("qr"),
service.Version("latest"),
)
// Register handler
pb.RegisterQrHandler(srv.Server(), handler.New())
// Run service
if err := srv.Run(); err != nil {
logger.Fatal(err)
}
}

1
qr/micro.mu Normal file
View File

@@ -0,0 +1 @@
service qr

222
qr/proto/qr.pb.go Normal file
View File

@@ -0,0 +1,222 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.15.5
// source: proto/qr.proto
package qr
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type GenerateRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// the text to encode as a QR code (URL, phone number, email, etc)
Text string `protobuf:"bytes,1,opt,name=text,proto3" json:"text,omitempty"`
// the size (height and width) in pixels of the generated QR code. Defaults to 256
Size int64 `protobuf:"varint,2,opt,name=size,proto3" json:"size,omitempty"`
}
func (x *GenerateRequest) Reset() {
*x = GenerateRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_proto_qr_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GenerateRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GenerateRequest) ProtoMessage() {}
func (x *GenerateRequest) ProtoReflect() protoreflect.Message {
mi := &file_proto_qr_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GenerateRequest.ProtoReflect.Descriptor instead.
func (*GenerateRequest) Descriptor() ([]byte, []int) {
return file_proto_qr_proto_rawDescGZIP(), []int{0}
}
func (x *GenerateRequest) GetText() string {
if x != nil {
return x.Text
}
return ""
}
func (x *GenerateRequest) GetSize() int64 {
if x != nil {
return x.Size
}
return 0
}
type GenerateResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// link to the QR code image in PNG format
Qr string `protobuf:"bytes,1,opt,name=qr,proto3" json:"qr,omitempty"`
}
func (x *GenerateResponse) Reset() {
*x = GenerateResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_proto_qr_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GenerateResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GenerateResponse) ProtoMessage() {}
func (x *GenerateResponse) ProtoReflect() protoreflect.Message {
mi := &file_proto_qr_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GenerateResponse.ProtoReflect.Descriptor instead.
func (*GenerateResponse) Descriptor() ([]byte, []int) {
return file_proto_qr_proto_rawDescGZIP(), []int{1}
}
func (x *GenerateResponse) GetQr() string {
if x != nil {
return x.Qr
}
return ""
}
var File_proto_qr_proto protoreflect.FileDescriptor
var file_proto_qr_proto_rawDesc = []byte{
0x0a, 0x0e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x71, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x12, 0x02, 0x71, 0x72, 0x22, 0x39, 0x0a, 0x0f, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x65, 0x78, 0x74, 0x18,
0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x65, 0x78, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x73,
0x69, 0x7a, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x04, 0x73, 0x69, 0x7a, 0x65, 0x22,
0x22, 0x0a, 0x10, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f,
0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x71, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
0x02, 0x71, 0x72, 0x32, 0x3d, 0x0a, 0x02, 0x51, 0x72, 0x12, 0x37, 0x0a, 0x08, 0x47, 0x65, 0x6e,
0x65, 0x72, 0x61, 0x74, 0x65, 0x12, 0x13, 0x2e, 0x71, 0x72, 0x2e, 0x47, 0x65, 0x6e, 0x65, 0x72,
0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x71, 0x72, 0x2e,
0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65,
0x22, 0x00, 0x42, 0x0c, 0x5a, 0x0a, 0x2e, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x3b, 0x71, 0x72,
0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_proto_qr_proto_rawDescOnce sync.Once
file_proto_qr_proto_rawDescData = file_proto_qr_proto_rawDesc
)
func file_proto_qr_proto_rawDescGZIP() []byte {
file_proto_qr_proto_rawDescOnce.Do(func() {
file_proto_qr_proto_rawDescData = protoimpl.X.CompressGZIP(file_proto_qr_proto_rawDescData)
})
return file_proto_qr_proto_rawDescData
}
var file_proto_qr_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_proto_qr_proto_goTypes = []interface{}{
(*GenerateRequest)(nil), // 0: qr.GenerateRequest
(*GenerateResponse)(nil), // 1: qr.GenerateResponse
}
var file_proto_qr_proto_depIdxs = []int32{
0, // 0: qr.Qr.Generate:input_type -> qr.GenerateRequest
1, // 1: qr.Qr.Generate:output_type -> qr.GenerateResponse
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_proto_qr_proto_init() }
func file_proto_qr_proto_init() {
if File_proto_qr_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_proto_qr_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GenerateRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_proto_qr_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GenerateResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_proto_qr_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_proto_qr_proto_goTypes,
DependencyIndexes: file_proto_qr_proto_depIdxs,
MessageInfos: file_proto_qr_proto_msgTypes,
}.Build()
File_proto_qr_proto = out.File
file_proto_qr_proto_rawDesc = nil
file_proto_qr_proto_goTypes = nil
file_proto_qr_proto_depIdxs = nil
}

95
qr/proto/qr.pb.micro.go Normal file
View File

@@ -0,0 +1,95 @@
// Code generated by protoc-gen-micro. DO NOT EDIT.
// source: proto/qr.proto
package qr
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
math "math"
)
import (
context "context"
api "github.com/micro/micro/v3/service/api"
client "github.com/micro/micro/v3/service/client"
server "github.com/micro/micro/v3/service/server"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
// Reference imports to suppress errors if they are not otherwise used.
var _ api.Endpoint
var _ context.Context
var _ client.Option
var _ server.Option
// Api Endpoints for Qr service
func NewQrEndpoints() []*api.Endpoint {
return []*api.Endpoint{}
}
// Client API for Qr service
type QrService interface {
// Generate a QR code
Generate(ctx context.Context, in *GenerateRequest, opts ...client.CallOption) (*GenerateResponse, error)
}
type qrService struct {
c client.Client
name string
}
func NewQrService(name string, c client.Client) QrService {
return &qrService{
c: c,
name: name,
}
}
func (c *qrService) Generate(ctx context.Context, in *GenerateRequest, opts ...client.CallOption) (*GenerateResponse, error) {
req := c.c.NewRequest(c.name, "Qr.Generate", in)
out := new(GenerateResponse)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for Qr service
type QrHandler interface {
// Generate a QR code
Generate(context.Context, *GenerateRequest, *GenerateResponse) error
}
func RegisterQrHandler(s server.Server, hdlr QrHandler, opts ...server.HandlerOption) error {
type qr interface {
Generate(ctx context.Context, in *GenerateRequest, out *GenerateResponse) error
}
type Qr struct {
qr
}
h := &qrHandler{hdlr}
return s.Handle(s.NewHandler(&Qr{h}, opts...))
}
type qrHandler struct {
QrHandler
}
func (h *qrHandler) Generate(ctx context.Context, in *GenerateRequest, out *GenerateResponse) error {
return h.QrHandler.Generate(ctx, in, out)
}

22
qr/proto/qr.proto Normal file
View File

@@ -0,0 +1,22 @@
syntax = "proto3";
package qr;
option go_package = "./proto;qr";
service Qr {
// Generate a QR code
rpc Generate(GenerateRequest) returns (GenerateResponse) {}
}
message GenerateRequest {
// the text to encode as a QR code (URL, phone number, email, etc)
string text = 1;
// the size (height and width) in pixels of the generated QR code. Defaults to 256
int64 size = 2;
}
message GenerateResponse {
// link to the QR code image in PNG format
string qr = 1;
}