golang之net/http模块学习

文章目录

开启服务

go 复制代码
package main

import (
	"fmt"
	"net/http"
)

//路由
func handler(w http.ResponseWriter, r *http.Request){
	fmt.Fprintf(w, "hello World!")
}

func main(){
	//路由
	http.HandleFunc("/", handler)
  	//开启服务
	http.ListenAndServe(":8091", nil) //port:8091(自定义,注意:要是空闲端口)
}
shell 复制代码
#启动服务
go run main.go

这样本地的8091端口就可以访问了

开启访问静态文件

我们这里拿video来举例

go 复制代码
package main

import (
  "fmt"
  "net/http"
)

func main(){
  	//静态文件访问
	fs := http.FileServer(http.Dir("./assets"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))
	//开启服务
	http.ListenAndServe(":8091", nil)
}

按照图上的访问路径(http://localhost:8091/static/video/20231204-134423.mp4)

获取现在时间

go 复制代码
package main

import (
  "fmt"
  "time"
)

func main(){
	currentTime := time.Now()
	fmt.Println("当前的时间为",currentTime)
}

因为currentTime是time.Time类型所以要想页面输出要进行字符串转换

go 复制代码
//获取时间
func getNowTime(w http.ResponseWriter, r *http.Request){
	currentTime := time.Now()
	timeString := currentTime.Format("2006-01-02 15:04:05")//"2006-01-02 15:04:05"只是时间格式化字符串格式
	fmt.Fprintf(w,timeString)
}

至于这个函数上面命名也是如此,就当是net/http路由服务的固定格式便好

注意: Golang函数首字符大写代表着公开(public)小写代表着私有(private)

按时间创建一个空的json文件

go 复制代码
package main

import (
	"fmt"
	"time"
//	"encoding/json"
	"os"
)

func CreateFileNil(){
	currentTime := GetTime()
	fileName := currentTime.Format("2006-01-02_15-04-05") + ".json"
	file,err := os.Create("./assets/json/"+fileName)
	if err != nil {
		fmt.Println("JSON编码失败:", err)
		return
	}
	defer file.Close() //defer:表示函数的最后执行(这里是确保最后文件是关闭的)
}

func main(){
	CreateFileNil()
}
按时间创建一个固定值的json文件
go 复制代码
package main

import (
	"fmt"
	"time"
	"encoding/json"
	"os"
)

type Person struct {
	Name string
	Age int
}
//创建一个固定值的json文件
func CreateFileGuDin(){
	currentTime := GetTime()
	fileName := currentTime.Format("2006-01-02_15-04-05") + ".json"
	file,err := os.Create("./assets/json/"+fileName)
	if err != nil {
		fmt.Println("JSON编码失败:", err)
		return
	}
	defer file.Close()
	
	person := Person{Name: "Alice", Age: 25}
	jsonData, err := json.Marshal(person)
	if err != nil {
		fmt.Println("JSON编码失败:", err)
		return
	}

	_, err = file.Write(jsonData)
	if err != nil {
		fmt.Println("写入文件失败:", err)
		return
	}

	fmt.Println("JSON文件创建成功:", fileName)
}

func main(){
  CreateFileGuDin()
}

跨域请求处理

go 复制代码
package main

import (
	"fmt"
	"net/http"
)

//路由
func handler(w http.ResponseWriter, r *http.Request){
	fmt.Fprintf(w, "hello World!")
}

func main(){
	//创建一个处理跨域请求的处理器函数
	corsHandler := func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// 设置允许跨域的域名
			w.Header().Set("Access-Control-Allow-Origin", "*")
			// 允许的请求方法
			w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
			// 允许的请求头
			w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
			// 如果是预检请求,直接返回
			if r.Method == "OPTIONS" {
				return
			}
			h.ServeHTTP(w, r)
		})
	}
	//路由
	http.Handle("/", corsHandler(http.HandlerFunc(handler)))

	//开启服务
	http.ListenAndServe(":8091", nil)
}

golang返回给前端的是json

go 复制代码
package main

import (
  "fmt"
  "net/http"
  "encoding/json"
)

type FileDetail struct{
  NowTime string `json:"now_time"`
  FileName string `json:"file_name"`
}

func func_name1(w http.ResponseWriter, r *http.Request){
  responseData := FileDetail {NowTime:"2023_12_04_22_51_30.json",FileName:"http://"+local+":" + port + "/static/video/20231204-19.mp4"}
  w.Header().Set("Content-Type", "application/json")
  w.WriteHeader(http.StatusOK)
  json.NewEncoder(w).Encode(responseData)
}

func main(){
  //创建一个处理跨域请求的处理器函数
	corsHandler := func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// 设置允许跨域的域名
			w.Header().Set("Access-Control-Allow-Origin", "*")
			// 允许的请求方法
			w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
			// 允许的请求头
			w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
			// 如果是预检请求,直接返回
			if r.Method == "OPTIONS" {
				return
			}
			h.ServeHTTP(w, r)
		})
	}
    
    http.Handle("/test", corsHandler(http.HandlerFunc(func_name1)))
    //开启服务
	http.ListenAndServe(":8091", nil)
}

处理post请求数据(golang返回给前端的是json)

