Go原生web

349 阅读3分钟

hello world

package main

import "net/http"
import "fmt"

func main() {
	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		fmt.Fprintf(writer, "hello world")
	})
	http.ListenAndServe(":9090", nil)
}

获取GET请求参数

package main

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

func GetParams(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	// 方式1
	fmt.Println(`r.Form.Get("name"):`, r.Form.Get("name"))
	fmt.Println(`r.Form.Get("age"):`, r.Form.Get("age"))

	// 方式2
	fmt.Println(`r.Form["name"]:`, r.Form["name"])
	fmt.Println(`r.Form["age"]:`, r.Form["age"])

	// 获取所有参数
	for k, v := range r.Form {
		fmt.Println(k, strings.Join(v, ""))
	}

	// 返回消息
	fmt.Fprintf(w, "hello")
}

func main() {
	http.HandleFunc("/", GetParams)
	http.ListenAndServe(":9090", nil)
}

http://127.0.0.1:9090/?name=wang&age=23

输出:

r.Form.Get("name"): wang
r.Form.Get("age"): 23
r.Form["name"]: [wang]
r.Form["age"]: [23]
name wang
age 23

URL

package main

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

func URL(w http.ResponseWriter, r *http.Request) {
	fmt.Println(`r.URL.Scheme:`, r.URL.Scheme)
	fmt.Println(`r.URL.Path:`, r.URL.Path)
	fmt.Println(`r.URL.RawPath:`, r.URL.RawPath)
	fmt.Println(`r.URL.RawQuery:`, r.URL.RawQuery)
	fmt.Println(`r.URL.Opaque:`, r.URL.Opaque)
	fmt.Println(`r.URL.Fragment:`, r.URL.Fragment)
	fmt.Println(`r.URL.Host:`, r.URL.Host)
	fmt.Println(`r.URL.Hostname():`, r.URL.Hostname())
	fmt.Println(`r.URL.Port():`, r.URL.Port())
	fmt.Println(`r.URL.String():`, r.URL.String())
	fmt.Println(`r.URL.RequestURI():`, r.URL.RequestURI())
	fmt.Println(`r.URL.EscapedPath():`, r.URL.EscapedPath())
	fmt.Println(`r.URL.IsAbs():`, r.URL.IsAbs())
	fmt.Println(`r.URL.User.String():`, r.URL.User.String())
}

func main() {
	http.HandleFunc("/index", URL)
	http.ListenAndServe(":9090", nil)
}

http://127.0.0.1:9090/index?name=wang&age=23

输出

r.URL.Scheme: 
r.URL.Path: /index
r.URL.RawPath: 
r.URL.RawQuery: name=wang&age=23
r.URL.Opaque: 
r.URL.Fragment: 
r.URL.Host: 
r.URL.Hostname(): 
r.URL.Port(): 
r.URL.String(): /index?name=wang&age=23
r.URL.RequestURI(): /index?name=wang&age=23
r.URL.EscapedPath(): /index
r.URL.IsAbs(): false
r.URL.User.String(): 

获取URL参数

package main

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

func URLParams(w http.ResponseWriter, r *http.Request) {
	fmt.Println(`r.URL.Query().Get("name"):`, r.URL.Query().Get("name"))
	fmt.Println(`r.URL.Query().Get("age"):`, r.URL.Query().Get("age"))
}

func main() {
	http.HandleFunc("/url_params", URLParams)

	http.ListenAndServe(":9090", nil)
}

http://127.0.0.1:9090/url_params?name=wang&age=23

输出:

r.URL.Query().Get("name"): wang
r.URL.Query().Get("age"): 23

创建服务器的方式2

package main

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

func URLParams(w http.ResponseWriter, r *http.Request) {
	fmt.Println(`r.URL.Query().Get("name"):`, r.URL.Query().Get("name"))
	fmt.Println(`r.URL.Query().Get("age"):`, r.URL.Query().Get("age"))
}

func main() {
	http.HandleFunc("/url_params", URLParams)

	server := http.Server{
		Addr: ":9090",
	}

	server.ListenAndServe()
}

创建服务器方式3

package main

import (
	"io"
	"net/http"
)

type test1 struct{content string}

func (s *test1) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, s.content)
}


type test2 struct{content string}

