Go Web 实战编程-http的使用

我爱海鲸 2024-06-06 16:57:37 go语言学习

简介http2、向客户端推送数据、https

1、helloWorldWeb:

package main

import (
	"fmt"
	"net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello World")
}
func main() {
	server := &http.Server{
		Addr: "0.0.0.0:80",
	}
	http.HandleFunc("/", hello)
	server.ListenAndServe()
}

2、http2:

package main

import (
	"log"
	"net/http"
)

func main() {
	// 启动服务器
	srv := &http.Server{Addr: ":8088", Handler: http.HandlerFunc(handle)}
	// 用TLS启动服务器,因为我们运行的是http/2,它必须是与TLS一起运行。
	log.Printf("Serving on https://0.0.0.0:8088")
	log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
}

//处理器方法
func handle(w http.ResponseWriter, r *http.Request) {
	// 记录请求协议
	log.Printf("Got connection: %s", r.Proto)
	// 向客户发送一条消息
	w.Write([]byte("Hello this is a HTTP/2 message!"))
}

3、refer:

package main

import (
	"net/http"
)

type Refer struct {
	handler http.Handler
	refer   string
}

func (this *Refer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Referer() == this.refer {
		this.handler.ServeHTTP(w, r)
	} else {
		w.WriteHeader(403)
	}
}
func myHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("this is handler"))
}
func hello(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hello"))
}
func main() {
	referer := &Refer{
		handler: http.HandlerFunc(myHandler),
		refer:   "www.shirdon.com",
	}
	http.HandleFunc("/hello", hello)
	http.ListenAndServe(":8080", referer)
}

4、https:

package main

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

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "This is HTTPS Server!")
}

func main() {
	http.HandleFunc("/hi", handler)
	err := http.ListenAndServeTLS(":8080", "cert.pem", "key.pem", nil)
	if err != nil {
		log.Fatal("ListenerAndServe:", err)
	}
}

5、delete:

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

func main() {
	url := "http://www.haijin.xyz"
	payload := strings.NewReader("{\"userId\":1,\"articleId\":1,\"comment\":\"这是一条评论\"}")
	req, _ := http.NewRequest("DELETE", url, payload)
	req.Header.Add("Content-Type", "application/json")
	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))
}

6、get:

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	resp, err := http.Get("https://www.taobao.com")
	if err != nil {
		fmt.Print("err", err)
	}
	closer := resp.Body
	bytes, err := ioutil.ReadAll(closer)
	fmt.Println(string(bytes))
}

7、http-server:

package main

import (
	"io"
	"log"
	"net/http"
)

func main() {
	// 设置路由
	http.HandleFunc("/v1", version1)
	// 路由注册完,开始运行
	err := http.ListenAndServe(":8082", nil)
	if err != nil {
		log.Fatal(err)
	}
}

// version1 handler
func version1(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "This is a version 1 response!")
}

8、post:

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	url := "http://www.haijin.xyz"
	body := "{\"userId\":1,\"articleId\":1,\"comment\":\"这是一条评论\"}"
	response, err := http.Post(url, "•application/x-www-form-urlencoded",
		bytes.NewBuffer([]byte(body)))
	if err != nil {
		fmt.Println("err", err)
	}
	b, err := ioutil.ReadAll(response.Body)
	fmt.Println(string(b))
}

9、put:

import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)

func main() {
url := "http://www.haijin.xyz"
payload := strings.
NewReader("{\"userId\":1,\"articleId\":1,\"comment\":\"这是一条评论\"}")
req, _ := http.NewRequest("PUT", url, payload)
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)

defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)

fmt.Println(res)
fmt.Println(string(body))
}

10、template-example:

package main

import (
	"fmt"
	"html/template"
	"net/http"
)

func helloHandleFunc(w http.ResponseWriter, r *http.Request) {
	// 1. 解析模板
	t, err := template.ParseFiles("./template_example.tmpl")
	if err != nil {
		fmt.Println("template parsefile failed, err:", err)
		return
	}
	// 2.渲染模板
	name := "我爱Go语言"
	t.Execute(w, name)
}

func main() {
	http.HandleFunc("/", helloHandleFunc)
	http.ListenAndServe(":8086", nil)
}

template_example.tmpl:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模板使用示例</title>
</head>
<body>
   <p>加油,小伙伴, {{ . }} </p>
