使用go来实现一个简单的增删改查接口

最近在学习go,发现go自带的http包很强大,可以通过简单的代码实现数据的增删改查,遂进行一下练习,代码如下:

package main

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

type goods struct {
	Name  string  `json:"name"`
	Price float64 `json:"price"`
}

type rack []goods

func (r *rack) ToJson(resp http.ResponseWriter, req *http.Request) {
	b, err := json.Marshal(*r)
	if err != nil {
		fmt.Fprintf(resp, "%s", err)
		return
	}
	resp.Header().Set("Content-Type", "application/json;charset=utf-8")
	fmt.Fprintf(resp, "%s", b)
}

func (r *rack) list(resp http.ResponseWriter, req *http.Request) {
	r.ToJson(resp, req)
}

func (r *rack) add(resp http.ResponseWriter, req *http.Request) {
	name := req.FormValue("name")
	price, err := strconv.ParseFloat(req.FormValue("price"), 64)
	if err != nil {
		fmt.Fprintf(resp, "解析价格错误!")
		return
	}
	for _, goods := range *r {
		if goods.Name == name {
			fmt.Fprintf(resp, "%s商品已经存在!", name)
			return
		}
	}
	*r = append(*r, goods{name, price})
	r.ToJson(resp, req)
}

func (r *rack) del(resp http.ResponseWriter, req *http.Request) {
	name := req.FormValue("name")
	for index, goods := range *r {
		if goods.Name == name {
			// 删除对应名字的商品
			*r = append((*r)[:index], (*r)[index+1:]...)
			r.ToJson(resp, req)
			return
		}
	}
	fmt.Fprintf(resp, "%s商品不存在!", name)
}

func (r *rack) update(resp http.ResponseWriter, req *http.Request) {
	name := req.FormValue("name")
	price, err := strconv.ParseFloat(req.FormValue("price"), 64)
	if err != nil {
		fmt.Fprintf(resp, "解析价格错误!")
		return
	}
	for index, goods := range *r {
		if goods.Name == name {
			(*r)[index].Price = price
			r.ToJson(resp, req)
			return
		}
	}
	fmt.Fprintf(resp, "%s商品不存在!", name)
}

func main() {
	var r rack = []goods{
		{"图书", 120},
		{"香烟", 75},
	}
	http.HandleFunc("/list", r.list)
	http.HandleFunc("/add", r.add)
	http.HandleFunc("/del", r.del)
	http.HandleFunc("/update", r.update)
	http.ListenAndServe(":8080", nil)
}

posted @ 2023-06-07 16:44  理性黄昏  阅读(44)  评论(0)    收藏  举报