当前位置:网站首页>Go Xiaobai implements a simple go mock server
Go Xiaobai implements a simple go mock server
2022-07-24 18:34:00 【InfoQ】
Preface
Purpose
Code
step 1
// Get current json The path where the file is located already has the file name , And then we'll do the stitching
func ParsePath() (path string, err error) {
pwd, _ := os.Getwd()
fileList, err := ioutil.ReadDir(pwd)
if err != nil {
log.Fatal(err)
}
var curJsonFile string
for _, v := range fileList {
name := v.Name()
if isJson := strings.Contains(name, "json"); isJson {
curJsonFile = name
}
}
if curJsonFile == "" {
return curJsonFile, errors.New("dont have json file")
}
absPath := pwd + "/" + curJsonFile
return absPath, nil
}step 2
// Read the specific... According to the passed in file name []byte data
func ReadJSON(path string) ([]byte, error) {
jsonFile, err := os.Open(path)
if err != nil {
log.Fatal("open file err")
}
defer jsonFile.Close()
byteValue, err := ioutil.ReadAll(jsonFile)
if err != nil {
return nil, err
}
return byteValue, nil
}step 3
// Based on the incoming []byte data , Deserialize the data conversion to map type
// Because I don't know json Specific data of the document , Specific structure , So use the map[string]interface{} Of
// data type
func DecodeJSONString(jsonBytes []byte) (map[string]interface{}, error) {
var m map[string]interface{}
err := json.Unmarshal(jsonBytes, &m)
if err != nil {
log.Fatal("json unmarshal fail", err)
return nil, err
}
return m, nil
}var data map[string]interface{}
func returnResponse(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
path := r.URL.Path
if d := data[path]; d != nil {
stringData, err := json.Marshal(data[path])
if err != nil {
log.Fatal(err)
}
w.Write(stringData)
}
}
func main() {
path, err := src.ParsePath()
if err != nil {
log.Fatal(err)
}
bytes, err := src.ReadJSON(path)
if err != nil {
log.Fatal(err)
}
m, err := src.DecodeJSONString(bytes)
data = m
if err != nil {
log.Fatal("decode fail: ", err)
}
for addr, _ := range data {
http.HandleFunc(addr, returnResponse)
}
err = http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatal("listenAndServer fail")
}
}Final effect
localhost:3000/v1/lottery
{
"/v1/lottery": [{
"name": "shinji",
"age": 20
}, {
"name": "ayanami",
"age": 20
}]
}Last
边栏推荐
- Array object methods commonly used traversal methods & higher-order functions
- redis 数据类型
- Getaverse,走向Web3的远方桥梁
- Four ways of simple interest mode
- Highcharts chart and report display, export data
- The collapse of margin
- ["code" power is fully open, and "chapter" shows strength] list of contributors to the task challenge in the first quarter of 2022
- JMeter -- silent operation
- [record of question brushing] 20. Valid brackets
- 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
猜你喜欢

Number of times a number appears in an ascending array

Leetcode memory deep search / dynamic planning V2

Maximum sum and promotion of continuous subarrays (2)

QT - animation frame

Data analysis of network security competition of national vocational college skills competition digital forensics-a

Escape character in JS?

Typora is still the most beautiful and beautiful document editing artifact of yyds in my heart. I believe you will never abandon it

Ionic4 Learning Notes 6 -- using native ionic4 components in custom components

Mid year inventory | in 2022, PAAS will be upgraded again

EasyUI framework dialog repeated loading problem
随机推荐
Variable and immutable data types
ES6 cycle filter value
Space three point circle code
Ionic4 learning notes 8 -- UI component 2 list (no practice, direct excerpt)
树链剖分板子
Pytoch's journey 1: linear model
Pytoch's Journey 2: gradient descent
04 distributed resource management system yarn
使用der格式公钥生成publicKey报错
Template inheritance and import
Leetcode memory deep search / dynamic planning V2
Getting started with MySQL database
Missing value processing
Pycharm configuring opencv Library
Windowing function (1) - top three employees of department salary
L4L7负载均衡
National vocational college skills competition network security competition -- detailed explanation of Apache security configuration
jmeter -- prometheus+grafana服务器性能可视化
Ionic4 Learning Notes 6 -- using native ionic4 components in custom components
Mysql——》数据类型隐式转换