Share a very simple Demo written using Go, why share? There are a couple of little things involved

  1. Go modThe use of
  2. How do I import packages in GO
  3. Simple demo build layers with Go
  4. Demonstrates how to write a scripted Jenkinfile that automates the build.

1. Go modHow to use

We prepare a module of apis in which we implement a function Says(STR string) that prints strings: so

mkdir apis
cat << EOF > ./apis.go
package apis

import "fmt"

func Says(str string) {
    fmt.Printf("hello,%s", name)
}Copy the code

Then we initialize the Go mod

Go GO111MODULE env - w = "auto" go mod init code. Kubemaster. Top/DevOpsTeam/apis # right now look at the mod file content as follows: The cat go. Mod module code. Kubemaster. Top/DevOpsTeam/apis go 1.14Copy the code

Then one is generated in the workspacego.modfileAnd then we initialize the commit to the repository, and the repository’s address ishttps://code.kubemaster.top/DevOpsTeam/apis.git.

2. How do I import packages

The Demo relies on the apis module to implement its functions. The Demo file is called main.go:

Package the main import code. Kubemaster. "top/DevOpsTeam/apis" func main () {apis. Says (" cloud native ecosystem \ n ")}Copy the code

There is a note here: when the program calls a module whose file name does not match that of the module, it needs to be imported by an alias, otherwise it can be imported directly:

# module called apis actually, but here the file name is API, so you need to solve the import through the alias m_api "code. Kubemaster. Top/DevOpsTeam/API"Copy the code

When it’s time to run and build main.go:

go get -insecure code.kubemaster.top/DevOpsTeam/apis
go run main.goCopy the code

Here basically is to use the basis of defining the go mod, then we will submit code to warehouse: https://code.kubemaster.top/DevOpsTeam/goci.git.

3. How should you build the Go program

Use Docker to build an image, first need to prepare a Dockerfile, think carefully, Go written program will be directly compiled into the specified compilation architecture binary file, so we can build in the Go environment first through the way of layered construction, and then copy the built binary file into a tiny image. To reduce the size of the image, here is a Dockerfile example:

The FROM golang: 1.14 as builder WORKDIR/go/SRC/code. Kubemaster. Top/DevOpsTeam/demos/ARG ARCH = "amd64 ARG OS =" Linux "COPY" main.go . RUN go get -insecure code.kubemaster.top/DevOpsTeam/apis && \ CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main . FROM alpine:latest WORKDIR /root/ COPY --from=builder /go/src/code.kubemaster.top/DevOpsTeam/demos/ . CMD [ "./main" ]Copy the code

After the image is compiled, the image is 7.69m in size. After the Dockerfile is ready, we commit the Dockerfile to goCI’s repository. Now we can configure Jenkinsfile so that we can continue building

4. Continuous build through Jenkinsfile

Here is a simple script pipeline to achieve continuous construction of services, very simple, but also a complete basic framework:

pipeline {
  agent any
  environment {
    registry = "registry-vpc.cn-beijing.aliyuncs.com/kubemaster/gocodecitestdemo"
    registryCredential = '854bfe2f-7923-48a5-9156-7be54cc38a88'
  }
  stages {
    stage('Cloning Git') {
      steps {
        git 'https://code.kubemaster.top/DevOpsTeam/goci.git'
      }
    }
    stage('Building image') {
      steps{
        script {
          dockerImage = docker.build registry + ":$BUILD_NUMBER"
        }
      }
    }
    stage('Testing Image'){
      steps{
        sh "docker run --rm $registry:$BUILD_NUMBER"
      }
    }
    stage('Deploy Image') {
      steps{
        script {
          docker.withRegistry('https://registry-vpc.cn-beijing.aliyuncs.com', registryCredential ) {
            dockerImage.push()
          }
        }
      }
    }
    stage('Remove Unused docker image') {
      steps{
        sh "docker rmi $registry:$BUILD_NUMBER"
      }
    }
  }
}Copy the code

After completing the preparation of Jenkinsfile, it is still submitted to the GoCI code repository, and then we can configure it on Jenkins. Firstly, prepare the XML configuration file goci.xml of Jenkins job configuration:

<? The XML version = '1.1' encoding = "utf-8"? > < flow - definition plugin = "[email protected]" > < actions > < org. Jenkinsci. Plugins. Pipeline. Modeldefinition. Actions. DeclarativeJobAction plugin = "[email protected]" / > <org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobPropertyTrackerAction Plugin ="[email protected]"> <jobProperties/> <triggers/> <parameters/> <options/> </org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobPropertyTrackerAction> </actions> <description></description> <keepDependencies>false</keepDependencies> <properties> < com. Dabsquared. Gitlabjenkins. Connection. GitLabConnectionProperty plugin = "[email protected]" > <gitLabConnection></gitLabConnection> </com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty> < org. Jenkinsci. Plugins. Gitlablogo. GitlabLogoProperty plugin = "[email protected]" > < repositoryName > < / repositoryName > </org.jenkinsci.plugins.gitlablogo.GitlabLogoProperty> < com. Synopsys. Arc. Jenkinsci. Plugins. Jobrestrictions. Jobs. JobRestrictionProperty plugin = "[email protected]" / > < / properties > < definition class = "org. Jenkinsci. Plugins. Workflow. CPS. CpsScmFlowDefinition" plugin = "[email protected]" > < SCM class = "Hudson. Plugins. Git. GitSCM" plugin = "[email protected]" > < configVersion > 2 < / configVersion > < userRemoteConfigs > <hudson.plugins.git.UserRemoteConfig> <url>https://code.kubemaster.top/DevOpsTeam/goci.git</url> <credentialsId>73a21ee2-2cdb-4658-8f99-309a3b77f2d4</credentialsId> </hudson.plugins.git.UserRemoteConfig> </userRemoteConfigs> <branches> <hudson.plugins.git.BranchSpec> <name>*/master</name> </hudson.plugins.git.BranchSpec> </branches> <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations> <submoduleCfg class="list"/> <extensions/> </scm> <scriptPath>Jenkinsfile</scriptPath> <lightweight>true</lightweight> </definition> <triggers/> <disabled>false</disabled>Copy the code

We can then create the build job and perform the trigger build:

# for Jenkins - crumb crumb = $(curl -u "admin: admin" -s "http://jenkins.kubemaster.top/crumbIssuer/api/xml? Xpath =concat(//crumbRequestField,":",//crumb)') # Create job curl "http://admin:[email protected]/createItem? name=goci" --data-binary "@goci.xml" -H "Content-Type: Text/XML "-h ${jenkins_crumb} # run job curl -x POST -u admin:admin -h ${jenkins_crumb} http://jenkins.kubemaster.top/job/goci/buildCopy the code

This is basically the end of the Demo. We have basically finished writing the Demo in practice, containerizing the build, and continuing to build related parts. Let’s look at the results of the build:

Log of completed builds:

This article is published by OpenWrite, a blogging tool platform