编译

在kong的镜像中使用的是alpine linux,在linux上build的.so文件和go-pluginserver无法在容器中运行,需要使用golang:alpine来build

  1. $ apk add gcc --update-cache --repository http://mirrors.ustc.edu.cn/alpine/v3.4/main/ --allow-untrusted
  2. # 编译go-pluginserver
  3. $ GOPROXY=https://goproxy.cn go get -d -v github.com/Kong/go-pluginserver
  4. $ GOPROXY=https://goproxy.cn CGO_ENABLED=0 go build github.com/Kong/go-pluginserver
  5. # 编译插件
  6. $ apk add libc-dev --update-cache --repository http://mirrors.ustc.edu.cn/alpine/v3.4/main/ --allow-untrusted
  7. $ GOPROXY=https://goproxy.cn go build -buildmode plugin auth-plugin.go

直接使用golang:alpine来做镜像

  1. FROM golang:alpine as builder
  2. RUN apk add --no-cache git gcc libc-dev
  3. RUN go get github.com/Kong/go-pluginserver
  4. RUN mkdir /go-plugins
  5. COPY go-key-checker.go /go-plugins/go-key-checker.go
  6. RUN go build -buildmode plugin -o /go-plugins/go-key-checker.so /go-plugins/go-key-checker.go
  7. FROM kong:2.0.1-alpine
  8. COPY --from=builder /go/bin/go-pluginserver /usr/local/bin/go-pluginserver
  9. RUN mkdir /tmp/go-plugins
  10. COPY --from=builder /go-plugins/go-key-checker.so /tmp/go-plugins/go-key-checker.so
  11. COPY config.yml /tmp/config.yml
  12. USER root
  13. RUN chmod -R 775 /tmp
  14. USER kong

Go-plugin

  1. package main
  2. import (
  3. "github.com/Kong/go-pdk"
  4. )
  5. // it represents to config parameters into the config.yml
  6. type Config struct {
  7. Apikey string
  8. }
  9. func New() interface{} {
  10. return &Config{}
  11. }
  12. func (conf Config) Access(kong *pdk.PDK) {
  13. key, err := kong.Request.GetQueryArg("key")
  14. apiKey := conf.Apikey
  15. if err != nil {
  16. kong.Log.Err(err.Error())
  17. }
  18. //it adjusts the header parameters in this way.
  19. x := make(map[string][]string)
  20. x["Content-Type"] = append(x["Content-Type"], "application/json")
  21. //If the key of the consumer is not equal to the claimed key, kong doesn't ensure the proxy
  22. if apiKey != key {
  23. kong.Response.Exit(403, "You have no correct consumer key.", x)
  24. }
  25. }

知识链接

  1. 链接