added openi apis

This commit is contained in:
tzwang 2024-12-05 16:04:19 +08:00
parent 06a0071d5f
commit 547831609c
21 changed files with 802 additions and 0 deletions

1
apis/dataset.go Normal file
View File

@ -0,0 +1 @@
package apis

42
apis/image.go Normal file
View File

@ -0,0 +1,42 @@
package apis
import (
"github.com/gin-gonic/gin"
"net/http"
"pcm-openi/common"
"pcm-openi/model"
)
func GetImageRecommended(ctx *gin.Context) {
token := ctx.Query(common.ACCESSTOKEN)
var param model.ImageRecommendedParam
if err := ctx.BindJSON(&param); err != nil {
model.Response(ctx, http.StatusBadRequest, common.INVALIDPARAMS, err)
return
}
reqUrl := common.OPENIPREFIX + common.IMAGERECOMMENDED
var resp model.ImageRecommended
req := common.GetRestyRequest(common.TIMEOUT)
_, err := req.
SetQueryParam(common.ACCESSTOKEN, token).
SetQueryParam("", param.Python).
SetQueryParam("", param.Python).
SetQueryParam("", param.Python).
SetQueryParam("", param.Python).
SetQueryParam("", param.Python).
SetQueryParam("", param.Python).
SetQueryParam("", param.Python).
SetResult(&resp).
Get(reqUrl)
if err != nil {
model.Response(ctx, 500, common.INVOKEERROR, err)
return
}
model.Response(ctx, http.StatusOK, common.SUCCESS, resp)
}

57
apis/repo.go Normal file
View File

@ -0,0 +1,57 @@
package apis
import (
"github.com/gin-gonic/gin"
"net/http"
"pcm-openi/common"
"pcm-openi/model"
)
func GetRepos(ctx *gin.Context) {
token := ctx.Query(common.ACCESSTOKEN)
reqUrl := common.OPENIPREFIX + common.REPO
var resp []model.Repo
req := common.GetRestyRequest(common.TIMEOUT)
_, err := req.
SetQueryParam(common.ACCESSTOKEN, token).
SetResult(&resp).
Get(reqUrl)
if err != nil {
model.Response(ctx, 500, common.INVOKEERROR, err)
return
}
model.Response(ctx, http.StatusOK, common.SUCCESS, resp)
}
func CreateRepo(ctx *gin.Context) {
var param model.RepoCreateParam
if err := ctx.BindJSON(&param); err != nil {
model.Response(ctx, http.StatusBadRequest, common.INVALIDPARAMS, err)
return
}
token := ctx.Query(common.ACCESSTOKEN)
reqUrl := common.OPENIPREFIX + common.REPO
var resp model.Repo
req := common.GetRestyRequest(common.TIMEOUT)
_, err := req.
SetQueryParam(common.ACCESSTOKEN, token).
SetBody(&param).
SetResult(&resp).
Post(reqUrl)
if err != nil {
model.Response(ctx, 500, common.INVOKEERROR, err)
return
}
model.Response(ctx, http.StatusOK, common.SUCCESS, resp)
}

40
apis/task.go Normal file
View File

@ -0,0 +1,40 @@
package apis
import (
"github.com/gin-gonic/gin"
"net/http"
"pcm-openi/common"
"pcm-openi/model"
)
func GetTaskCreationRequired(ctx *gin.Context) {
token := ctx.Query(common.ACCESSTOKEN)
reqUrl := common.OPENIPREFIX + common.TASKCREATIONREQUIRED
var resp model.TaskCreationRequired
var param model.TaskCreationRequiredParam
if err := ctx.BindJSON(&param); err != nil {
model.Response(ctx, http.StatusBadRequest, common.INVALIDPARAMS, err)
return
}
req := common.GetRestyRequest(common.TIMEOUT)
_, err := req.
SetQueryParam(common.ACCESSTOKEN, token).
SetQueryParam("job_type", param.JobType).
SetQueryParam("compute_source", param.ComputeSource).
SetQueryParam("cluster_type", param.ClusterType).
SetPathParam("username", param.UserName).
SetPathParam("reponame", param.RepoName).
SetResult(&resp).
Get(reqUrl)
if err != nil {
model.Response(ctx, 500, common.INVOKEERROR, err)
return
}
model.Response(ctx, http.StatusOK, common.SUCCESS, resp)
}

