GO web学习(三)
跟着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学习(三)的更多相关文章
- java web 学习三(Tomcat 服务器学习和使用2)
一.打包JavaWeb应用 在Java中,使用"jar"命令来对将JavaWeb应用打包成一个War包,jar命令的用法如下:
- Java Web 学习路线
实际上,如果时间安排合理的话,大概需要六个月左右,有些基础好,自学能力强的朋友,甚至在四个月左右就开始找工作了.大三的时候,我萌生了放弃本专业的念头,断断续续学 Java Web 累计一年半左右,总算 ...
- web—第三章XHTML
web—第三章XHTML 又是一周 我们学的了做表单:一开始我以为表单是表格.但结果:表单是以采集和提交用户输入数据的,这样讲很迷,说简单点就是登陆端.比如:Facebook.twitter.Ins ...
- Java Web学习系列——Maven Web项目中集成使用Spring
参考Java Web学习系列——创建基于Maven的Web项目一文,创建一个名为LockMIS的Maven Web项目. 添加依赖Jar包 推荐在http://mvnrepository.com/.h ...
- WEB学习路线2019完整版(附视频教程+网盘下载地址)
WEB学习路线2019完整版(附视频教程+网盘下载地址).适合初学者的最新WEB前端学习路线汇总! 在当下来说web前端开发工程师可谓是高福利.高薪水的职业了.所以现在学习web前端开发的技术人员也是 ...
- Java反射:Web学习的灵魂
反射:Web学习的灵魂 我们从最初的 javac -HelloWorld.java,到面向对象部分,我们可以将Java代码在计算机中经历的阶段分为三部分:Scource源代码阶段 -- Class类对 ...
- JAVA Web学习笔记
JAVA Web学习笔记 1.JSP (java服务器页面) 锁定 本词条由“科普中国”百科科学词条编写与应用工作项目 审核 . JSP全名为Java Server Pages,中文名叫java服务器 ...
- day 82 Vue学习三之vue组件
Vue学习三之vue组件 本节目录 一 什么是组件 二 v-model双向数据绑定 三 组件基础 四 父子组件传值 五 平行组件传值 六 xxx 七 xxx 八 xxx 一 什么是组件 首先给 ...
- Salesforce LWC学习(三十九) lwc下quick action的recordId的问题和解决方案
本篇参考: https://developer.salesforce.com/docs/component-library/bundle/force:hasRecordId/documentation ...
- HTTP学习三:HTTPS
HTTP学习三:HTTPS 1 HTTP安全问题 HTTP1.0/1.1在网络中是明文传输的,因此会被黑客进行攻击. 1.1 窃取数据 因为HTTP1.0/1.1是明文的,黑客很容易获得用户的重要数据 ...
随机推荐
- python去掉重复值的方法--四种
my_list = [1,1,1,1,2,3,3,3,4,5,5,56,6,7,77,7,5,5,3]# 集合法:缺点是结果会打乱原始数据的顺序print(set(my_list)) # 列表法:缺点 ...
- 添加索引后SQL消耗量在执行计划中的变化
不同索引的执行效率也是不一样的,下面比较三条SQL语句在正常查询与建立普通索引与位图索引后的CPU消耗量的变化,目的为了是加强对索引的理解与运用 实验步骤:1.创建有特点的大数据表.为了保证索引产生前 ...
- 【Vue项目】尚品汇(三)Home模块+Floor模块+Swiper轮播图
写在前面 今天是7.23,这一篇内容主要完成了Home模块和部分Search模块的开发,主要是使用了swiper轮播图插件获取vuex仓库数据展示组件以及其他信息. 1 Search模块 1.1 Se ...
- uniapp directive 在原生 wgt 包不生效 uniapp directive 不生效
需求 根据权限编码禁用按钮 阻止当前 dom 绑定的点击事件,禁用状态(opacity 半透明?? 或者 display: none?? ) 尝试 开发环境用 Chrome 跑,一切正常,构建打包后去 ...
- Mapstruct使用报java: Couldn't retrieve @Mapper annotation
检查代码报错 java: Couldn't retrieve @Mapper annotation jar包冲突,去掉一个Mapstructjar包.
- vue将页面(dom元素)转换成图片,并保存到本地
1 npm install html2canvas --save <template> <div class="QRCode-box"> <img i ...
- 前端 本地缓存localStorage/sessionStorage
当我们刷新页面时,除了路由,页面的当前状态及数据会全部清空/重置,包括浏览器标题. 如果想保存刷新前的一些数据,可以通过window.localStorage/sessionStorage,在浏览器里 ...
- Java设计模式简介(总结)
Java设计模式简介(总结) 什么是设计模式 Java设计模式是一组经过验证的解决特定问题的编程技术,这些技术可以帮助开发人员快速.有效地开发高质量的软件.使用设计模式是为了可重用代码.让代码更容易被 ...
- 2022-11-22:小美将要期中考试,有n道题,对于第i道题, 小美有pi的几率做对,获得ai的分值,还有(1-pi)的概率做错,得0分。 小美总分是每道题获得的分数。 小美不甘于此,决定突击复习,
2022-11-22:小美将要期中考试,有n道题,对于第i道题, 小美有pi的几率做对,获得ai的分值,还有(1-pi)的概率做错,得0分. 小美总分是每道题获得的分数. 小美不甘于此,决定突击复习, ...
- 2020-12-07:go中,slice的底层数据结构是什么?
福哥答案2020-12-07: 源码位于runtime/slice.go文件中的slice结构体. type slice struct { array unsafe.Pointer len int c ...