跟着b站https://space.bilibili.com/361469957 杨旭老师学习做的笔记

路由

Controller / Router

角色

  • main():设置类工作
  • controller:
    • 静态资源
    • 把不同的请求送到不同的 controller 进行处理

它会根据请求,匹配最具体的 handler

路由参数

静态路由:一个路径对应一个页面

/home

/about

带参数的路由:根据路由参数,创建出一族不同的页面

/companies/123

/companies/Microsoft

-controller ----company.go
----content.go
----controller.go
----home.go company.html
companies.html
content.html
home.html
layout.html
main.go -wwwroot ----css -----style.css
----js -----script.js
----image -----img1.png
// controller.go
package controller func RegisterRoutes(){
registerContentRouts()
registerHomeRouts()
registerCompanyRoutes()
registerStaticResource()
}
func registerStaticResource(){
http.Handle("/css/",http.FileServer(http.Dir("wwwroot")))
http.Handle("/img/",http.FileServer(http.Dir("wwwroot")))
http.Handle("/js/",http.FileServer(http.Dir("wwwroot")))
} //company.go
package controller
import (
"net/http"
"text/template"
"strconv"
"regexp"
)
func registerCompanyRoutes(){
http.HandleFunc("/companies",handleCompanies)
http.HandleFunc("/companies/",handleCompany)
}
func handleCompanies(w http.ResponseWriter, r *http.Request){
t,_ := template.ParseFiles("companies.html")
t.ExecuteTemplate(w,"content",nil)
}
func handleCompany(w http.ResponseWriter, r *http.Request){
pattern ,_ := regexp.Compile(`/companies/(\d+)`)
matches := pattern.FindStringSubmatch(r.URL.Path)
t,_ := template.ParseFiles("company.html")
if len(matches) >0{
companyID ,_ := strconv.Atoi(matches[1])
t.ExecuteTemplate(w,"content",companyID)
}else{
w.WriteHeader(http.StatusNotFound)
}
}
//content.go
package controller
import (
"net/http"
"text/template" )
func registerContentRouts(){
http.HandleFunc("/content", handleContent)
} func handleContent(w http.ResponseWriter, r *http.Request) {
t,_ := template.ParseFiles("content.html","layout.html")
t.ExecuteTemplate(w,"layout","hello world")
}
//home.go
package controller
import (
"net/http"
"text/template"
)
func registerHomeRouts(){
http.HandleFunc("/home", handleHome)
}
func handleHome(w http.ResponseWriter, r *http.Request){
t,_ := template.ParseFiles("home.html")
t.ExecuteTemplate(w,"content","")
}

最小惊讶原则

绑定 handler

/hello ——》 hello

/index ——》 index

/wow/ ——》 wow

则实际操作时

/index ——》 index

/hello/two ——》 index

/wow/two ——》 wow

第三方路由器

gorilla/mux:灵活性高、功能强大、性能相对差一些

httprouter:注重性能、功能简单

web 服务

REST 速度块,构建简单 -》 服务外部和第三方开发者

SOAP 安全并健壮 -》 内部应用的企业集成

【API技术核心原理】REST | GraphQL | gRPC | tRPC

https://www.bilibili.com/video/BV1yL41167fD/?share_source=copy_web&vd_source=03c1dc52eeb3747825ecad0412c18ab1

JSON

JSON 与 Go 的 Struct

{
"id":123,
"name":"CNSA",
"country":"China"
}
type  SpaceAdministration struct{
ID int
Name string
Country string
}

结构标签

对应映射

type  SpaceAdministration struct{
ID int `json:"id"`
Name string `json:"name"`
Country string `json:"country"`
}

类型映射

Go bool:JSON boolean

Go float64:JSON 数值

Go string:JSON strings

Go nil:JSON null.

对于未知结构的 JSON

map[string]interface{} 可以存储任意 JSON 对象

[]interface{} 可以存储任意的 JSON 数组