16
apis/test.go Normal file
View File

@ -0,0 +1,16 @@
package apis
import (
"github.com/gin-gonic/gin"
"pcm-openi/model"
)
type TestApi struct {
}
func (t *TestApi) TestASD(ctx *gin.Context) {
ctx.JSON(200, model.ASD{
Asd: "asd",
Zxc: "zxc",
})
}

31
apis/user.go Normal file
View File

@ -0,0 +1,31 @@
package apis
import (
"github.com/gin-gonic/gin"
"pcm-openi/common"
"pcm-openi/model"
)
func GetUserInfo(ctx *gin.Context) {
token := ctx.Query(common.ACCESSTOKEN)
reqUrl := common.OPENIPREFIX + common.USERINFO
resp := &model.UserInfo{}
req := common.GetRestyRequest(common.TIMEOUT)
_, err := req.
SetQueryParam(common.ACCESSTOKEN, token).
SetResult(resp).
Get(reqUrl)
if err != nil {
ctx.JSON(500, model.Error{
Error: err.Error(),
})
return
}
ctx.JSON(200, resp)
}

10
app.go Normal file
View File

@ -0,0 +1,10 @@
package main
import (
"pcm-openi/router"
)
func main() {
rt, _ := router.Create(nil)
_ = rt.Run(":8082")
}

42
common/const.go Normal file
View File

@ -0,0 +1,42 @@
package common
const (
TIMEOUT = 10
OPENIPREFIX = "https://openi.pcl.ac.cn"
ACCESSTOKEN = "access_token"
// user
USERINFO = "/api/v1/user"
// repo
REPO = "/api/v1/user/repos"
// image
IMAGERECOMMENDED = "/api/v1/images/recommend"
IMAGECUSTOM = "/api/v1/images/custom"
IMAGESTARED = "/api/v1/images/star"
// datasets
DATASETCURRENT = "/api/v1/datasets/{username}/{reponame}/current_repo" //查询当前项目的数据集接口
DATASETMINE = "/api/v1/datasets/{username}/{reponame}/my_datasets" //我上传的数据集
DATASETPUBLIC = "/api/v1/datasets/{username}/{reponame}/public_datasets" //查询公开数据集
DATASETFAVORITE = "/api/v1/datasets/{username}/{reponame}/my_favorite" //查询我收藏的数据集
// task
TASKCREATIONREQUIRED = "/api/v1/{username}/{reponame}/ai_task/creation/required" // 查询创建任务所需资源接口
TASKIMAGEBYSPECFORNPN = "/api/v1/{username}/{reponame}/ai_task/creation/image_by_spec" // 根据选择的规格获取镜像计算资源是NPU时使用
TASKCREATE = "/api/v1/{username}/{reponame}/ai_task/create" // 创建任务
TASKDETAIL = "/api/v1/repos/{username}/{reponame}/ai_task" // 查询任务详情
TASKSTOP = " /api/v1/{username}/{reponame}/ai_task/stop" // 停止任务接口
TASKOUTPUT = "/api/v1/{username}/{reponame}/ai_task/output" // 查询结果列表接口
TASKRESULTDOWNLOAD = "/api/v1/{username}/{reponame}/ai_task/output/download/all" // 所有结果下载接口
)
const (
SUCCESS = "success"
)
// error
const (
INVOKEERROR = "failed to invoke"
INVALIDPARAMS = "invalid request params"
)

12
common/util.go Normal file
View File

@ -0,0 +1,12 @@
package common
import (
"github.com/go-resty/resty/v2"
"time"
)
func GetRestyRequest(timeoutSeconds int64) *resty.Request {
client := resty.New().SetTimeout(time.Duration(timeoutSeconds) * time.Second)
request := client.R()
return request
}

4
config/config.go Normal file
View File

@ -0,0 +1,4 @@
package config
type Configuration struct {
}

64
err/handler.go Normal file
View File

