Go语言后端api

API实例

前端

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
// 点击登录
$('.login').click(function () {
var user=$('.user').val();
var pass=$('.pass').val();
$.ajax({
type: 'post',
url:'http://'+location.host+'/api/system/login',
data:JSON.stringify({
params:{
UserName:(user),
Password:($.md5(pass).toUpperCase()),
ForceLogin:1
}
}),
success:function (msg) {
var data=msg;
// return
if (data.result == 0) {
sessionStorage.setItem('userName',user);
sessionStorage.setItem('token',data.params.Token);
alert('登录成功!');
}
}
})
});

后端

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
package auth

import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"strings"
)

var (
user = "userName"
password = "passWord"
urlLogin = `http://host/api/login`
)

//
type AutoLogin struct {
Method string `json:"method"`
Params struct {
UserName string `json:"UserName"`
Password string `json:"Password"`
Token string `json:"Token"`//token result:100
UserGroup string `json:"UserGroup"`
} `json:"params"`
Result int `json:"result"`
}

func AuthLogin() AutoLogin {
md5s := md5EncodeToUp()
password = md5s
return authLogin()
}

// md5加密 转大写
func md5EncodeToUp() string {
h := md5.New()
h.Write([]byte("你的登录密码"))
hs := h.Sum(nil)
md5s := hex.EncodeToString(hs)
md5s = strings.ToUpper(md5s)
return md5s
}

//用户名密码登录 获取token
func authLogin() AutoLogin {
params := &AutoLogin{}
params.Params.UserName = user
params.Params.Password = password
info, err := json.Marshal(&params)

if err != nil {
log.Fatal("json Marshal:", err)
}

req, err := http.NewRequest("POST", urlLogin, strings.NewReader(string(info)))
if err != nil {
log.Fatal("new post request:", err)
}

req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Expect", "100-continue")//Result:100


client := http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal("client Do", err)
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)

var login AutoLogin
err = json.Unmarshal(body, &login)
if err != nil {
log.Fatal("json Unmarshal:", err)
}
//fmt.Printf("authLogin: %+v\n", login)

return login

}

test

1
2
3
4
5
6
7
8
9
package auth

import "testing"

// go test --run TestAuthLogin
func TestAuthLogin(t *testing.T) {
AuthLogin()

}

单元测试

del_p.go

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
package delp

import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)

var url = `http://host/api/delp`

type Obj struct {
Params struct {
Pid string `json:"Pid"`
} `json:"params"`
Token string `json:"Token"`
}

func DelP(pid, token string) {
obj := &Obj{}
obj.Params.Pid = pid
obj.Token = token

info, err := json.Marshal(obj)
if err != nil {
log.Fatal("Marshal:", err)
}
req, err := http.NewRequest("POST", url, strings.NewReader(string(info)))
if err != nil {
log.Fatal("req:", err)
}

client := http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal("client do:", err)
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("body:", err)
}
var delp DelPObj
err = json.Unmarshal(body, &delp)
if err != nil {
log.Fatal("Unmarshal:", err)
}
fmt.Printf("%+v\n", delp)

}

type DelPObj struct {
Method string `json:"method"`
Params Params `json:"params"`
}

type Params struct {
DepartID int64 `json:"DepartID"`
Offset int64 `json:"Offset"`
PersonCount int64 `json:"PersonCount"`
Persons []Person `json:"Persons"`
Result int64 `json:"result"`
}

type Person struct {
Authority int64 `json:"Authority"`
DepartID int64 `json:"DepartID"`
Password string `json:"Password"`
Pid string `json:"Pid"`
Pid2 string `json:"Pid2"`
PersonName string `json:"PersonName"`
workId string `json:"workId"`
}

go test –run TestDelP

del_p_test.go

1
2
3
4
5
6
7
8
9
10
11
12
13
package delp

import (
"auth"
"testing"
)

func TestDelP(t *testing.T) {
obj := auth.AuthLogin()
token := obj.Params.Token
pid := "foobarfoobarfoobar"
DelP(pid, token)
}

bwg

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
89
90
91
92
93
94
95
96
97
98
99
100

