parent
556b089a60
commit
15d412e903
8 changed files with 146 additions and 81 deletions
@ -0,0 +1,33 @@ |
||||
package protogen |
||||
|
||||
import ( |
||||
"github.com/golang/protobuf/proto" |
||||
"google.golang.org/genproto/googleapis/api/annotations" |
||||
"google.golang.org/protobuf/compiler/protogen" |
||||
"google.golang.org/protobuf/types/descriptorpb" |
||||
) |
||||
|
||||
const ( |
||||
METHOD_GET = "GET" |
||||
METHOD_POST = "POST" |
||||
METHOD_DELETE = "DELETE" |
||||
) |
||||
|
||||
func GetProtoMethod(m *protogen.Method) (method string, path string) { |
||||
if op, ok := m.Desc.Options().(*descriptorpb.MethodOptions); ok { |
||||
if opts, err := proto.GetExtension(op, annotations.E_Http); err != nil { |
||||
//log.Println(err)
|
||||
} else { |
||||
if vv, ok := opts.(*annotations.HttpRule); ok { |
||||
if vvv, ok := vv.Pattern.(*annotations.HttpRule_Get); ok { |
||||
return METHOD_GET, vvv.Get |
||||
} else if vvv, ok := vv.Pattern.(*annotations.HttpRule_Post); ok { |
||||
return METHOD_POST, vvv.Post |
||||
} else if vvv, ok := vv.Pattern.(*annotations.HttpRule_Delete); ok { |
||||
return METHOD_DELETE, vvv.Delete |
||||
} |
||||
} |
||||
} |
||||
} |
||||
return "", "" |
||||
} |
Binary file not shown.
@ -0,0 +1,54 @@ |
||||
//复制时倒入qs
|
||||
// @ts-ignore
|
||||
import qs from "qs"; |
||||
|
||||
const API_SERVER = process.env.NEXT_PUBLIC_WEB_SITE |
||||
|
||||
export interface Config<T> extends RequestInit { |
||||
token?: string |
||||
data?: T |
||||
method?: 'POST' | 'GET' |
||||
} |
||||
|
||||
interface IError { |
||||
status: number |
||||
details: [], |
||||
message: string |
||||
metadata: any |
||||
reason: string |
||||
} |
||||
|
||||
const http = async <T, V>(endpoint: string, {data, token, headers, ...customConfig}: Config<T>) => { |
||||
const config = { |
||||
method: "GET", |
||||
headers: { |
||||
Authorization: token ? `Bearer ${token}` : '', |
||||
'Content-type': data ? 'application/json' : '', |
||||
}, |
||||
...customConfig |
||||
} |
||||
if (config.method.toUpperCase() === "GET") { |
||||
endpoint += `?${qs.stringify(data)}` |
||||
} else { |
||||
config.body = JSON.stringify(data || {}) |
||||
} |
||||
console.log(API_SERVER + endpoint, token) |
||||
return fetch(API_SERVER + endpoint, config).then(async response => { |
||||
if (response.status == 401) { |
||||
if (typeof window != 'undefined') { |
||||
// window.location.reload();
|
||||
} |
||||
return Promise.reject({message: "请重新登录", status: 401}) |
||||
} |
||||
const data = await response.json(); |
||||
if (response.ok) { |
||||
return data as V; |
||||
} else { |
||||
return Promise.reject(data as IError); |
||||
} |
||||
}) |
||||
} |
||||
|
||||
export { |
||||
http |
||||
} |
Loading…
Reference in new issue