gin-gonic Go轻量级restful服务
2020-05-25 本文已影响0人
三分归元币
资源目录
https://github.com/gin-gonic/gin#quick-start
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
type RequestBody struct {
Hello string `json:"hello"`
}
func main(){
fmt.Println("http server setup")
r := gin.Default()
r.POST("/hello", helloHandler)
_ = r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
func helloHandler (context *gin.Context) {
var req RequestBody
param1 := context.Query("id")
fmt.Printf("receive param1 : %s\n",param1)
if err := context.ShouldBindJSON(&req); err != nil{
context.JSON(500,gin.H{
"status":-1,
"message":"request error",
"success":false,
})
}
fmt.Printf("receive jsonbody : %s\n",req.Hello)
context.JSON(200,gin.H{
"status":0,
"message":"success",
"success":true,
})
}
指定port
_ = r.Run(":8081")
启动完成之后,就可以使用HTTP工具进行访问,如同一个tomcat,而且比较轻量级。
一般Json请求的处理方式
package main
import (
"errors"
"github.com/gin-gonic/gin"
"log"
)
type RequestBody struct {
Hello string `json:"hello"`
}
func main(){
log.Println("http server setup")
r := gin.Default()
r.POST("/hello/:id" , jsonApi(helloHandler))
_ = r.Run(":8081") // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
type Any interface {}
type HandlerFunc func(*gin.Context)(Any,error)
func jsonApi(handler HandlerFunc) gin.HandlerFunc{
return func(c *gin.Context) {
id := c.Param("id")
log.Printf("id : %v\n", id)
code := 200
var resMap = make(map[string]interface{})
out,err := handler(c)
if err != nil{
code = 500
resMap["message"] = err.Error()
resMap["success"] = false
} else {
resMap["message"] = out
resMap["success"] = true
}
c.JSON(code,resMap)
}
}
func helloHandler (context *gin.Context)(Any,error) {
type Result struct {
Status int `json:"status"`
GetMessage string `json:"get_message"`
}
type Request struct {
Name string `json:"name"`
}
var req Request
if err := context.ShouldBindJSON(&req); err != nil{
log.Fatalf("get an error %v\n",err)
return nil,err
}
log.Printf("helloHandler get name %v\n",req.Name)
if req.Name == "exp"{
return nil,errors.New("this is a target error")
}else{
result := &Result{
Status: 200,
GetMessage: req.Name,
}
return result,nil
}
}
上传文件
// 上传文件
func upload(context *gin.Context)(Any,error) {
type Response struct {
Status int `json:"status"`
}
file,header,err := context.Request.FormFile("img")
if err != nil{
log.Fatalf("file read error,%v\n",err)
return nil,err
}
log.Printf("get file name : %v\n",header.Filename)
log.Printf("file size : %v\n",header.Size)
data,_:= ioutil.ReadAll(file)
defer file.Close()
if strings.HasSuffix(header.Filename,".txt") {
content := string(data)
log.Printf("content : %v\n",content)
}
resp := &Response{
Status: 200,
}
return resp,nil
}
websocket功能
Server.GET("/ping" , Ping)
// websocket 协议
func Ping(context * gin.Context){
// 升级协议
ws,err := upGrader.Upgrade(context.Writer,context.Request,nil)
if err != nil {
log.Printf("get an error on connecting: %v\n",err)
return
}
defer ws.Close()
for{
mt,message,err := ws.ReadMessage()
str := string(message)
if err != nil{
log.Printf("get an error : %v\n",err)
}
log.Printf("get message type : %v\n",mt)
log.Printf("get message : %v\n",str)
var resp []byte
if str == "ping"{
resp = []byte("pong")
} else if str == "exit"{
resp = []byte("bye")
} else {
resp = message
}
err = ws.WriteMessage(mt,resp)
if err != nil || str == "exit"{
break
}
}
}
客户端我就抄了一个可用的,毕竟我不会写
<html>
<head>
<title>Golang Chat</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var conn;
var msg = $("#msg");
var log = $("#log");
function appendLog(msg) {
var d = log[0]
var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
msg.appendTo(log)
if (doScroll) {
d.scrollTop = d.scrollHeight - d.clientHeight;
}
}
$("#form").submit(function() {
if (!conn) {
return false;
}
if (!msg.val()) {
return false;
}
conn.send(msg.val());
msg.val("");
return false
});
if (window["WebSocket"]) {
conn = new WebSocket("ws://localhost:8081/ping");
conn.onclose = function(evt) {
appendLog($("<div><b>Connection Closed.</b></div>"))
}
conn.onmessage = function(evt) {
appendLog($("<div/>").text(evt.data))
}
} else {
appendLog($("<div><b>WebSockets Not Support.</b></div>"))
}
});
</script>
<style type="text/css">
html {
overflow: hidden;
}
body {
overflow: hidden;
padding: 0;
margin: 0;
width: 100%;
height: 100%;
background: gray;
}
#log {
background: white;
margin: 0;
padding: 0.5em 0.5em 0.5em 0.5em;
position: absolute;
top: 0.5em;
left: 0.5em;
right: 0.5em;
bottom: 3em;
overflow: auto;
}
#form {
padding: 0 0.5em 0 0.5em;
margin: 0;
position: absolute;
bottom: 1em;
left: 0px;
width: 100%;
overflow: hidden;
}
</style>
</head>
<body>
<div id="log"></div>
<form id="form">
<input type="submit" value="发送" />
<input type="text" id="msg" size="64"/>
</form>
</body>
</html>
image.png
image.png