func (s *test2) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, s.content)
}

func main() {
	http.Handle("/test1", &test1{"test1..."})
	http.Handle("/test2", &test2{"test2..."})
	http.ListenAndServe(":9090", nil)
}

接收post x-www-form-urlencoded 参数

package main

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

func AddUser(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		// 解析form参数
		r.ParseForm()

		if r.Form.Get("username") == "" || r.Form.Get("password") == "" {
			io.WriteString(w, "参数不能为空")
			return
		}

		// 接收方式1
		fmt.Println(`r.Form.Get("username"):`, r.Form.Get("username"))
		fmt.Println(`r.Form.Get("password"):`, r.Form.Get("password"))

		// 接收方式2
		fmt.Println(`r.Form["username"]:`, r.Form["username"])
		fmt.Println(`r.Form["password"]:`, r.Form["password"])

		// 接收方式3
		for k, v := range r.Form {
			fmt.Println(k, strings.Join(v, ""))
		}

		io.WriteString(w, "add user success")
		return
	} else {
		io.WriteString(w, "请使用POST方式请求")
		return
	}
}

func main() {
	http.HandleFunc("/add_user", AddUser)
	http.ListenAndServe(":9090", nil)
}

接收JSON格式请求

package main

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

// 接收json格式请求
func Hello(w http.ResponseWriter, r *http.Request) {
	var params map[string]string
	decode := json.NewDecoder(r.Body)
	decode.Decode(&params)
	io.WriteString(w, "name is:"+ params["name"])
}

func main() {
	http.HandleFunc("/hello", Hello)
	http.ListenAndServe(":9090", nil)
}

返回JSON数据

package main

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

// 接收json格式请求
func WriteJson(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Write([]byte(`{"name": "wanghaha", "age": 24}`))
}

func WriteJson2(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	info := map[string]interface{}{
		"name": "wanghaha",
		"age": 24,
	}
	json.NewEncoder(w).Encode(info)
}

func main() {
	http.HandleFunc("/hello", WriteJson)
	http.HandleFunc("/hello2", WriteJson2)
	http.ListenAndServe(":9090", nil)
}

返回HTML

package main

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

func Hello(w http.ResponseWriter, r *http.Request) {
	tpl, err := template.ParseFiles("templates/login.html")
	if err != nil {
		log.Fatal(err)
	}

	tpl.Execute(w, nil)
}

func main() {
	http.HandleFunc("/hello", Hello)
	http.ListenAndServe(":9090", nil)
}

模板继承

main.go

package main

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

func About(w http.ResponseWriter, r *http.Request) {
	tpl, err := template.ParseFiles("templates/base.html", "templates/about.html")
	if err != nil {
		log.Fatal(err)
	}

	err = tpl.ExecuteTemplate(w, "about.html", map[string]interface{}{
		"name": "王哈哈",
		"age": 24,
	})
	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	http.HandleFunc("/about", About)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal(err)
	}
}

templates/base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{block "title" .}}{{end}}</title>
</head>
<body>
    {{block "content" .}} {{end}}
</body>
</html>

templates/about.html

{{template "base.html" .}}
{{define "title"}}
    about
{{end}}

{{define "content"}}
    <h1>about page name: {{.name}}</h1>
{{end}}

上传文件

package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path"
	"strconv"
	"time"
)

func Upload(w http.ResponseWriter, r *http.Request) {
	file, handler, err := r.FormFile("file")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	// 获取文件后缀
	ext := path.Ext(handler.Filename)
	newFileName := time.Now().Format("20060102150405") + strconv.Itoa(time.Now().Nanosecond()) + ext

	f, err := os.OpenFile(newFileName, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	io.Copy(f, file)
	fmt.Fprintf(w, "upload %v success", newFileName)
}

func main() {
	http.HandleFunc("/upload", Upload)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal(err)
	}
}

中间件

package main

import (
	"net/http"
)

type Middleware func(w http.ResponseWriter, r *http.Request)

// 中间件
func middleware(next Middleware) http.HandlerFunc {
	return func(writer http.ResponseWriter, request *http.Request) {
		next(writer, request)
	}
}

// 视图函数
func Index(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hello world"))
}

func main() {
	http.HandleFunc("/", middleware(Index))
	http.ListenAndServe(":8090", nil)
}