资源目录
https://github.com/gin-gonic
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
}
}
}
客户端我就抄了一个可用的,毕竟我不会写
Golang Chat