1. 程式人生 > >Golang Http Middleware 判斷 增加cookie

Golang Http Middleware 判斷 增加cookie

原始碼:

package main

import (
	"fmt"
	"net/http"

	. "github.com/soekchl/myUtils"
)

func main() {
	finalHandler := http.HandlerFunc(final) // 設定最後訪問

	http.Handle("/", middleware(finalHandler)) // 設定中介軟體

	if err := http.ListenAndServe(":8088", nil); err != nil {
		Error(err)
		return
	}
}

func final(w http.ResponseWriter, r *http.Request) {
	Info("final handler")
	fmt.Fprintln(w, "final")
}

func middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		Info("middleware handler")

		id := r.FormValue("id") // 判斷是否有 id 和 passwd 變數
		passwd := r.FormValue("passwd")

		if id == "" { // 沒有先從cookie 獲取
			c, err := r.Cookie("id")
			if err == nil {
				id = c.Value
			}
		}

		if passwd == "" {
			c, err := r.Cookie("passwd")
			if err == nil {
				passwd = c.Value
			}
		}

		if id == "admin" && passwd == "123456" { // 賬號密碼判斷
			cookie := http.Cookie{Name: "id", Value: id, Path: "/", MaxAge: 86400}
			http.SetCookie(w, &cookie)
			cookie = http.Cookie{Name: "passwd", Value: passwd, Path: "/", MaxAge: 86400}
			http.SetCookie(w, &cookie)

			next.ServeHTTP(w, r) // 跳轉
		} else {
			fmt.Fprintln(w, "Id or Passwd is Error!") // 不滿足條件
		}

		Info("middleware over") // 中介軟體結束
	})
}


訪問地址:http://localhost:8088/?id=admin&passwd=123456