go的web开发

web开发流程

在这里插入图片描述

一、创立一个web服务器

自己配置handler处理机

package main

import (
	"net/http"
	"fmt"
)

type myHandle struct {
	content string
}

//实现了接口
func (h *myHandle) ServeHTTP(w http.ResponseWriter,r *http.Request){
	fmt.Println("hillo handle")
	fmt.Fprint(w,"hillo",h.content)
}

func main(){
	myhandle :=myHandle{content:"我是一只小小鸟"}
	http.Handle("/hello",&myhandle)
	err :=http.ListenAndServe("0.0.0.0:8880",nil)
	if err!=nil{
		fmt.Println("http is err")
	}
}

创建一个自己的多路转接器

package main

import (
	"net/http"
	"fmt"
)

type myHandle struct {
	content string
}

func (h *myHandle) ServeHTTP(w http.ResponseWriter,r *http.Request){
	fmt.Println("hillo handle")
	fmt.Fprint(w,"hillo",h.content)
	fmt.Fprint(w,"\n这是我自己调用多路交换器创建的")
}

func main(){
	myhandle :=myHandle{content:"我是一只小小鸟"}
	myServerMux :=http.NewServeMux()//自己new一个多路转换器
	myServerMux.Handle("/hello",&myhandle)
	http.ListenAndServe(":8880",myServerMux)
}

自己配置server

package main

import (
	"net/http"
	"fmt"
	"time"
)

type myHandle struct {
	content string
}

func (h *myHandle) ServeHTTP(w http.ResponseWriter,r *http.Request){
	fmt.Println("hillo handle")
	fmt.Fprint(w,"hillo",h.content)
	fmt.Fprint(w,"\n这是我自己调用多路交换器创建的2")
}

func main(){
	myhandle :=myHandle{content:"我是一只小小鸟"}
	myServerMux :=http.NewServeMux()
	myServerMux.Handle("/hillo",&myhandle)
	//http.ListenAndServe(":8880",myServerMux)
	server :=http.Server{		//自己配置server
		Addr:":8882",
		Handler:myServerMux,
		ReadTimeout: 2*time.Second,
	}
	server.ListenAndServe()   //调用ListenAndServe监听srv.Addr指定的TCP地址
}

二、HTTP协议

HTTP超文本传输协议(HTTP-Hypertext transfer protocol),**是一个属于应用层的
面向对象的协议,由于其简捷、快速的方式,适用于分布式超媒体信息系统。**它于1990
年提出,经过几年的使用与发展,得到不断地完善和扩展。

它是一种详细规定了浏览器和万维网服务器之间互相通信的规则,通过因特网传送万维网文档的数据传送协议。客户端与服务端通信时传输的内容我们称之为报文

HTTP就是一个通信规则,这个规则规定了客户端发送给服务器的报文格式,也规
定了服务器发送给客户端的报文格式。实际我们要学习的就是这两种报文。客户端发送
给服务器的称为"请求报文",服务器发送给客户端的称为”响应报文"。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mONToxIL-1596270886927)(./img/0902.png)]

二、处理请求和响应

请求

获取url的请求在Request结构体中含有

还可以通过Header和From等获取到其中请求体信息和数据

响应

通过respondWrite来进行响应

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值