Go Http服务器

http 协议用于 web 开发,Go 语言中也实现了他,下面我们就来看下如何使用他。

hello world

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
"net/http"
"log"
)

func main() {
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte("hello world"))
})
log.Fatal(http.ListenAndServe(":8000", nil))
}

编译运行

1
go run http.go

打开浏览器 http://localhost:8000 就可以看到效果了,是不是很简单。

使用 html 模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main

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

func main() {
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
tmpl, _ := template.ParseFiles("index.html")
data := make(map[string]interface{})
data["Title"] = "Title"
tmpl.ExecuteTemplate(writer, "index", data)
})
log.Fatal(http.ListenAndServe(":8000", nil))
}

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{{define "index"}}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
{{.Title}}
</body>
</html>
{{end}}

加载静态 css/js 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

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

func main() {
http.Handle("/css/", http.FileServer(http.Dir("static")))
http.Handle("/js/", http.FileServer(http.Dir("static")))

http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
tmpl, _ := template.ParseFiles("index.html")
data := make(map[string]interface{})
data["Title"] = "Title"
tmpl.ExecuteTemplate(writer, "index", data)
})
log.Fatal(http.ListenAndServe(":8000", nil))
}

©版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 & 作者信息

Happy Coding

坚持原创技术分享,您的支持将鼓励我继续创作!
Flyertutor WeChat Pay

WeChat Pay

Flyertutor Alipay

Alipay