1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"log"
"net/http"
"time"
)
var loginUrl = proxyUrl + "login/sms"
func LoggingHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
t1 := time.Now()
next.ServeHTTP(w, r)
t2 := time.Now()
log.Printf("[%s] %q %v", r.Method, r.URL.String(), t2.Sub(t1))
}
return http.HandlerFunc(fn)
}
func RecoverHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("Recover from panic: %+v", err)
http.Error(w, http.StatusText(500), 500)
}
}()
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func AuthHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, err := getAccessToken()
if err != nil {
log.Fatalln(err)
}
r.Header.Set("X-Auth-AppId", "10003")
r.Header.Set("X-Auth-Token", token)
next.ServeHTTP(w, r)
})
}
func getAccessToken() (string, error) {
params := map[string]string{
"phone": "15555555551",
"verifyCode": "888888",
"codeId": "111111",
}
marshal, _ := json.Marshal(params)
reader := bytes.NewReader(marshal)
request, _ := http.NewRequest("POST", loginUrl, reader)
request.Header.Add("X-Auth-AppId", "10003")
request.Header.Set("content-type", "application/json")
client := &http.Client{}
do, err := client.Do(request)
if err != nil {
return "", err
}
b, err := ioutil.ReadAll(do.Body)
if err != nil {
return "", err
}
_ = do.Body.Close()
result := &LoginResult{}
if err := json.Unmarshal(b, result); err != nil {
return "", err
}
if result.ErrCode != "0" {
return "", errors.New(result.Message)
}
return result.Data.Token, nil
}
type LoginResult struct {
ErrCode string
Message string
Data struct {
Name string
Token string
Phone string
}
}
|