概述
如果您没有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 main
import (
"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 main
import (
"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"] = "李四"
// 将字段转换为JSON
jsonBytes, 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 main
import (
"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 main
import (
"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, "王五")
// 将字段转换为JSON
jsonBytes, 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 main
import (
"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 main
import (
"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}
// 将字段转换为JSON
jsonBytes, 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 main
import (
"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 main
import (
"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}
// 将字段转换为JSON
jsonBytes, 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 main
import (
"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 main
import (
"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 main
import (
"fmt"
"io"
"net/http"
)
func main() {
resp, err := http.Get("http://localhost:8888/")
if err != nil {
fmt.Println(err)
return
}
body := resp.Body
bodyBytes, err := io.ReadAll(body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(bodyBytes))
}
15 获取查询参数
package main
import (
"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 main
import (
"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.Body
bodyBytes, err := io.ReadAll(body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(bodyBytes))
}
16 封装GetQuery和GetQueryInt方法
17 获取查询参数的方式
package main
import (
"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 main
import (
"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.Body
bodyBytes, err := io.ReadAll(body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(bodyBytes))
}
18 发送和获取表单参数
package main
import (
"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 main
import (
"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 error
log.Fatal("生成请求失败!", err)
return
}
//注意别忘了设置header
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// Do方法发送请求
resp, err := client.Do(req)
body2 := resp.Body
bodyBytes, err := io.ReadAll(body2)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(bodyBytes))
}
19 封装GetForm方法
package main
import (
"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 main
import (
"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 error
log.Fatal("生成请求失败!", err)
return
}
//注意别忘了设置header
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// Do方法发送请求
resp, err := client.Do(req)
body2 := resp.Body
bodyBytes, err := io.ReadAll(body2)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(bodyBytes))
}
20 封装SendForm方法
package main
import (
"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 main
import (
"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.Body
bodyBytes, err := io.ReadAll(body2)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(bodyBytes))
}
21 发送和获取JSON
package main
import (
"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 User
err := 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 main
import (
"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.Body
bodyBytes, err := io.ReadAll(body2)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(bodyBytes))
}
22 获取路径参数
package main
import (
"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 main
import (
"fmt"
"io"
"net/http"
)
func main() {
targetUrl := "http://localhost:8888/3"
resp, err := http.Get(targetUrl)
body2 := resp.Body
bodyBytes, err := io.ReadAll(body2)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(bodyBytes))
}
23 发送PUT请求
package main
import (
"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 User
err := 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 main
import (
"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.Body
bodyBytes, err := io.ReadAll(body2)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(bodyBytes))
}
24 发送DELETE请求
package main
import (
"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 User
err := 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 main
import (
"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.Body
bodyBytes, 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私教~
标签:02,http,err,zdpgo,REST,20240728,httprouter,router,main From: https://blog.csdn.net/qq_37703224/article/details/140768205