//Returns
//[OVZ hypervisor]
//vz_status: array containing OpenVZ beancounters, system load average, number of processes, open files, sockets, memory usage etc
//vz_quota: array containing OpenVZ disk size, inodes and usage info
//is_cpu_throttled: 0 = CPU is not throttled, 1 = CPU is throttled due to high usage. Throttling resets automatically every 2 hours.
//ssh_port: SSH port of the VPS
//
//Returns
//[KVM hypervisor]
//ve_status: Starting, Running or Stopped
//ve_mac1: MAC address of primary network interface
//ve_used_disk_space_b: Occupied (mapped) disk space in bytes
//ve_disk_quota_gb: Actual size of disk image in GB
//is_cpu_throttled: 0 = CPU is not throttled, 1 = CPU is throttled due to high usage. Throttling resets automatically every 2 hours.
//is_disk_throttled: 0 = Disk I/O is not throttled, 1 = Disk I/O is throttled due to high usage. Throttling resets automatically every 15-180 minutes depending on sustained storage I/O utilization.
//ssh_port: SSH port of the VPS (returned only if VPS is running)
//live_hostname: Result of "hostname" command executed inside VPS
//load_average: Raw load average string
//mem_available_kb: Amount of available RAM in KB
//swap_total_kb: Total amount of Swap in KB
//swap_available_kb: Amount of available Swap in KB
//screendump_png_base64: base64 encoded png screenshot of the VGA console
type LiveServiceInfo struct {
Vm_type string `json:"vm_type"`
VeStatus string `json:"ve_status"`
VeMac1 string `json:"ve_mac1"`
VeUsedDiskSpaceB int `json:"ve_used_disk_space_b"`
VeDiskQuotaGb string `json:"ve_disk_quota_gb"`
IsCpuThrottled string `json:"is_cpu_throttled"`
IsDiskThrottled string `json:"is_disk_throttled"`
SshPort int `json:"ssh_port"`
LiveHostName string `json:"live_hostname"`
LoadAverage string `json:"load_average"`
MemAvailableKb int `json:"mem_available_kb"`
SwapTotalKb int `json:"swap_total_kb"`
SwapAvailableKb int `json:"swap_available_kb"`
ScreendumpPngBase64 string `json:"screendump_png_base64"`
//
Hostname string `json:"hostname"`
Node_ip string `json:"node_ip"`
Node_alias string `json:"node_alias"`
Node_location string `json:"node_location"`
Node_location_id string `json:"node_location_id"`
Node_datacenter string `json:"node_datacenter"`
Location_ipv6_ready bool `json:"location_ipv6_ready"`
Plan string `json:"plan"`
Plan_monthly_data int64 `json:"plan_monthly_data"`
Monthly_data_multiplier int `json:"monthly_data_multiplier"`
Plan_disk int64 `json:"plan_disk"`
Plan_ram int64 `json:"plan_ram"`
Plan_swap int `json:"plan_swap"`
Plan_max_ipv6s int `json:"plan_max_ipv6s"`
Os string `json:"os"`
Email string `json:"email"`
Data_counter int64 `json:"data_counter"`
Data_next_reset int64 `json:"data_next_reset"`
Ip_addresses []string `json:"ip_addresses"`
Rdns_api_available bool `json:"rdns_api_available"`
Suspended bool `json:"suspended"`
Ptr string `json:"-"`
Error int `json:"error"`
}

//This function returns all data provided by getServiceInfo. In addition, it provides detailed status of the VPS.
//Please note that this call may take up to 15 seconds to complete.
//Depending on hypervisor this call will return the following information:
// getLiveServiceInfo
func GetLiveServiceInfo(id, key string) LiveServiceInfo {
url := "https://api.64clouds.com/v1/getLiveServiceInfo?veid=" + id + "&api_key=" + key
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println("req:", err)
}

client := http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("resp:", err)
}

defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Println("read:", err)
}
}(resp.Body)

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("body:", err)
}
var result LiveServiceInfo

err = json.Unmarshal(body, &result)
if err != nil {
log.Println("Unmarshal:", err)
}
return result
}
  • go test –run TestGetLiveServiceInfo
    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
    func TestGetLiveServiceInfo(t *testing.T) {
    id := "1223445"
    key := "private_avfrdgdsdf"

    result := GetLiveServiceInfo(id, key)
    //控制台图片输出...
    //Base64StringToPng(result.ScreendumpPngBase64)

    fmt.Printf(
    "Vm_type:%v\n"+
    "ve_status:%v\nve_mac1:%v\nve_used_disk_space_b:%v\nve_disk_quota_gb:%v\nis_cpu_throttled:%v\nis_disk_throttled:%v\n"+
    "ssh_port:%v\nlive_hostname:%v\n"+
    "load_average:%v\nmem_available_kb:%v\nswap_total_kb:%v\nswap_available_kb:%v\nscreendump_png_base64:%v\n"+
    "Hostname:%v\n"+
    "Node_ip:%v\nNode_alias:%v\nNode_location:%v\nNode_location_id:%v\nNode_datacenter:%v\n"+
    "Location_ipv6_ready:%v\nPlan:%v\nPlan_monthly_data:%v\nMonthly_data_multiplier Plan_disk:%v\nPlan_ram:%v\nPlan_swap:%v\n"+
    "Plan_max_ipv6s:%v %v\nOs:%v\nEmail:%v\nData_counter:%v\nData_next_reset:%v\nIp_addresses:%v\nRdns_api_available:%v\n"+
    "Suspended:%v\nPtr:%v\nError:%v\nS",
    result.Vm_type,
    //
    result.VeStatus,
    result.VeMac1,
    result.VeUsedDiskSpaceB,
    result.VeDiskQuotaGb,
    result.IsCpuThrottled,
    result.IsDiskThrottled,
    result.SshPort,
    result.LiveHostName,
    result.LoadAverage,
    result.MemAvailableKb,
    result.SwapTotalKb,
    result.SwapAvailableKb,
    result.ScreendumpPngBase64,
    //
    result.Hostname,
    result.Node_ip,
    result.Node_alias,
    result.Node_location,
    result.Node_location_id,
    result.Node_datacenter,
    result.Location_ipv6_ready,
    result.Plan,
    result.Plan_monthly_data,
    result.Monthly_data_multiplier,
    result.Plan_disk,
    result.Plan_ram,
    result.Plan_swap,
    result.Plan_max_ipv6s,
    result.Os,
    result.Email,
    result.Data_counter,
    result.Data_next_reset,
    result.Ip_addresses,
    result.Rdns_api_available,
    result.Suspended,
    result.Ptr,
    result.Error)
    }


Paste JSON as Code

推荐文章