@ -0,0 +1,64 @@
package err
import (
"fmt"
"net/http"
"pcm-openi/model"
"strings"
"unicode"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
)
// Handler creates a gin middleware for handling errors.
func Handler() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if len(c.Errors) > 0 {
for _, e := range c.Errors {
switch e.Type {
case gin.ErrorTypeBind:
errs, ok := e.Err.(validator.ValidationErrors)
if !ok {
writeError(c, e.Error())
return
}
var stringErrors []string
for _, err := range errs {
stringErrors = append(stringErrors, validationErrorToText(err))
}
writeError(c, strings.Join(stringErrors, "; "))
default:
writeError(c, e.Err.Error())
}
}
}
}
}
func validationErrorToText(e validator.FieldError) string {
runes := []rune(e.Field())
runes[0] = unicode.ToLower(runes[0])
fieldName := string(runes)
switch e.Tag() {
case "required":
return fmt.Sprintf("Field '%s' is required", fieldName)
case "max":
return fmt.Sprintf("Field '%s' must be less or equal to %s", fieldName, e.Param())
case "min":
return fmt.Sprintf("Field '%s' must be more or equal to %s", fieldName, e.Param())
}
return fmt.Sprintf("Field '%s' is not valid", fieldName)
}
func writeError(ctx *gin.Context, errString string) {
status := http.StatusBadRequest
if ctx.Writer.Status() != http.StatusOK {
status = ctx.Writer.Status()
}
ctx.JSON(status, &model.Error{Error: http.StatusText(status), ErrorCode: status, ErrorDescription: errString})
}

57
go.mod Normal file
View File

@ -0,0 +1,57 @@
module pcm-openi
go 1.23.0
require (
github.com/gin-gonic/gin v1.9.0
github.com/go-playground/validator/v10 v10.11.2
github.com/go-resty/resty/v2 v2.10.0
)
require (
github.com/bytedance/sonic v1.8.0 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/creack/pty v1.1.9 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/assert/v2 v2.2.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/goccy/go-json v0.10.0 // indirect
github.com/golang/protobuf v1.5.0 // indirect
github.com/google/go-cmp v0.5.5 // indirect
github.com/google/gofuzz v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.0.9 // indirect
github.com/kr/pretty v0.3.0 // indirect
github.com/kr/pty v1.1.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rogpeppe/go-internal v1.8.0 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/stretchr/testify v1.8.1 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.9 // indirect
github.com/yuin/goldmark v1.4.13 // indirect
golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect
golang.org/x/crypto v0.14.0 // indirect
golang.org/x/mod v0.8.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/sync v0.1.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/term v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
golang.org/x/tools v0.6.0 // indirect
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/errgo.v2 v2.1.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
rsc.io/pdf v0.1.1 // indirect
)

24
model/error.go Normal file
View File

@ -0,0 +1,24 @@
package model
// Error Model
//
// The Error contains error relevant information.
//
// swagger:model Error
type Error struct {
// The general error message
//
// required: true
// example: Unauthorized
Error string `json:"error"`
// The http error code.
//
// required: true
// example: 401
ErrorCode int `json:"errorCode"`
// The http error code.
//
// required: true
// example: you need to provide a valid access token or user credentials to access this api
ErrorDescription string `json:"errorDescription"`
}

63
model/image.go Normal file
View File

@ -0,0 +1,63 @@
package model
type ImageRecommended struct {
Count int `json:"count"`
Images []Image `json:"images"`
}
type Image struct {
Id int `json:"id"`
ImageId string `json:"image_id"`
Type int `json:"type"`
CloudbrainType int `json:"cloudbrainType"`
Uid int `json:"uid"`
IsPrivate bool `json:"isPrivate"`
Tag string `json:"tag"`
Description string `json:"description"`
Topics []string `json:"topics"`
Place string `json:"place"`
NumStars int `json:"numStars"`
ComputeResource string `json:"compute_resource"`
IsStar bool `json:"isStar"`
UserName string `json:"userName"`
RelAvatarLink string `json:"relAvatarLink"`
Status int `json:"status"`
ApplyStatus int `json:"apply_status"`
Message string `json:"message"`
UseCount int `json:"useCount"`
Framework string `json:"framework"`
FrameworkVersion string `json:"frameworkVersion"`
CudaVersion string `json:"cudaVersion"`
PythonVersion string `json:"pythonVersion"`
OperationSystem string `json:"operationSystem"`
OperationSystemVersion string `json:"operationSystemVersion"`
ThirdPackages string `json:"thirdPackages"`
AiCenterImages []struct {
AiCenterId string `json:"aiCenterId"`
ImageUrl string `json:"imageUrl"`
ImageId string `json:"imageId"`
AccDeviceModel string `json:"accDeviceModel"`
PoolIds interface{} `json:"poolIds"`
} `json:"AiCenterImages"`
GrampusBaseImage int `json:"grampusBaseImage"`
TrainType string `json:"trainType"`
HuJingId string `json:"huJingId"`
ProcessorType string `json:"processorType"`
AccCardType string `json:"accCardType"`
CreatedUnix int `json:"createdUnix"`
UpdatedUnix int `json:"updatedUnix"`
}
type ImageRecommendedParam struct {
Q string `json:"q"`
CloudbrainType int `json:"cloudbrainType"`
ComputeResource string `json:"computeResource"`
Spec int `json:"spec"`
TrainType string `json:"trainType"`
Framework string `json:"framework"`
FrameworkVersion string `json:"frameworkVersion"`
Cuda string `json:"cuda"`
Python string `json:"python"`
Page int `json:"page"`
PageSize int `json:"pageSize"`
}

