package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
)
var cookies []*http.Cookie
var client = http.Client{}
func main() {
// 用戶客戶端程式登錄后,攜帶cookie,js-ajax跨域回傳資料
http.HandleFunc("/", getData)
// 用戶客戶端程式登錄后,攜帶cookie,重新定向URL頁面
http.HandleFunc("/login", doLogin)
http.ListenAndServe(":996", nil)
}
func doLogin(w http.ResponseWriter, r *http.Request) {
if login() {
http.SetCookie(w, cookies[0])
http.Redirect(w, r, "http://127.0.0.1:997/index#/home", http.StatusFound)
}
}
func getData(w http.ResponseWriter, r *http.Request) {
// 處理js-ajax跨域問題
w.Header().Set("Access-Control-Allow-Credentials", "true")
if login() {
resp2, err := client.Get("http://127.0.0.1:997/user/getTestData")
defer resp2.Body.Close()
if err != nil {
err := fmt.Errorf("登錄后發起Get請求時,client.Get錯誤:%v", err)
fmt.Println(err)
return
}
if resp2.StatusCode != 200 {
err := fmt.Errorf("登錄后發起Get請求時,response.StatusCode:%v", resp2.StatusCode)
fmt.Println(err)
return
}
body, err := ioutil.ReadAll(resp2.Body)
w.Write(body)
}
}
func login() bool {
form := url.Values{}
form.Set("username", "administrator")
form.Set("password", "xxxxx")
b := bytes.NewBufferString(form.Encode())
req, err := http.NewRequest("POST", "http://127.0.0.1:997/login", b)
if err != nil {
err := fmt.Errorf("登錄發起post請求時,http.NewRequest錯誤:%v", err)
fmt.Println(err)
return false
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
jar, err := cookiejar.New(nil)
if err != nil {
panic(err)
}
client.Jar = jar
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
err := fmt.Errorf("登錄發起post請求時,client.Do錯誤:%v", err)
fmt.Println(err)
return false
}
if resp.StatusCode != 200 {
err := fmt.Errorf("登錄發起post請求時,response.StatusCode:%v", resp.StatusCode)
fmt.Println(err)
return false
}
cookies = resp.Cookies()
return true
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/257507.html
標籤:區塊鏈
下一篇:位元幣BTC和以太坊ETH怎么挖
