一,Dockerfile
#####################
## Go plugins - https://github.com/Kong/docker-kong/issues/326
#####################
FROM kong:2.0-ubuntu as compiler
USER root
RUN sed -i s@/archive.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list
RUN sed -i s@/deb.debian.org/@/mirrors.aliyun.com/@g /etc/apt/sources.list
RUN apt-get clean
## We've tried also :
## FROM ubuntu:16.04 as compiler
## FROM ubuntu:18.04 as compiler
# Install build tools
RUN apt-get update -y && DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends -y -q curl build-essential ca-certificates git
# Download and configure Go compiler
RUN curl -s https://storage.googleapis.com/golang/go1.13.5.linux-amd64.tar.gz | tar -v -C /usr/local -xz
ENV GOPATH /go
ENV GOROOT /usr/local/go
ENV PATH $PATH:/usr/local/go/bin
# Copy and compile go-plugins
RUN go get github.com/Kong/go-pluginserver
#RUN git clone https://github.com/Kong/go-plugins /usr/src/go-plugins
#RUN mkdir /tmp/go-plugins && cp /usr/src/go-plugins/go-hello.go /tmp/go-plugins
RUN mkdir /tmp/go-plugins
COPY ./plugins/go-hello.go /tmp/go-plugins
RUN cd /tmp/go-plugins && go build -buildmode plugin go-hello.go
#####################
## Release image
#####################
FROM kong:2.0-ubuntu
RUN mkdir -p /usr/local/kong \
&& chown -R kong:0 /usr/local/kong \
&& chmod -R g=u /usr/local/kong
# Copy Go files
COPY --from=compiler /tmp/go-plugins/*.so /usr/local/kong/
COPY --from=compiler /go/bin/go-pluginserver /usr/local/bin/go-pluginserver
USER kong
COPY config.yml /tmp/config.yml
二,go-hello.go
/*
A "hello world" plugin in Go,
which reads a request header and sets a response header.
*/
package main
import (
"fmt"
"github.com/Kong/go-pdk"
)
type Config struct {
Message string
}
func New() interface{} {
return &Config{}
}
func (conf Config) Access(kong *pdk.PDK) {
host, err := kong.Request.GetHeader("host")
if err != nil {
kong.Log.Err(err.Error())
}
message := conf.Message
if message == "" {
message = "hello zander"
}
kong.Response.SetHeader("x-hello-from-go", fmt.Sprintf("Go says %s to %s", message, host))
}
三,config.yml
# go.yml
_format_version: "1.1"
services:
- url: https://blog.csdn.net/zhangzhen02/article/details/112233859
routes:
- paths:
- "/"
plugins:
- name: go-hello
config:
message: "hello zander!"
四,目录结构
|--Dockerfile
|--config.yml
|--plugins
|--go-hello.go
五,生成镜像并执行
docker build -t kong1 .
docker run -ti --rm --name kong-go-plugins -e "KONG_DATABASE=off" -e "KONG_GO_PLUGINS_DIR=/usr/local/kong" -e "KONG_DECLARATIVE_CONFIG=/tmp/config.yml" -e "KONG_PLUGINS=go-hello" -e "KONG_PROXY_LISTEN=0.0.0.0:8000" -p 8 000:8000 kong1
六,访问localhost:8000,可以看到go 插件生效
以上。