使用 net/http
标准库创建一个 http
的 restful api
的服务端,用来处理 GET
、POST
等请求。
源代码如下:
package mainimport ("encoding/json""fmt""net""net/http""strconv""time"
)type Contact struct {Home string `json:"home"`Cell string `json:"cell"`
}type Student struct {Name string `json:"name"`Year string `json:"year"`Contact Contact `json:"contact"`
}// 任务的HTTP接口
type ApiServer struct {httpServer *http.Server
}// HTTP接口应答
type Response struct {Errno int `json:"errno"`Msg string `json:"msg"`Data interface{} `json:"data"`
}// 构造一个响应
func BuildResponse(errno int, msg string, data interface{}) ([]byte, error) {// 1, 定义一个responseresponse := &Response{Errno: errno,Msg: msg,Data: data,}// 2, 序列化jsonresp, err := json.Marshal(response)return resp, err
}func saveFunction(resp http.ResponseWriter, req *http.Request) {// 1, 解析 POST 表单err := req.ParseForm()if err != nil {fmt.Printf("ParseForm error: %s\n", err)}// 获取表单中所有字段内容fmt.Printf("req.PostForm is %v", req.PostForm)// 2, 取表单中的 name 字段name := req.PostForm.Get("name")fmt.Printf("name: %s\n", name)contactInfo := req.PostForm.Get("contact")fmt.Printf("contactInfo: %s\n", contactInfo)// 3, 反序列化jobvar contact Contacterr = json.Unmarshal([]byte(contactInfo), &contact)fmt.Printf("contact: %s\n", contact)if err != nil {fmt.Printf("Unmarshal error: %s\n", err)}// 4, 保存到数据库// saveToDB()// 5, 返回正常应答 ({"errno": 0, "msg": "", "data": {....}})bytes, err := BuildResponse(0, "success", contact)if err == nil {resp.Write(bytes)}
}func listFunction(resp http.ResponseWriter, req *http.Request) {// 1. 解析GET参数err := req.ParseForm()if err != nil {fmt.Printf("ParseForm error: %s\n", err)}// 2. 获取请求参数 /api/list?name=wohuname := req.Form.Get("name")fmt.Printf("name: %s\n", name)// 3. 从数据库中读取对应的字段值后显示// ret := queryDB()// 4. 返回正常应答 ({"errno": 0, "msg": "", "data": {....}})bytes, err := BuildResponse(0, "success", name)if err == nil {resp.Write(bytes)}
}// 初始化服务
func InitApiServer() (err error) {// 配置路由mux := http.NewServeMux()mux.HandleFunc("/api/save", saveFunction)// mux.HandleFunc("/api/del", delFunction)// mux.HandleFunc("/api/update", updateFunction)mux.HandleFunc("/api/list", listFunction)// 启动TCP监听listener, err := net.Listen("tcp", ":"+strconv.Itoa(8070))if err != nil {return}// 创建一个HTTP服务httpServer := &http.Server{ReadTimeout: 100 * time.Millisecond,WriteTimeout: 100 * time.Millisecond,Handler: mux,}// 启动了服务端go httpServer.Serve(listener)return
}func main() {InitApiServer()// 正常退出for {time.Sleep(1 * time.Second)}
}
然后使用 Postman
工具发送 GET
、POST
请求: