go webapi
创建数据库
/*
Navicat Premium Data Transfer
Source Server : 本地
Source Server Type : MySQL
Source Server Version : 80022
Source Host : localhost:3306
Source Schema : book
Target Server Type : MySQL
Target Server Version : 80022
File Encoding : 65001
Date: 20/02/2021 16:51:59
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for order_items
-- ----------------------------
DROP TABLE IF EXISTS `order_items`;
CREATE TABLE `order_items` (
`id` int(0) NOT NULL,
`count` int(0) NULL DEFAULT NULL,
`amount` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`author` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`price` decimal(10, 2) NULL DEFAULT NULL,
`img_path` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`order_id` int(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of order_items
-- ----------------------------
INSERT INTO `order_items` VALUES (2, 3, '5', '白白', '小宝宝', 5.00, 'imgpath', 7);
SET FOREIGN_KEY_CHECKS = 1;
**
golang代码附上
**
package main
import (
"database/sql"
"fmt"
"net/http"
"encoding/json"
_ "github.com/go-sql-driver/mysql"
)
var (
Db *sql.DB
err error
)
func init() {
Db, err = sql.Open("mysql","root:123456@tcp(localhost:3306)/book?utf8mb4");
if err != nil {
panic(err.Error())
}
}
type OrderItem struct {
OrderItemID int64
Count int64
Amount float64
Title string
Author string
Price float64
ImgPath string
OrderID string
}
func GetOrderItemsByOrderID(orderID string) ([]*OrderItem, error) {
//写sql语句
sql := "select id,count,amount,title,author,price,img_path,order_id from order_items where order_id = ?"
//执行
rows, err := Db.Query(sql, orderID)
if err != nil {
return nil, err
}
var orderItems []*OrderItem
for rows.Next() {
orderItem := &OrderItem{}
rows.Scan(&orderItem.OrderItemID, &orderItem.Count, &orderItem.Amount, &orderItem.Title, &orderItem.Author, &orderItem.Price, &orderItem.ImgPath, &orderItem.OrderID)
//添加到切片中
orderItems = append(orderItems, orderItem)
}
return orderItems, nil
}
func GetDetailGoods(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
gidStr := r.Form.Get("order_id")
respStr := "{}"
if gidStr != ""{
goods,_ := GetOrderItemsByOrderID(gidStr)
jsons, errs := json.Marshal(goods)
if errs == nil {
respStr = string(jsons)
}
}
fmt.Fprint(w, respStr)
}
func main() {
http.HandleFunc("/api", GetDetailGoods)
http.ListenAndServe(":8080", nil)
}