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
- Dockerfile:
docker build -t bodhiye/http-fake .
After compiling, enter it on the terminaldocker images
You can view the compiled HTTP-FAKE image. - You need to register for a Docker Hub account and log in to Docker Hub:
docker login -u bodhiye
Then enter the password to log in successfully. - Upload image to Docker Hub:
docker push bodhiye/http-fake
You can see the http-fake image on Docker Hub after it is uploaded successfully. - 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. - Start the HTTP-fake service:
docker run --name test-http -d -p 2048:2333 bodhiye/http-fake
Map port 2333 inside the container service to port 2048 on the native, and give the container service a my-test-HTTP name. - Testing http-fake service:
The curl -x POST - d '{" uri ":" https://img.yeqiongzhou.com/test.jpg "}' 127.0.0.1:2048 / fake
Curl 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. - View logs:
docker logs test-http
You can print service logsurl=https://img.yeqiongzhou.com/test.jpg