go 复制代码
//第一个接受外部的请求处理函数
func RequestVlaue1_handler(w http.ResponseWriter, r *http.Request){
	if r.Method == "POST" {
		body, err := ioutil.ReadAll(r.Body) //读取post请求中body的值
		if err != nil {
			http.Error(w, "Unable to read request body", http.StatusBadRequest)
			return
		}
		defer r.Body.Close() //关闭body读取
		fmt.Println(string(body)) //可以不写
		
		// 在这里处理接收到的数据,可以进行解析和处理
		// 例如,你可以使用json.Unmarshal来解析JSON格式的数据
		byteData := []byte(body) //将body的[]byte数据存储起来
		var jsonData map[string]interface{} //定义一个map[string]用来转换成json
		err1 := json.Unmarshal(byteData,&jsonData) //将body存储到map[string]中进行json转换
		if err1 != nil {
			fmt.Println("解析JSON失败:", err)
			return
		}
		//之后就是json返回输出
		responseData := jsonData
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(responseData)	
	}
}

处理Get请求数据(golang返回给前端的是json)

go 复制代码
func RequestVlaueGet_handler(w http.ResponseWriter, r *http.Request){
	defer r.Body.Close() //关闭post请求的body
	data := r.URL.Query()
	//获取到的值是map[xxx:[xxx],xxx:[xxx]]
	//	fmt.Println(data)
	//获取值,比如url是http://localhost:8091/music_find?file_name=xxx.mp3
	file_name := data["file_name"][0]
	
	responseData := {FileName:file_name}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(responseData)
}

golang连接数据库

sql 复制代码
create database webgo_download; #创建数据库
use webgo_download; #使用此数据库
#创建表格
create table music_detail(id int not null AUTO_INCREMENT PRIMARY KEY,file_name varchar(255) not null,file_cast_name varchar(255) not null,url varchar(255) not null);

#测试
insert into music_detail(file_name,file_cast_name,url) values("test","test.mp3","http://localhost:8091/static/music/test.mp3");

select * from music_detail;
添加依赖
shell 复制代码
go get github.com/jmoiron/sqlx
shell 复制代码
go get github.com/go-sql-driver/mysql
打开数据库

sql版

go 复制代码
//第二个参数,按照自己的数据库来改,格式为"user:password@tcp(数据库ip:数据库端口号)/要连接的数据库名称"
db,err := sql.Open("mysql","root:123456@tcp(127.0.0.1:3306)/webgo_download") 
	if err != nil {
		fmt.Println(err)
	}
	defer db.Close()

	// 尝试连接数据库
	err = db.Ping()
	if err != nil {
		fmt.Println(err)
	}
	
	fmt.Println("成功连接到数据库")

sqlx版

go 复制代码
//第二个参数,按照自己的数据库来改,格式为"user:password@tcp(数据库ip:数据库端口号)/要连接的数据库名称"
db,err := sqlx.Open("mysql","root:123456@tcp(127.0.0.1:3306)/webgo_download")
	if err != nil {
		fmt.Println("Open error:",err)
	}
	defer db.Close()

查询数据(单个数据)

我这里使用的是sqlx所以sql的请另辟蹊径

go 复制代码
//创建一个和mysql结构一样的结构体
type FileSaveOfMySQL struct {
	Id int `db:"id"`
	FileName string `db:"file_name"`
	FileCastName string `db:"file_cast_name"`
	Url string `db:"url"`
}
go 复制代码
//package link //package你自己定(或者直接在主函数main.go中编写)

//用到的依赖(如果没用到会报not used错误,到时候取消掉没用到的依赖即可)
import (
	"database/sql"
	"fmt"
//	"log"
	"github.com/jmoiron/sqlx"
	_ "github.com/go-sql-driver/mysql"
)

//创建一个和mysql结构一样的结构体
type FileSaveOfMySQL struct {
	Id int `db:"id"`
	FileName string `db:"file_name"`
	FileCastName string `db:"file_cast_name"`
	Url string `db:"url"`
}

func SelectMusic(file_name string) FileSaveOfMySQL{
	var fileSave FileSaveOfMySQL
	//第二个参数,按照自己的数据库来改,格式为"user:password@tcp(数据库ip:数据库端口号)/要连接的数据库名称"
	db,err := sqlx.Open("mysql","root:123456@tcp(127.0.0.1:3306)/webgo_download")
	if err != nil {
		fmt.Println("Open error:",err)
	}
	defer db.Close()
	
	err = db.Get(&fileSave, "select * from music_detail where file_name = ?", file_name)
	if err != nil {
		fmt.Println("query failed:",err)
		return FileSaveOfMySQL{}
	}
	defer db.Close()
	return fileSave
}

使用多个结构体实例序列化

这里打个比方

go 复制代码
type FileSaveOfMySQL struct {
	Id int  `json:"id" db:"id"`
	FileName string `json:"file_name" db:"file_name"`
	FileCastName string `json:"file_cast_name" db:"file_cast_name"`
	Url string  `json:"url" db:"url"`
}
相关推荐
觉醒法师2 分钟前
HarmonyOS开发 - 电商App实例二( 网络请求http)
前端·http·华为·typescript·harmonyos·ark-ts
初学者7.8 分钟前
lodash手写源码-cloneDeep,debounce,throttle
笔记·学习·loadsh
q567315231 小时前
使用CPR库编写的爬虫程序
开发语言·爬虫·golang·音视频
eggcode1 小时前
IDEA与Maven使用-学习记录(持续补充...)
学习·maven·intellij-idea
Pyroyster2 小时前
【Go语言圣经1.1】
开发语言·后端·golang
charlie1145141913 小时前
从0开始的操作系统手搓教程33:挂载我们的文件系统
学习·系统架构·操作系统·教程·文件系统·手搓教程
YGGP3 小时前
【每日八股】Golang篇(三):关键字(下)
开发语言·后端·golang
Bright Data3 小时前
在 Axios 中设置代理
http·https·axios·api·socks·代理服务器·proxy server
熬了夜的程序员3 小时前
Go 语言封装 HTTP 请求的 Curl 工具包
后端·程序人生·http·golang