備忘錄_20160105(定位) 修改 回首頁

程式 2018-07-03 12:16:01 1530591361 100
Golang 撰寫 web service 可處理 session,login,logout

Golang 撰寫 web service 可處理 session,login,logout
  1. 安裝 GO (https://golang.org)
  2. 安裝 GIT (https://git-scm.com)
  3. 在 GIT 的 Command 視窗中,執行 go get github.com/gorilla/sessions
  4. 在 c:\users\使用者名稱\go\src\hello 中撰寫程式碼,然後 go build ,可以得到 hello.exe 檔案
------------------------------------
hello.go
------------------------------------

// sessions.go
package main

import (
	"fmt"
	"net/http"
	"github.com/gorilla/sessions"
)

var (
	// key must be 16, 24 or 32 bytes long (AES-128, AES-192 or AES-256)
	key = []byte("super-secret-key")
	store = sessions.NewCookieStore(key)
)

func secret(w http.ResponseWriter, r *http.Request) {
	session, _ := store.Get(r, "cookie-name")

	// Check if user is authenticated
	if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}

	// Print secret message
	fmt.Fprintln(w, "Mission Impossible!")
}

func login(w http.ResponseWriter, r *http.Request) {
	session, _ := store.Get(r, "cookie-name")

	// Authentication goes here
	// ...

	// Set user as authenticated
	session.Values["authenticated"] = true
	session.Save(r, w)
}

func logout(w http.ResponseWriter, r *http.Request) {
	session, _ := store.Get(r, "cookie-name")

	// Revoke users authentication
	session.Values["authenticated"] = false
	session.Save(r, w)
}

func main() {
	http.HandleFunc("/secret", secret)
	http.HandleFunc("/login", login)
	http.HandleFunc("/logout", logout)

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