package main

import (
    "net/http"

    "github.com/gorilla/rpc/v2"
    "github.com/gorilla/rpc/v2/json2"
)

type WebService struct {
}

type LoginReq struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

type LoginResp struct {
    Token string `json:"token"`
}

func (*WebService) Login(r *http.Request, req *LoginReq, resp *LoginResp) error {
    if len(req.Username) < 4 ||
        len(req.Username) > 12 {
        return &json2.Error{
            Code:    1001,
            Message: "用户名长度错误",
            Data:    req.Username,
        }
    }
    resp.Token = "恭喜你登录成功!!!~~~"
    return nil
}

func main() {
    s := rpc.NewServer()
    s.RegisterCodec(json2.NewCodec(), "application/json")
    s.RegisterService(&WebService{}, "Web")
    http.Handle("/webrpc", s)
    http.ListenAndServe(":8000", nil)
}
curl http://localhost:8000/webrpc -X POST -H 'Content-Type: application/json' -d '{"id":0, "jsonrpc":"2.0", "method":"Web.Login", "params":[{"username": "daqiu"}]}'

{"jsonrpc":"2.0","result":{"token":"恭喜你登录成功!!!~~~"},"id":0}
跨域问题
r.POST("/webrpc", func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        s.ServeHTTP(c.Writer, c.Request)
    })
    r.OPTIONS("/webrpc", func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Max-Age", "86400")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "*")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
        c.Writer.Header().Set("Access-Control-Expose-Headers", "*")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(http.StatusNoContent)
        } else {
            c.Next()
        }
    })

标签: none

添加新评论