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": "中国"
}
posted @ 2023-05-21 20:35  id_shiguang  阅读(6)  评论(0编辑  收藏  举报