Commit 56f8733f authored by luxq's avatar luxq

add code

parents
Pipeline #515 canceled with stages
.idea
*.log
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/randomservice.iml" filepath="$PROJECT_DIR$/.idea/randomservice.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
[server]
address = "0.0.0.0:9900"
privatekey = 0x0aa528c00748fd3fc37f5cb5f995f3da9c820df02aef5cb7786c8ea54abb0950
[log]
level = info
file = service.log
\ No newline at end of file
package common
import (
"bytes"
"github.com/ethereum/go-ethereum/common"
)
func Hex2Addr(addr string) []byte {
a := common.HexToAddress(addr)
return a[:]
}
func BytesCombine(pBytes ...[]byte) []byte {
return bytes.Join(pBytes, []byte(""))
}
\ No newline at end of file
package common
import (
"github.com/ethereum/go-ethereum/crypto"
)
func Sign(priv string, data []byte) ([]byte, error) {
pk, err := crypto.HexToECDSA(priv)
if err != nil {
return nil, err
}
hash := crypto.Keccak256(data)
return crypto.Sign(hash, pk)
}
package config
import (
log "github.com/sirupsen/logrus"
"os"
"path/filepath"
"gopkg.in/ini.v1"
)
type Config struct {
cfg *ini.File
}
var gConfig = &Config{}
func init() {
confpath := "app.conf"
cfg, err := ini.Load(confpath)
if err != nil {
log.Println("文件读取错误", err)
os.Exit(1)
}
gConfig.cfg = cfg
}
func GetConfig() *Config {
return gConfig
}
func (c *Config) ServerAddr() string {
addr := c.cfg.Section("server").Key("address").MustString("0.0.0.0:9900")
return addr
}
func (c *Config) PrivateKey() string {
priv := c.cfg.Section("server").Key("privatekey").String()
return priv
}
func (c *Config) LogLevel() string {
level := c.cfg.Section("log").Key("level").String()
if len(level) == 0 {
return "info"
}
return level
}
func (c *Config) LogFile() string {
name := c.cfg.Section("log").Key("file").String()
if len(name) == 0 {
name = "service.log"
}
filename := filepath.Join("logs", name)
return filename
}
package controller
import (
"net/http"
"github.com/gin-gonic/gin"
)
// Response return response
type Response struct {
ErrorCode int `json:"error_code"`
ErrorMessage string `json:"error_message"`
Data interface{} `json:"data"`
}
func ResponseError(c *gin.Context, code int, m string) {
c.AbortWithStatusJSON(code, Response{
ErrorCode: code,
ErrorMessage: m,
})
}
func ResponseSuccess(c *gin.Context, data interface{}) {
c.AbortWithStatusJSON(http.StatusOK, Response{
Data: data,
})
}
func ResponseResult(c *gin.Context, res Response) {
c.AbortWithStatusJSON(http.StatusOK, res)
}
package controller
import (
"fmt"
"github.com/gin-gonic/gin"
"gitlab.com/hashrs/randomservice/common"
"gitlab.com/hashrs/randomservice/config"
"gitlab.com/hashrs/randomservice/model"
"gitlab.com/hashrs/randomservice/service"
"net/http"
)
func HandleRandom(c *gin.Context) {
var param model.RandomParam
err := c.BindJSON(&param)
if err != nil {
ResponseError(c, http.StatusBadRequest, fmt.Sprintf("invalid param"))
return
}
res, err := service.RandomService(common.Hex2Addr(param.Account), config.GetConfig().PrivateKey())
if err != nil {
ResponseError(c, http.StatusInternalServerError, err.Error())
return
}
ResponseSuccess(c, res)
}
module gitlab.com/hashrs/randomservice
go 1.17
require (
github.com/ethereum/go-ethereum v1.10.16
github.com/gin-gonic/gin v1.7.7
github.com/sirupsen/logrus v1.8.1
gopkg.in/ini.v1 v1.66.4
)
require (
github.com/btcsuite/btcd v0.20.1-beta // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.13.0 // indirect
github.com/go-playground/universal-translator v0.17.0 // indirect
github.com/go-playground/validator/v10 v10.4.1 // indirect
github.com/golang/protobuf v1.4.3 // indirect
github.com/json-iterator/go v1.1.9 // indirect
github.com/leodido/go-urn v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.12 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.1 // indirect
github.com/ugorji/go/codec v1.1.7 // indirect
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 // indirect
golang.org/x/sys v0.0.0-20210816183151-1e6c022a8912 // indirect
google.golang.org/protobuf v1.23.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
This diff is collapsed.
package main
import (
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"gitlab.com/hashrs/randomservice/config"
"gitlab.com/hashrs/randomservice/router"
"io"
"net/http"
"os"
"os/signal"
"syscall"
)
func InitLog(conf *config.Config) {
level := conf.LogLevel()
switch level {
case "info":
log.SetLevel(log.InfoLevel)
case "debug":
log.SetLevel(log.DebugLevel)
default:
log.SetLevel(log.InfoLevel)
}
logfile, err := os.OpenFile(conf.LogFile(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModeAppend|0755)
//logfile, err := os.OpenFile(conf.LogFile(), os.O_WRONLY|os.O_CREATE, 0755)
if err != nil {
log.Error("can't open log file", conf.LogFile())
}
Formatter := new(log.TextFormatter)
Formatter.TimestampFormat = "2006-01-02T15:04:05.999999999Z07:00"
Formatter.FullTimestamp = true
Formatter.ForceColors = true
log.SetFormatter(Formatter)
log.SetOutput(io.MultiWriter(logfile))
}
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin")
if origin != "" {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
c.Header("Access-Control-Allow-Credentials", "true")
c.Set("content-type", "application/json")
}
//放行所有OPTIONS方法
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
}
func main() {
conf := config.GetConfig()
InitLog(conf)
go func() {
r := gin.New()
//r.Use(Cors()) //默认跨域
r.Use(gin.Recovery())
router.InitRouter(r)
log.Infof("Start HTTP Server on %s:%d", conf.ServerAddr())
if err := r.Run(conf.ServerAddr()); err != nil {
log.WithError(err).Fatalln("fail to run server")
}
}()
exitSig := []os.Signal{os.Interrupt, syscall.SIGTERM}
exitCh := make(chan os.Signal, 2)
signal.Notify(exitCh, exitSig...)
<-exitCh
os.Exit(1)
}
package model
type RandomParam struct {
Account string `json:"account"`
}
package router
import (
"github.com/gin-gonic/gin"
"gitlab.com/hashrs/randomservice/controller"
)
func InitRouter(r *gin.Engine) {
service := r.Group("/randomapi")
v1 := service.Group("/v1")
v1.POST("/random", controller.HandleRandom)
}
package service
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"gitlab.com/hashrs/randomservice/common"
)
func RandomService(account []byte, pk string) (map[string]interface{},error) {
r,err := rand.Prime(rand.Reader, 128)
if err != nil {
return nil, errors.New("generate prime failed")
}
data := common.BytesCombine(account,r.Bytes())
sig, err := common.Sign(pk, data)
if err != nil {
return nil, errors.New(fmt.Sprintf("sign failed (%s)", err))
}
var res = make(map[string]interface{})
res["rand"] = r.Text(16)
res["signature"] = hex.EncodeToString(sig)
return res, nil
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment