一、Goweb通过https提供服务
func main() {
ListenAndServerTLS()
}
func ListenAndServerTLS() {
server := http.Server{
Addr: "127.0.0.1:8080",
Handler: nil,
}
server.ListenAndServeTLS("cert.pem", "key.pem")
}
二、Goweb生成SSL证书和私钥
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"net"
"os"
"time"
)
func main() { //生成SSL证书和私钥
max := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, _ := rand.Int(rand.Reader, max)
subject := pkix.Name{
Organization: []string{"书文教育"},
OrganizationalUnit: []string{"互联网教育"},
CommonName: "学思题库",
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: subject,
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, //
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, // 证书设置成只能在IP地址为127上运行
}
pk, _ := rsa.GenerateKey(rand.Reader, 2048)
derBytes, _ := x509.CreateCertificate(rand.Reader, &template, &template, &pk.PublicKey, pk)
certOut, _ := os.Create("cert.pem")
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
certOut.Close()
keyOut, _ := os.Create("key.pem")
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(pk)})
keyOut.Close()
}
三、Goweb处理请求
package main
import (
"fmt"
"net/http"
)
type MyHandler struct{} // 处理器和处理器函数
//ServeHTTP为固定写法
func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello world !")
}
func main() { // Server服务器&hander处理器进行了绑定:用同一个处理器处理所有的请求
handler := MyHandler{}
server := http.Server{ // 服务器
Addr: "127.0.0.1:8080",
Handler: &handler, // 处理器绑定服务器http://127.0.0.1:8080/anything/at/all
}
server.ListenAndServe()
}
四、Goweb使用多个处理器对请求进行处理
package main
import (
"fmt"
"net/http"
)
type HelloHandler struct{}
func (h *HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello!")
}
type WorldHandler struct{}
func (http *WorldHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "World!")
}
func main() {
hello := HelloHandler{}
world := WorldHandler{}
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.Handle("/hello", &hello)
http.Handle("/world", &world)
server.ListenAndServe()
}
五、Goweb使用处理器函数处理请求
package main
import (
"fmt"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello!")
}
func world(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "World!")
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/hello", hello)
http.HandleFunc("/world", world)
server.ListenAndServe()
}
六、Goweb串联两个处理器函数
package main
import (
"fmt"
"net/http"
"reflect"
"runtime"
)
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello!")
}
func log(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := runtime.FuncForPC(reflect.ValueOf(h).Pointer()).Name()
fmt.Println("Handler function called = ", name)
h(w, r)
}
}
func main() {
Server := http.Server{Addr: "127.0.0.1:8080"}
http.HandleFunc("/hello", log(hello))
Server.ListenAndServe()
}
七、Goweb串联多个处理器
八、Goweb使用HttpRouter实现的服务器
package main
import (
"fmt"
"net/http"
"github.com/julienschmidt/httprouter"
)
func hello(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
fmt.Fprintf(w, "hello,%s!\n", p.ByName("name"))
}
func main() {
mux := httprouter.New()
mux.GET("/hello/:name", hello)
server := http.Server{
Addr: "127.0.0.1:8080",
Handler: mux,
}
server.ListenAndServe()
}
九、Goweb读取请求首部
package main
import (
"fmt"
"net/http"
)
func headers(w http.ResponseWriter, r *http.Request) {
h := r.Header // 读取请求首部
fmt.Println("h=", h)
fmt.Fprintln(w, h)
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/headers", headers)
server.ListenAndServe()
}
十、Goweb读取请求主体中的数据
package main
import (
"fmt"
"net/http"
)
func body(w http.ResponseWriter, r *http.Request) {
len := r.ContentLength // 获取主体字节长度
body := make([]byte, len) // 根据长度创建字节数组
r.Body.Read(body) // 调用Read方法将主体数据读取到字节数组中
fmt.Fprintln(w, string(body))
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080", // curl -id "first_name=Shuwen&last_name=He" 127.0.0.1:8080/body
}
http.HandleFunc("/body", body)
server.ListenAndServe()
}
十一、Goweb对表单进行语法分析
package main
import (
"fmt"
"net/http"
)
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/process", process)
server.ListenAndServe()
}
func process(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Fprintln(w, r.Form)
}
十二、Goweb接收用户上传文件
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/process", process)
server.ListenAndServe()
}
func process(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(1024)
fileHeader := r.MultipartForm.File["uploaded"][0]
file, err := fileHeader.Open()
if err == nil {
data, err := ioutil.ReadAll(file)
if err == nil {
fmt.Fprintln(w, string(data))
}
}
}
十三、Goweb请求主体
package main
import (
"fmt"
"net/http"
)
func body(w http.ResponseWriter, r *http.Request) {
len := r.ContentLength // 获取主体字节长度
body := make([]byte, len) // 根据长度创建字节数组
r.Body.Read(body) // 调用Read方法将主体数据读取到字节数组中
fmt.Fprintln(w, string(body))
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080", // curl -id "first_name=Shuwen&last_name=He" 127.0.0.1:8080/body
}
http.HandleFunc("/body", body)
server.ListenAndServe()
}
十四、Goweb使用write方法向客户端发送响应
package main
import (
"net/http"
)
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/write", writeExample)
server.ListenAndServe()
}
func writeExample(w http.ResponseWriter, r *http.Request) {
str := `<html>
<head><title>Go web </title></head>
<body><h1>hello world</h1></body>
</html>`
w.Write([]byte(str))
}
十五、Goweb通过WriteHeader方法将状态码写入到响应当中
package main
import (
"fmt"
"net/http"
)
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/writeheader", WriteHeader)
server.ListenAndServe()
}
func WriteHeader(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(501)
fmt.Fprintln(w, "No such service,try next door.")
}
十六、通过编写首部实现客户端重定向
package main
import (
"net/http"
)
type Post struct {
User string
Threads []string
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/header", header)
server.ListenAndServe()
}
func header(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", "http://xstiku.com")
w.WriteHeader(302)
}