142
model/repo.go Normal file
View File

@ -0,0 +1,142 @@
package model
import "time"
type Repo struct {
Id int `json:"id"`
Owner struct {
Id int `json:"id"`
Login string `json:"login"`
FullName string `json:"full_name"`
Email string `json:"email"`
AvatarUrl string `json:"avatar_url"`
Language string `json:"language"`
IsAdmin bool `json:"is_admin"`
IsActive bool `json:"is_active"`
LastLogin time.Time `json:"last_login"`
Created time.Time `json:"created"`
Username string `json:"username"`
} `json:"owner"`
Name string `json:"name"`
Alias string `json:"alias"`
FullName string `json:"full_name"`
FullDisplayName string `json:"full_display_name"`
Description string `json:"description"`
Empty bool `json:"empty"`
Private bool `json:"private"`
Fork bool `json:"fork"`
Template bool `json:"template"`
Parent struct {
Id int `json:"id"`
Owner struct {
Id int `json:"id"`
Login string `json:"login"`
FullName string `json:"full_name"`
Email string `json:"email"`
AvatarUrl string `json:"avatar_url"`
Language string `json:"language"`
IsAdmin bool `json:"is_admin"`
IsActive bool `json:"is_active"`
LastLogin time.Time `json:"last_login"`
Created time.Time `json:"created"`
Username string `json:"username"`
} `json:"owner"`
Name string `json:"name"`
Alias string `json:"alias"`
FullName string `json:"full_name"`
FullDisplayName string `json:"full_display_name"`
Description string `json:"description"`
Empty bool `json:"empty"`
Private bool `json:"private"`
Fork bool `json:"fork"`
Template bool `json:"template"`
Parent interface{} `json:"parent"`
Mirror bool `json:"mirror"`
Size int `json:"size"`
HtmlUrl string `json:"html_url"`
SshUrl string `json:"ssh_url"`
CloneUrl string `json:"clone_url"`
OriginalUrl string `json:"original_url"`
Website string `json:"website"`
StarsCount int `json:"stars_count"`
ForksCount int `json:"forks_count"`
WatchersCount int `json:"watchers_count"`
OpenIssuesCount int `json:"open_issues_count"`
OpenPrCounter int `json:"open_pr_counter"`
ReleaseCounter int `json:"release_counter"`
DefaultBranch string `json:"default_branch"`
Archived bool `json:"archived"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Permissions struct {
Admin bool `json:"admin"`
Push bool `json:"push"`
Pull bool `json:"pull"`
} `json:"permissions"`
HasIssues bool `json:"has_issues"`
InternalTracker struct {
EnableTimeTracker bool `json:"enable_time_tracker"`
AllowOnlyContributorsToTrackTime bool `json:"allow_only_contributors_to_track_time"`
EnableIssueDependencies bool `json:"enable_issue_dependencies"`
} `json:"internal_tracker"`
HasWiki bool `json:"has_wiki"`
HasPullRequests bool `json:"has_pull_requests"`
IgnoreWhitespaceConflicts bool `json:"ignore_whitespace_conflicts"`
AllowMergeCommits bool `json:"allow_merge_commits"`
AllowRebase bool `json:"allow_rebase"`
AllowRebaseExplicit bool `json:"allow_rebase_explicit"`
AllowSquashMerge bool `json:"allow_squash_merge"`
AvatarUrl string `json:"avatar_url"`
Status int `json:"status"`
} `json:"parent"`
Mirror bool `json:"mirror"`
Size int `json:"size"`
HtmlUrl string `json:"html_url"`
SshUrl string `json:"ssh_url"`
CloneUrl string `json:"clone_url"`
OriginalUrl string `json:"original_url"`
Website string `json:"website"`
StarsCount int `json:"stars_count"`
ForksCount int `json:"forks_count"`
WatchersCount int `json:"watchers_count"`
OpenIssuesCount int `json:"open_issues_count"`
OpenPrCounter int `json:"open_pr_counter"`
ReleaseCounter int `json:"release_counter"`
DefaultBranch string `json:"default_branch"`
Archived bool `json:"archived"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Permissions struct {
Admin bool `json:"admin"`
Push bool `json:"push"`
Pull bool `json:"pull"`
} `json:"permissions"`
HasIssues bool `json:"has_issues"`
InternalTracker struct {
EnableTimeTracker bool `json:"enable_time_tracker"`
AllowOnlyContributorsToTrackTime bool `json:"allow_only_contributors_to_track_time"`
EnableIssueDependencies bool `json:"enable_issue_dependencies"`
} `json:"internal_tracker"`
HasWiki bool `json:"has_wiki"`
HasPullRequests bool `json:"has_pull_requests"`
IgnoreWhitespaceConflicts bool `json:"ignore_whitespace_conflicts"`
AllowMergeCommits bool `json:"allow_merge_commits"`
AllowRebase bool `json:"allow_rebase"`
AllowRebaseExplicit bool `json:"allow_rebase_explicit"`
AllowSquashMerge bool `json:"allow_squash_merge"`
AvatarUrl string `json:"avatar_url"`
Status int `json:"status"`
}
type RepoCreateParam struct {
AutoInit bool `json:"auto_init"`
DefaultBranch string `json:"default_branch"`
Description string `json:"description"`
Gitignores string `json:"gitignores"`
IssueLabels string `json:"issue_labels"`
License string `json:"license"`
Name string `json:"name"`
Alias string `json:"alias"`
Private bool `json:"private"`
Readme string `json:"readme"`
}

15
model/resp.go Normal file
View File

@ -0,0 +1,15 @@
package model
import (
"github.com/gin-gonic/gin"
"net/http"
)
func Response(c *gin.Context, code int, msg interface{}, data interface{}) {
c.JSON(http.StatusOK, map[string]interface{}{
"code": code,
"msg": msg,
"data": data,
})
return
}

74
model/task.go Normal file
View File

@ -0,0 +1,74 @@
package model
type TaskCreationRequired struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Specs struct {
All []struct {
Id int `json:"id"`
AccCardsNum int `json:"acc_cards_num"`
AccCardType string `json:"acc_card_type"`
CpuCores int `json:"cpu_cores"`
MemGiB int `json:"mem_gi_b"`
GpuMemGiB int `json:"gpu_mem_gi_b"`
ShareMemGiB int `json:"share_mem_gi_b"`
ComputeResource string `json:"compute_resource"`
UnitPrice int `json:"unit_price"`
SourceSpecId string `json:"source_spec_id"`
HasInternet int `json:"has_internet"`
EnableVisualization bool `json:"enable_visualization"`
} `json:"all"`
HasInternet []struct {
Id int `json:"id"`
AccCardsNum int `json:"acc_cards_num"`
AccCardType string `json:"acc_card_type"`
CpuCores int `json:"cpu_cores"`
MemGiB int `json:"mem_gi_b"`
GpuMemGiB int `json:"gpu_mem_gi_b"`
ShareMemGiB int `json:"share_mem_gi_b"`
ComputeResource string `json:"compute_resource"`
UnitPrice int `json:"unit_price"`
SourceSpecId string `json:"source_spec_id"`
HasInternet int `json:"has_internet"`
EnableVisualization bool `json:"enable_visualization"`
} `json:"has_internet"`
NoInternet []interface{} `json:"no_internet"`
} `json:"specs"`
Images []struct {
ImageId string `json:"image_id"`
ImageName string `json:"image_name"`
ImageUrl string `json:"image_url"`
} `json:"images"`
CanUseAllImages bool `json:"can_use_all_images"`
Branches []string `json:"branches"`
DefaultBranch string `json:"default_branch"`
WaitCount int `json:"wait_count"`
NotStopTaskCount int `json:"not_stop_task_count"`
CanCreateMore bool `json:"can_create_more"`
DisplayJobName string `json:"display_job_name"`
PointAccount struct {
AccountCode string `json:"account_code"`
Balance int `json:"balance"`
TotalEarned int `json:"total_earned"`
TotalConsumed int `json:"total_consumed"`
} `json:"point_account"`
PaySwitch bool `json:"pay_switch"`
Config struct {
DatasetMaxSize int `json:"dataset_max_size"`
DatasetMaxNum int `json:"dataset_max_num"`
ModelMaxSize int `json:"model_max_size"`
ModelMaxNum int `json:"model_max_num"`
} `json:"config"`
AllowedWorkerNum []int `json:"allowed_worker_num"`
IsSubscriber bool `json:"is_subscriber"`
} `json:"data"`
}
type TaskCreationRequiredParam struct {
UserName string `json:"username"`
RepoName string `json:"reponame"`
JobType string `json:"job_type"`
ComputeSource string `json:"compute_source"`
ClusterType string `json:"cluster_type"`
}

