02 Go语言开发REST API接口_20240728 课程笔记

news/2024/12/27 11:06:31/

概述

如果您没有Golang的基础,应该学习如下前置课程。

  • Golang零基础入门
  • Golang面向对象编程
  • Go Web 基础

基础不好的同学每节课的代码最好配合视频进行阅读和学习,如果基础比较扎实,则阅读本教程巩固一下相关知识点即可,遇到不会的知识点再看视频。

视频课程

最近发现越来越多的公司在用Golang了,所以精心整理了一套视频教程给大家,这个是其中的第4部,后续还会有很多。

视频已经录制完成,完整目录截图如下:
在这里插入图片描述

打个小广告,目前处于特价阶段,一节课只需要1块钱,24节课只需要24元哦。如果有需要,请前往我的淘宝店铺“Python私教”下单。

课程目录

  • 01 环境搭建
  • 02 关于年月日版本不被支持的说明
  • 03 返回JSON字典
  • 04 Go语言通过replace查找本地库的用法
  • 05 封装JsonMap方法
  • 06 使用封装的JsonMap方法
  • 07 优化JsonMap方法
  • 08 返回JSON数组
  • 09 封装ResponseJsonArr方法
  • 10 返回JSON结构体
  • 11 封装ResponseJsonStruct方法
  • 12 统一返回格式
  • 13 封装ResponseSuccess方法
  • 14 发送GET请求
  • 15 获取查询参数
  • 16 封装GetQuery和GetQueryInt方法
  • 17 获取获取查询参数的方式
  • 18 发送和获取表单参数
  • 19 封装GetForm方法
  • 20 封装SendForm方法
  • 21 发送和获取JSON
  • 22 获取路径参数
  • 23 发送PUT请求
  • 24 发送DELETE请求

完整代码

01 环境搭建

