首页 > 其他分享 >GO web 学习(三)

GO web 学习(三)

时间:2023-05-21 20:45:19浏览次数:32  
标签:web http string JSON 学习 go json func GO

路由

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 安全并健壮 -》 内部应用的企业集成

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

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

标签:web,http,string,JSON,学习,go,json,func,GO
From: https://www.cnblogs.com/tiangong/p/17419125.html

相关文章

  • spring security授权过滤器FilterSecurityInterceptor学习
    目录一、springsecurity资源访问权限配置1.1使用ExpressionUrlAuthorizationConfigurer1.2使用UrlAuthorizationConfigurer二、FilterSecurityInterceptor的处理流程2.1ConfigAttribute的获取2.2决策管理器AccessDecisionManager2.3AccessDecisionVoter投票器三、FilterSec......
  • 算法学习记录(模拟枚举贪心题单):[NOIP2007]字符串的展开(未AC,明天找bug)
    题目链接https://ac.nowcoder.com/acm/contest/20960/1001解题思路很简单的模拟题,以后写模拟要先分两大类,元素在某个集合中存不存在的问题,再细分。未AC代码#include<iostream>#include<string>usingnamespacestd;//碰到'-'的展开条件:// 1.减号两侧同为小写字母......
  • Openresty 学习笔记(二)Nginx Lua 正则表达式相关API
    ngx.re.match语法: captures,err=ngx.re.match(subject,regex,options?,ctx?,res_table?)环境: init_worker_by_lua*,set_by_lua*,rewrite_by_lua*,access_by_lua*,content_by_lua*,header_filter_by_lua*,body_filter_by_lua*,log_by_lua*,ngx.timer.*,balancer......
  • pytorch学习笔记——timm库
    当使用ChatGPT帮我们工作的时候,确实很大一部分人就会失业,当然也有很大一部分人收益其中。我今天继续使用其帮我了解新的内容,也就是timm库。毫不夸张的说,ChatGPT比百分之80的博客讲的更清楚更好,仅次于源码。当提到计算机视觉的深度学习框架时,PyTorch无疑是最受欢迎的选择......
  • 【李宏毅机器学习】(一)正确认识ChatGPT
    该文是一篇机器学习的学习笔记,学习内容:李宏毅2023春机器学习课程ChatGPT(ChatGenerativePre-trainedTransformer)是一个以对话的方式进行交互的语言模型,由OpenAI发布。常见误解对ChatGPT的常见误解:ChatGPT是从开发者事先准备好的答案里随机抽取一个回答。ChatGPT......
  • C#学习笔记 -- 分部类、分部方法
    1、分部类和分部类型类的声明可以分割成几个分部类的声明每个分部类的声明都有一些成员的声明类的分部类声明可以在同一文件中也可以在不同文件中每个分部类声明必须被标注为patialclasspartialclassMyPartClass//类名称与下部分相同{  member1delaration......
  • MySQL学习基础篇Day6
    5.多表查询我们之前在讲解SQL语句的时候,讲解了DQL语句,也就是数据查询语句,但是之前讲解的查询都是单表查询,而本章节我们要学习的则是多表查询操作,主要从以下几个方面进行讲解。5.1多表关系项目开发中,在进行数据库表结构设计时,会根据业务需求及业务模块之间的关系,分析并设计表......
  • Go源码阅读——github.com/medcl/esm —— v7.go
    esm(AnElasticsearchMigrationTool)——v7.go https://github.com/medcl/esmrelease:8.7.1通过阅读好的源代码,细致思考,理性分析并借鉴优秀实践经验,提高zuoyang的编程水平,所谓"他山之石,可以攻玉" 该是如此吧。 /*Copyright2016Medcl(mATmedcl.net)Licensed......
  • whatweb----web指纹探测工具
    简介原文链接:https://culturesun.site/index.php/archives/691.htmlWhatWeb是一款kali自带的工具。可以识别网站。它认可网络技术,包括内容管理系统(CMS)、博客平台、统计/分析包、JavaScript库、网络服务器和嵌入式设备。WhatWeb有900多个插件,每个插件都可以识别不同的东西。它还......
  • springboot集成websocket
    导入依赖1<dependency>2<groupId>org.springframework.boot</groupId>3<artifactId>spring-boot-starter-websocket</artifactId>4</dependency>编写配置类@ConfigurationpublicclassWebSocketConfig{@Beanpub......