6
model/test.go Normal file
View File

@ -0,0 +1,6 @@
package model
type ASD struct {
Asd string `json:"asd"`
Zxc string `json:"zxc"`
}

17
model/user.go Normal file
View File

@ -0,0 +1,17 @@
package model
import "time"
type UserInfo struct {
Id int `json:"id"`
Login string `json:"login"`
FullName string `json:"full_name"`
Email string `json:"email"`
AvatarUrl string `json:"avatar_url"`
Language string `json:"language"`
IsAdmin bool `json:"is_admin"`
IsActive bool `json:"is_active"`
LastLogin time.Time `json:"last_login"`
Created time.Time `json:"created"`
Username string `json:"username"`
}

80
router/router.go Normal file
View File

@ -0,0 +1,80 @@
package router
import (
"fmt"
"github.com/gin-gonic/gin"
"pcm-openi/apis"
"pcm-openi/config"
"pcm-openi/err"
"regexp"
"time"
)
func Create(conf *config.Configuration) (*gin.Engine, error) {
g := gin.New()
g.Use(gin.LoggerWithFormatter(logFormatter), gin.Recovery())
g.NoRoute(err.Handler())
g.Use(gin.Logger())
g.Use(gin.Recovery())
//g.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
//handler := api.TestApi{}
api := g.Group("/api")
v1 := api.Group("/v1")
{
//user
user := v1.Group("user")
user.GET("", apis.GetUserInfo)
//repo
repo := v1.Group("user")
repo.GET("/repos", apis.GetRepos)
repo.POST("/repos", apis.CreateRepo)
//image
image := v1.Group("image")
image.GET("/recommend", apis.GetImageRecommended)
//datasets
datasets := v1.Group("datasets")
datasets.GET("/datasets", apis.GetRepos)
//task
task := v1.Group("task")
task.GET("/creationRequired", apis.GetTaskCreationRequired)
}
return g, nil
}
var tokenRegexp = regexp.MustCompile("token=[^&]+")
func logFormatter(param gin.LogFormatterParams) string {
if (param.ClientIP == "127.0.0.1" || param.ClientIP == "::1") && param.Path == "/health" {
return ""
}
var statusColor, methodColor, resetColor string
if param.IsOutputColor() {
statusColor = param.StatusCodeColor()
methodColor = param.MethodColor()
resetColor = param.ResetColor()
}
if param.Latency > time.Minute {
param.Latency = param.Latency - param.Latency%time.Second
}
path := tokenRegexp.ReplaceAllString(param.Path, "token=[masked]")
return fmt.Sprintf("%v |%s %3d %s| %13v | %15s |%s %-7s %s %#v\n%s",
param.TimeStamp.Format(time.RFC3339),
statusColor, param.StatusCode, resetColor,
param.Latency,
param.ClientIP,
methodColor, param.Method, resetColor,
path,
param.ErrorMessage,
)
}

5
test/client_test.go Normal file
View File

@ -0,0 +1,5 @@
package test
var (
ClientToken = "Caaaaaaaaaaaaaa"
)