package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {fmt.Fprint(w, "Welcome!\n")
}func main() {router := zdpgo_httprouter.New()router.GET("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}

02 关于年月日版本不被支持的说明

03 返回JSON字典

package mainimport ("encoding/json""fmt""github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {// 声明返回的是JSON数据w.Header().Set("Content-Type", "application/json")m := make(map[string]string)m["a"] = "张三"m["b"] = "李四"// 将字段转换为JSONjsonBytes, err := json.Marshal(m)if err != nil {fmt.Println(err)fmt.Fprintf(w, err.Error())return}fmt.Fprint(w, string(jsonBytes))
}func main() {router := zdpgo_httprouter.New()router.GET("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}

04 Go语言通过replace查找本地库的用法

05 封装JsonMap方法

06 使用封装的JsonMap方法

package mainimport ("github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {m := make(map[string]interface{})m["a"] = "张三333"m["b"] = "李四333"zdpgo_httprouter.ResponseJsonMap(w, m)
}func main() {router := zdpgo_httprouter.New()router.GET("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}

07 优化JsonMap方法

08 返回JSON数组

package mainimport ("encoding/json""fmt""github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {// 声明返回的是JSON数据w.Header().Set("Content-Type", "application/json")var arr []interface{}arr = append(arr, "张三")arr = append(arr, "李四")arr = append(arr, "王五")// 将字段转换为JSONjsonBytes, err := json.Marshal(arr)if err != nil {fmt.Fprintf(w, err.Error())return}// 返回JSON信息fmt.Fprint(w, string(jsonBytes))
}func main() {router := zdpgo_httprouter.New()router.GET("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}

09 封装ResponseJsonArr方法

package mainimport ("github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {var arr []interface{}arr = append(arr, "张三333")arr = append(arr, "李四333")arr = append(arr, "王五333")zdpgo_httprouter.ResponseJsonArr(w, arr)
}func main() {router := zdpgo_httprouter.New()router.GET("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}

10 返回JSON结构体

package mainimport ("encoding/json""fmt""github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)type User struct {Name string `json:"name"`Age  int    `json:"age"`
}func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {// 声明返回的是JSON数据w.Header().Set("Content-Type", "application/json")u := User{"张三", 33}// 将字段转换为JSONjsonBytes, err := json.Marshal(u)if err != nil {fmt.Fprintf(w, err.Error())return}// 返回JSON信息fmt.Fprint(w, string(jsonBytes))
}func main() {router := zdpgo_httprouter.New()router.GET("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}

11 封装ResponseJsonStruct方法

package mainimport ("github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)type User struct {Name string `json:"name"`Age  int    `json:"age"`
}func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {u := User{"张三333", 333}zdpgo_httprouter.ResponseJsonStruct(w, u)
}func main() {router := zdpgo_httprouter.New()router.GET("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}

12 统一返回格式

package mainimport ("encoding/json""fmt""github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)type SuccessResult struct {Code    int         `json:"code"`Status  bool        `json:"status"`Message string      `json:"message"`Data    interface{} `json:"data,omitempty"`
}type User struct {Name string `json:"name"`Age  int    `json:"age"`
}func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {// 声明返回的是JSON数据w.Header().Set("Content-Type", "application/json")u := User{"张三", 33}s := SuccessResult{10000, true, "success", u}// 将字段转换为JSONjsonBytes, err := json.Marshal(s)if err != nil {fmt.Fprintf(w, err.Error())return}// 返回JSON信息fmt.Fprint(w, string(jsonBytes))
}func main() {router := zdpgo_httprouter.New()router.GET("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}

13 封装ResponseSuccess方法

package mainimport ("github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)type User struct {Name string `json:"name"`Age  int    `json:"age"`
}func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {u := User{"张三333", 333}zdpgo_httprouter.ResponseSuccess(w, u)
}func main() {router := zdpgo_httprouter.New()router.GET("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}

14 发送GET请求

package mainimport ("github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)type User struct {Name string `json:"name"`Age  int    `json:"age"`
}func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {u := User{"张三333", 333}zdpgo_httprouter.ResponseSuccess(w, u)
}func main() {router := zdpgo_httprouter.New()router.GET("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""io""net/http"
)func main() {resp, err := http.Get("http://localhost:8888/")if err != nil {fmt.Println(err)return}body := resp.BodybodyBytes, err := io.ReadAll(body)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}

15 获取查询参数

package mainimport ("github.com/zhangdapeng520/zdpgo_httprouter""net/http""strconv""time"
)type User struct {Name string `json:"name"`Age  int    `json:"age"`
}func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {name := r.URL.Query().Get("name")age := r.URL.Query().Get("age")ageInt, _ := strconv.ParseInt(age, 10, 64)u := User{name, int(ageInt)}zdpgo_httprouter.ResponseSuccess(w, u)
}func main() {router := zdpgo_httprouter.New()router.GET("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""io""net/http"
)func main() {resp, err := http.Get("http://localhost:8888/?name=张三333&age=33")if err != nil {fmt.Println(err)return}body := resp.BodybodyBytes, err := io.ReadAll(body)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}

16 封装GetQuery和GetQueryInt方法

17 获取查询参数的方式

package mainimport ("github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)type User struct {Name string `json:"name"`Age  int    `json:"age"`
}func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {name := zdpgo_httprouter.GetQuery(r, "name")age := zdpgo_httprouter.GetQueryInt(r, "age")u := User{name, age}zdpgo_httprouter.ResponseSuccess(w, u)
}func main() {router := zdpgo_httprouter.New()router.GET("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""io""net/http"
)func main() {resp, err := http.Get("http://localhost:8888/?name=张三33&age=33")if err != nil {fmt.Println(err)return}body := resp.BodybodyBytes, err := io.ReadAll(body)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}

18 发送和获取表单参数

package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_httprouter""net/http""strconv""time"
)type User struct {Name string `json:"name"`Age  int    `json:"age"`
}func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {r.ParseForm()fmt.Println(r.PostForm)name := r.PostForm.Get("name")age := r.PostForm.Get("age")ageInt, _ := strconv.ParseInt(age, 10, 64)u := User{name, int(ageInt)}zdpgo_httprouter.ResponseSuccess(w, u)
}func main() {router := zdpgo_httprouter.New()router.POST("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("bytes""fmt""io""log""net/http""net/url"
)func main() {targetUrl := "http://localhost:8888/"// 用url.values方式构造form-data参数formValues := url.Values{}formValues.Set("name", "张三")formValues.Set("age", "23")formDataStr := formValues.Encode()formDataBytes := []byte(formDataStr)formBytesReader := bytes.NewReader(formDataBytes)//生成post请求client := &http.Client{}req, err := http.NewRequest("POST", targetUrl, formBytesReader)if err != nil {// handle errorlog.Fatal("生成请求失败!", err)return}//注意别忘了设置headerreq.Header.Set("Content-Type", "application/x-www-form-urlencoded")// Do方法发送请求resp, err := client.Do(req)body2 := resp.BodybodyBytes, err := io.ReadAll(body2)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}

19 封装GetForm方法

package mainimport ("github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)type User struct {Name string `json:"name"`Age  int    `json:"age"`
}func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {name := zdpgo_httprouter.GetForm(r, "name")age := zdpgo_httprouter.GetFormInt(r, "age")u := User{name, age}zdpgo_httprouter.ResponseSuccess(w, u)
}func main() {router := zdpgo_httprouter.New()router.POST("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("bytes""fmt""io""log""net/http""net/url"
)func main() {targetUrl := "http://localhost:8888/"// 用url.values方式构造form-data参数formValues := url.Values{}formValues.Set("name", "张三")formValues.Set("age", "23")formDataStr := formValues.Encode()formDataBytes := []byte(formDataStr)formBytesReader := bytes.NewReader(formDataBytes)//生成post请求client := &http.Client{}req, err := http.NewRequest("POST", targetUrl, formBytesReader)if err != nil {// handle errorlog.Fatal("生成请求失败!", err)return}//注意别忘了设置headerreq.Header.Set("Content-Type", "application/x-www-form-urlencoded")// Do方法发送请求resp, err := client.Do(req)body2 := resp.BodybodyBytes, err := io.ReadAll(body2)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}

20 封装SendForm方法

package mainimport ("github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)type User struct {Name string `json:"name"`Age  int    `json:"age"`
}func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {name := zdpgo_httprouter.GetForm(r, "name")age := zdpgo_httprouter.GetFormInt(r, "age")u := User{name, age}zdpgo_httprouter.ResponseSuccess(w, u)
}func main() {router := zdpgo_httprouter.New()router.POST("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_httprouter""io"
)func main() {targetUrl := "http://localhost:8888/"formData := map[string]string{"name": "张三","age":  "23",}resp, err := zdpgo_httprouter.SendForm(targetUrl, formData)body2 := resp.BodybodyBytes, err := io.ReadAll(body2)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}

21 发送和获取JSON

package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)type User struct {Name string `json:"name"`Age  int    `json:"age"`
}func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {var u Usererr := zdpgo_httprouter.GetJson(r, &u)if err != nil {fmt.Fprintf(w, "err:%v", err)return}zdpgo_httprouter.ResponseSuccess(w, u)
}func main() {router := zdpgo_httprouter.New()router.POST("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_httprouter""io"
)func main() {targetUrl := "http://localhost:8888/"formData := map[string]interface{}{"name": "张三","age":  23,}resp, err := zdpgo_httprouter.SendJson("POST", targetUrl, formData)body2 := resp.BodybodyBytes, err := io.ReadAll(body2)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}

22 获取路径参数

package mainimport ("github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)func Index(w http.ResponseWriter, r *http.Request, ps zdpgo_httprouter.Params) {id := ps.ByName("id")data := map[string]interface{}{"id":   id,"name": "张三","age":  23,}zdpgo_httprouter.ResponseSuccess(w, data)
}func main() {router := zdpgo_httprouter.New()router.GET("/:id", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""io""net/http"
)func main() {targetUrl := "http://localhost:8888/3"resp, err := http.Get(targetUrl)body2 := resp.BodybodyBytes, err := io.ReadAll(body2)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}

23 发送PUT请求

package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)type User struct {Name string `json:"name"`Age  int    `json:"age"`
}func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {var u Usererr := zdpgo_httprouter.GetJson(r, &u)if err != nil {fmt.Fprintf(w, "err:%v", err)return}zdpgo_httprouter.ResponseSuccess(w, u)
}func main() {router := zdpgo_httprouter.New()router.PUT("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_httprouter""io"
)func main() {targetUrl := "http://localhost:8888/"formData := map[string]interface{}{"name": "张三","age":  23,}resp, err := zdpgo_httprouter.SendJson("PUT", targetUrl, formData)body2 := resp.BodybodyBytes, err := io.ReadAll(body2)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}

24 发送DELETE请求

package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_httprouter""net/http""time"
)type User struct {Name string `json:"name"`Age  int    `json:"age"`
}func Index(w http.ResponseWriter, r *http.Request, _ zdpgo_httprouter.Params) {var u Usererr := zdpgo_httprouter.GetJson(r, &u)if err != nil {fmt.Fprintf(w, "err:%v", err)return}zdpgo_httprouter.ResponseSuccess(w, u)
}func main() {router := zdpgo_httprouter.New()router.DELETE("/", Index)server := &http.Server{Addr:         "0.0.0.0:8888",Handler:      router,ReadTimeout:  5 * time.Second,WriteTimeout: 5 * time.Second,}server.ListenAndServe()
}
package mainimport ("fmt""github.com/zhangdapeng520/zdpgo_httprouter""io"
)func main() {targetUrl := "http://localhost:8888/"formData := map[string]interface{}{"name": "张三","age":  23,}resp, err := zdpgo_httprouter.SendJson("DELETE", targetUrl, formData)body2 := resp.BodybodyBytes, err := io.ReadAll(body2)if err != nil {fmt.Println(err)return}fmt.Println(string(bodyBytes))
}

总结

本套教程主要讲解Go REST API开发的基础知识,特别是讲解了httprouter的用法以及一些便捷函数的封装,并附上了完整的实战代码。

通过本套课程,能帮你入门Go REST API 接口开发,写一些简单的API程序。

如果您需要完整的源码,打赏20元即可。

人生苦短,我用Python,我是您身边的Python私教~


http://www.ppmy.cn/news/1503840.html

相关文章

Linux 命令,cat说明与使用

1:grep命令功用: 读一个或多个文件并显示到标准输出上,如果没有指定files或是指定一个文件,则从标准输入读取,输入以EOF结束。可以使用操作符>把几个文件组合为一个新文件,或者是使用>>在已经存在的文件里添加…

PHP安全防护抵御网络钓鱼攻击

本文由 ChatMoney团队出品 随着互联网的飞速发展,网络钓鱼攻击已成为网络安全领域的重要威胁之一。网络钓鱼攻击通过伪装成合法网站或企业,诱骗用户进入虚假网站并窃取用户的个人信息、密码等敏感信息。对于使用PHP框架开发的Web应用来说,加强…

链表的基础基础操作

#include<iostream> #include<iomanip> #include<cmath> #include<cstdio> using namespace std; #define Maxsize 100 #define ElemType int #define Status int typedef long long ll; typedef struct Node {int data;//数据存储struct Node *next…

分布式相关理论详解

目录 1.绪论 2.什么是分布式系统&#xff0c;和集群的区别 3.CAP理论 3.1 什么是CAP理论 3.2 一致性 3.2.1 计算机的一致性说明 1.事务中的一致性 2.并发场景下的一致性 3.分布式场景下的一致性 3.2.2 一致性分类 3.2.3 强一致性 1.线性一致性 a) 定义 a) Raft算法…

python爬虫初识

一、什么互联网 互联网&#xff08;Internet&#xff09;是全球范围内最大的计算机网络&#xff0c;它将数以百万计的私人、公共、学术、商业和政府网络通过一系列标准通信协议&#xff08;如TCP/IP&#xff09;连接起来形成的一个庞大的国际网络。 互联网的起源可以追溯到196…

【2024】InfluxDB v2 介绍和安装使用(1)

目录&#x1f4bb; 一、介绍1、时序数据库介绍特点&#xff1a;常见的时序数据库时序库受欢迎度排名 2、InfluxDB介绍**InfluxDB 1.x 和 2.0 的主要区别**InfluxDB行协议 二、docker安装 InfluxDB v2三. Web UI常用功能介绍以及使用1、页面介绍2、功能使用2.1、创建bucket2.2、…

【Linux 网络】链路层

文章目录 链路层1 以太网1.1 以太网帧格式1.2 MAC地址1.3 MTU 2. ARP协议2.1 ARP协议的作用2.2 ARP数据报格式2.3 ARP的流程 其他协议3. DNS协议3.1 域名3.2 输入URL后的事情 4. ICMP协议4.1 ICMP 功能都有啥&#xff1f;4.2 基于ICMP的命令ping命令 5. NAT协议5.1 NAT技术背景…

Kafka设计与原理详解

RocketMQ 是一款开源的分布式消息系统&#xff0c;基于高可用分布式集群技术&#xff0c;提供低延时的、高可靠的消息发布与订阅服务。同时&#xff0c;广泛应用于多个领域&#xff0c;包括异步通信解耦、企业解决方案、金融支付、电信、电子商务、快递物流、广告营销、社交、即…