preface

I recently had a requirement at work that I needed to mock an HTTP service that returned a specific JSON because a service was only deployed in production and there were no related services in the test environment, but production services were not locally accessible.

Service code

The code has been uploaded to GitHub:https://github.com/bodhiye/http-fake

The main. The go code

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type fakeReq struct {
	URI string `json:"uri"`
}

// Handle application/ JSON POST requests
func fake(w http.ResponseWriter, r *http.Request) {
	Create a JSON parser instance based on the request body
	decoder := json.NewDecoder(r.Body)
	// Store parameter data
	var req fakeReq
	// Parse parameters into map
    decoder.Decode(&req)
    // Prints logs
	fmt.Printf("url=%s\n", req.URI)

    {"code": 200}
	fmt.Fprintf(w, `{"code": 200}`)}func main(a) {
	http.HandleFunc("/fake", fake)
	http.ListenAndServe(": 2333".nil)}Copy the code

Dockerfile code

FROM golang:latest
MAINTAINER "[email protected]"
WORKDIR /go/src/http-fake
ADD . /go/src/http-fake
RUN go build .
EXPOSE 2333
ENTRYPOINT ["./http-fake"]
Copy the code

Deployment process

  1. Dockerfile:docker build -t bodhiye/http-fake .After compiling, enter it on the terminaldocker imagesYou can view the compiled HTTP-FAKE image.
  2. You need to register for a Docker Hub account and log in to Docker Hub:docker login -u bodhiyeThen enter the password to log in successfully.
  3. Upload image to Docker Hub:docker push bodhiye/http-fakeYou can see the http-fake image on Docker Hub after it is uploaded successfully.
  4. Pull images from the server or local environment where you want to deploy them:docker pull bodhiye/http-fake:latest“Latest” in the code indicates that the latest image version is pulled.
  5. Start the HTTP-fake service:docker run --name test-http -d -p 2048:2333 bodhiye/http-fakeMap port 2333 inside the container service to port 2048 on the native, and give the container service a my-test-HTTP name.
  6. Testing http-fake service:The curl -x POST - d '{" uri ":" https://img.yeqiongzhou.com/test.jpg "}' 127.0.0.1:2048 / fakeCurl curl curl curl curl curl curl curl curl curl curl curl curl curl curl curl curl curl curl curl curl curl To access the service on the server locally, replace 127.0.0.1 with the IP address of the server.
  7. View logs:docker logs test-httpYou can print service logsurl=https://img.yeqiongzhou.com/test.jpg