读取 JSON

  • 需要一个解码器:dec := json.NewDecoder(r.Body)
    • 参数需实现 Reader 接口
  • 在解码器上进行解码:dec.Decode(&query)

写入JSON

需要一个编码器:enc := json.NewEncoder(w)

参数需实现 Writer 接口

编码:enc.Encode(results)

Marshal 和 Unmarshal

Marshal(编码): 把 go struct 转化为 json 格式

MarshalIndent,带缩进

Unmarshal(解码): 把 json 转化为 go struct

两种方式区别

  • 针对 string 或 bytes:

    • Marshal => String
    • Unmarshal <= String
  • 针对 stream:

    • Encode => Stream,把数据写入到 io.Writer
    • Decode <= Stream,从 io.Reader 读取数据
type Company struct{
ID int `json:"id"`
Name string `json:name`
Country string `json:country`
} jsonStr := `{
"id":1213,
"name": "红旗",
"country": "中国"
}`
c := Company{} //返回一个error,这里没管这个error
// Unmarshal 把 json 转化为 go struct
_ = json.Unmarshal([]byte(jsonStr),&c)
fmt.Println(c)
// {1213 红旗 中国} //Marshal 把 go struct 转化为 json 格式
bytes ,_ := json.Marshal(c)
fmt.Println(string(bytes))
// {"id":1213,"Name":"红旗","Country":"中国"}
//这个是用来调格式,让格式好看的
bytes1 ,_ := json.MarshalIndent(c,""," ")
fmt.Println(string(bytes1))
// {
// "id": 1213,
// "Name": "红旗",
// "Country": "中国"
// }
http.HandleFunc("/companies",func(w http.ResponseWriter, r *http.Request) {
switch r.Method{
case http.MethodPost:
//解码器
dec:= json.NewDecoder(r.Body)
company:= Company{}
// 解码
err:=dec.Decode(&company)
if err!=nil{
log.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
// 编码器
enc := json.NewEncoder(w)
// 编码
err = enc.Encode(company)
if err!=nil{
log.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
default:
w.WriteHeader(http.StatusMethodNotAllowed)
} })
http.ListenAndServe(":8080",nil)

这个和上面相配合的test.http。注意content-type和json数据之间必须有空行

POST http://localhost:8080/companies HTTP/1.1
content-type: application/json {
"id":1213,
"name": "红旗",
"country": "中国"
}

GO web学习(三)的更多相关文章

  1. java web 学习三(Tomcat 服务器学习和使用2)

    一.打包JavaWeb应用 在Java中,使用"jar"命令来对将JavaWeb应用打包成一个War包,jar命令的用法如下:

  2. Java Web 学习路线

    实际上,如果时间安排合理的话,大概需要六个月左右,有些基础好,自学能力强的朋友,甚至在四个月左右就开始找工作了.大三的时候,我萌生了放弃本专业的念头,断断续续学 Java Web 累计一年半左右,总算 ...

  3. web—第三章XHTML

     web—第三章XHTML 又是一周 我们学的了做表单:一开始我以为表单是表格.但结果:表单是以采集和提交用户输入数据的,这样讲很迷,说简单点就是登陆端.比如:Facebook.twitter.Ins ...

  4. Java Web学习系列——Maven Web项目中集成使用Spring

    参考Java Web学习系列——创建基于Maven的Web项目一文,创建一个名为LockMIS的Maven Web项目. 添加依赖Jar包 推荐在http://mvnrepository.com/.h ...

  5. WEB学习路线2019完整版(附视频教程+网盘下载地址)

    WEB学习路线2019完整版(附视频教程+网盘下载地址).适合初学者的最新WEB前端学习路线汇总! 在当下来说web前端开发工程师可谓是高福利.高薪水的职业了.所以现在学习web前端开发的技术人员也是 ...

  6. Java反射:Web学习的灵魂

    反射:Web学习的灵魂 我们从最初的 javac -HelloWorld.java,到面向对象部分,我们可以将Java代码在计算机中经历的阶段分为三部分:Scource源代码阶段 -- Class类对 ...

  7. JAVA Web学习笔记

    JAVA Web学习笔记 1.JSP (java服务器页面) 锁定 本词条由“科普中国”百科科学词条编写与应用工作项目 审核 . JSP全名为Java Server Pages,中文名叫java服务器 ...

  8. day 82 Vue学习三之vue组件

      Vue学习三之vue组件   本节目录 一 什么是组件 二 v-model双向数据绑定 三 组件基础 四 父子组件传值 五 平行组件传值 六 xxx 七 xxx 八 xxx 一 什么是组件 首先给 ...

  9. Salesforce LWC学习(三十九) lwc下quick action的recordId的问题和解决方案

    本篇参考: https://developer.salesforce.com/docs/component-library/bundle/force:hasRecordId/documentation ...

  10. HTTP学习三:HTTPS

    HTTP学习三:HTTPS 1 HTTP安全问题 HTTP1.0/1.1在网络中是明文传输的,因此会被黑客进行攻击. 1.1 窃取数据 因为HTTP1.0/1.1是明文的,黑客很容易获得用户的重要数据 ...

随机推荐

  1. day07 字符串和列表

    day07字符串与列表 字符串的内置方法 lower upper startswitch endwhich 格式化输出 format join的用法 replace替换字符串 isdigit判断 字符 ...

  2. Quartz 简单使用

    Scheduler 每次执行,都会根据JobDetail创建一个新的Job实例,这样就可以规避并发访问的问题(jobDetail的实例也是新的) Quzrtz 定时任务默认都是并发执行,不会等待上一次 ...

  3. RDIFramework.NET WinForm版新增报表管理功能模块

    在Web版本中有报表管理功能模块,非常实用的功能,重量级推荐.在WinForm应用中,我们也增加了支持."报表管理"模块主要用于对日常常用的报表做定制展示,可以自动发布到模块,同时 ...

  4. Centos 安装 python3.x 为默认

    CentOS 7 中默认安装了 Python,但是版本是2.x的,由于2020年python2.x将停止更新,因此需要将版本升级至3.x.但由于python2.x是系统集成的,很多命令都是要基于pyt ...

  5. Gateway同时使用断言跟过滤器查询数据库报了这个错误怎么解决?

    DynamicServerListLoadBalancer for client shop-product-sentinel initialized: DynamicServerListLoadBal ...

  6. VueHub:我用 ChatGPT 开发的第一个项目,送给所有 Vue 爱好者

    大家好,我是DOM哥. 我用 ChatGPT 开发了一个 Vue 的资源导航网站. 不管你是资深 Vue 用户,还是刚入门想学习 Vue 的小白,这个网站都能帮助到你. 网站地址:https://do ...

  7. 深度学习02-03(图像处理、OpenCV实验案例)

    OpenCV实验案例 文章目录 OpenCV实验案例 一.OpenCV安装 1. OpenCV介绍 2. 安装 二.OpenCV基本操作 1. 图像读取与保存 1)读取.图像.保存图像 2. 图像色彩 ...

  8. Django笔记三十八之发送邮件

    本文首发于公众号:Hunter后端 原文链接:Django笔记三十八之发送邮件 这一篇笔记介绍如何在 Django 中发送邮件. 在 Python 中,提供了 smtplib 的邮件模块,而 Djan ...

  9. 2022-12-29:nsq是go语言写的消息队列。请问k3s部署nsq,yaml如何写?

    2022-12-29:nsq是go语言写的消息队列.请问k3s部署nsq,yaml如何写? 答案2022-12-29: yaml如下: apiVersion: apps/v1 kind: Deploy ...

  10. OData WebAPI实践-与ABP vNext集成

    本文属于 OData 系列文章 ABP 是一个流行的 ASP. NET 开发框架,旧版的的 ABP 已经能够非常好的支持了 OData ,并提供了对应的 OData 包. ABP vNext 是一个重 ...