go restful 安全_Go语言实现复杂Restful Api

章节

程序运行结果

什么是Restful Api?

go 实现复杂 Restful Api

感想

0.程序运行结果

程序运行结果

1.什么是Restful Api

2. go 实现复杂 Restful Api

2.1 go http server 端代码 httpServer.go 实现

package restApi

import (

"fmt"

"github.com/gorilla/mux"

"html"

"net/http"

)

func fooHandler(w http.ResponseWriter, r *http.Request) {

fmt.Fprintf(w, "hello,%q", html.EscapeString(r.URL.Path))

}

func doGetApiParam(w http.ResponseWriter, r *http.Request) {

vars := mux.Vars(r)

toDoId := vars["toDoId"]

fmt.Fprintf(w, "toDoId is: "+toDoId)

}

//开启http服务器

func FooHandler() {

router := mux.NewRouter().StrictSlash(true)

router.HandleFunc("/foo", fooHandler)

router.HandleFunc("/hello", fooHandler)

router.HandleFunc("/todo/{toDoId}", doGetApiParam)

//返回 api json 数据

router.HandleFunc("/users", restApiHandler)

//返回 productsList 数据

router.HandleFunc("/productsList", productsList)

//开启http服务,并引入路由管理器

http.ListenAndServe(":8082", router)

}

2.2 复杂 Api handler 端代码 complexApi.go 实现

package restApi

import (

"encoding/json"

"net/http"

)

/**

1.需求

编写返回商品列表数据的Api,返回数据对应的 struct (go 中struct为值类型)如下所示

*/

//定义接口返回的核心数据 如商品详情信息

type ProductInfo struct {

Name string `json:"name"` //商品名称

Des string `json:"des"` //商品信息描述

UseMethod string `json:"useMethod"` //使用方法

UseRange string `json:"useRange"` //使用范围

ValidDate string `json:"validDate"` //有效期

RpbStatement string `json:"rpbStatement"` //权责声明

}

type Data struct {

ProductsInfo []ProductInfo `json:"productsInfo"`

}

//定义接口返回的data数据

type ApiData struct {

//[结构体变量名 | 变量类型 | json 数据 对应字段名]

ErrCode int `json:"errCode"` //接口响应状态码

Msg string `json:"msg"` //接口响应信息

Data Data `json:"data"`

}

//请求路由(映射)至 productsList() handler

func productsList(w http.ResponseWriter, r *http.Request) {

//1.接口状态码

errorCode := 0

//2.接口返回信息

msg := "get products list success!"

product1 := ProductInfo{

"柿饼",

"来自陕西富平的特产",

"开箱即食",

"全国",

"2018-10-20 至 2018-12-31",

"与xx公司无关",

}

product2 := ProductInfo{

"金枪鱼",

"来自深海的美味",

"红烧、清蒸均可",

"全国",

"2018-10-20 至 2018-12-31",

"与xx公司无关",

}

product3 := ProductInfo{

"鲶鱼",

"来自淡水的美味",

"红烧、清蒸均可",

"全国",

"2018-10-20 至 2018-12-31",

"与xx公司无关",

}

//3.省略对应 DB(关系、非关系、搜索引擎) 操作,以 hard code 代替

data := Data{[]ProductInfo{product1, product2, product3}}

//4.组装接口返回的数据

apiData := ApiData{errorCode, msg, data}

//5.接口响应复杂json数据

json.NewEncoder(w).Encode(apiData)

}

感想

简单的东西需要记录,刻意练习才能保持精进!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值