</body>
</html>

11、template-func:

package main

import (
	"fmt"
	"html/template"
	"io/ioutil"
	"net/http"
)

func Welcome() string { //没参数
	return "Welcome"
}

func Doing(name string) string { //有参数
	return name + ", Learning Go Web template "
}

func sayHello(w http.ResponseWriter, r *http.Request) {
	htmlByte, err := ioutil.ReadFile("./funcs.html")
	if err != nil {
		fmt.Println("read html failed, err:", err)
		return
	}
	// 自定义一个匿名模板函数
	loveGo := func() string {
		return "欢迎一起学习《Go Web编程实战派从入门到精通》"
	}
	// 采用链式操作在Parse()方法之前调用Funcs添加自定义的loveGo函数
	tmpl1, err := template.New("funcs").Funcs(template.FuncMap{"loveGo": loveGo}).Parse(string(htmlByte))
	if err != nil {
		fmt.Println("create template failed, err:", err)
		return
	}
	funcMap := template.FuncMap{
		//在FuncMap中声明相应要使用的函数,然后就能够在template字符串中使用该函数
		"Welcome": Welcome,
		"Doing":   Doing,
	}
	name := "Shirdon"
	tmpl2, err := template.New("test").Funcs(funcMap).Parse("{{Welcome}}\n{{Doing .}}\n")
	if err != nil {
		panic(err)
	}

	// 使用user渲染模板,并将结果写入w
	tmpl1.Execute(w, name)
	tmpl2.Execute(w, name)
}

func main() {
	http.HandleFunc("/", sayHello)
	http.ListenAndServe(":8087", nil)

}

funcs.html

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>tmpl test</title></head><body>
<h1>{{loveGo}}</h1>

12、template-multi:

package main

import (
	"fmt"
	"html/template"
	"net/http"
)

// 定义一个UserInfo结构体
type UserInfo struct {
	Name   string
	Gender string
	Age    int
}

func tmplSample(w http.ResponseWriter, r *http.Request) {
	tmpl, err := template.ParseFiles("./t.html", "./ul.html")
	if err != nil {
		fmt.Println("create template failed, err:", err)
		return
	}
	user := UserInfo{
		Name:   "张三",
		Gender: "男",
		Age:    28,
	}
	tmpl.Execute(w, user)
	fmt.Println(tmpl)
}

func main() {
	http.HandleFunc("/", tmplSample)
	http.ListenAndServe(":8087", nil)
}

t.html:

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>tmpl test</title></head><body>
<h1>测试嵌套template语法</h1>
<hr>
{{template "ul.html"}}
<hr>
{{template "ol.html"}}</body></html>
{{ define "ol.html"}}<h1>这是ol.html</h1><ol>
    <li>I love Go</li>
    <li>I love java</li>
    <li>I love c</li></ol>
{{end}}

ul.html:

<ul>
    <li>注释</li>
    <li>日志</li>
    <li>测试</li>
</ul>

13、template-range:

package main

import (
	"log"
	"os"
	"text/template"
)

func main() {
	//创建一个模版
	rangeTemplate := `
{{if .Kind}}
{{range $i, $v := .MapContent}}
{{$i}} => {{$v}} , {{$.OutsideContent}}
{{end}}
{{else}}
{{range .MapContent}}
{{.}} , {{$.OutsideContent}}
{{end}}    
{{end}}`

	str1 := []string{"第一次 range", "用 index 和 value"}
	str2 := []string{"第二次 range", "没有用 index 和 value"}

	type Content struct {
		MapContent     []string
		OutsideContent string
		Kind           bool
	}
	var contents = []Content{
		{str1, "第一次外面的内容", true},
		{str2, "第二次外面的内容", false},
	}

	// 创建模板并将字符解析进去
	t := template.Must(template.New("range").Parse(rangeTemplate))

	// 接收并执行模板
	for _, c := range contents {
		err := t.Execute(os.Stdout, c)
		if err != nil {
			log.Println("executing template:", err)
		}
	}
}

14、header:

package main

import (
	"net/http"
)

func main() {
	headers := http.Header{"token": {"kuysdfaeg6634fwr324brfh3urhf839hf349h"}}
	headers.Add("Accept-Charset","UTF-8")
	headers.Set("Host","www.shirdon.com")
	headers.Set("Location","www.baidu.com")
}

 

 

你好:我的2025