GolangNote

Golang笔记

go json response Controller 例子

Permalink

go json response Controller 例子

Go: json_response
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// controller/json_response.go
package controller
 
import (
    "encoding/json"
    "net/http"
)
 
// status codes
const (
    StatusOK      = http.StatusOK
    StatusCreated = http.StatusCreated
)
 
// JSONResponse is alias of map for JSON response
type JSONResponse struct {
    data   map[string]interface{}
    status int
}
 
// NewResponse creates a new JSONResponse
func NewResponse() *JSONResponse {
    r := &JSONResponse{
        data:   make(map[string]interface{}),
        status: StatusOK,
    }
    return r
}
 
// Merge adds multiple map data to the response
func (r *JSONResponse) Merge(data map[string]interface{}) {
    for k, v := range data {
        r.data[k] = v
    }
}
 
// Add adds a single key-value to the response
func (r *JSONResponse) Add(key string, value interface{}) {
    r.data[key] = value
}
 
// SetCreated set http status code to 201
func (r *JSONResponse) SetCreated() {
    r.status = StatusCreated
}
 
// RenderJSON render json response
func RenderJSON(w http.ResponseWriter, msg interface{}) {
    switch v := msg.(type) {
    case *JSONResponse:
        if _, ok := v.data["error"]; !ok {
            v.data["error"] = nil
        }
        w.WriteHeader(v.status)
        msg = v.data
    }
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(msg)
}

使用

Go: pack apiv1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// controller/apiv1/author_controller.go
package apiv1
 
import (
    "net/http"
 
    "github.com/zenazn/goji/web"
 
    "github.com/eure/example-blog-golang/controller"
)
 
// GetAuthor shows author data
func GetAuthor(c web.C, w http.ResponseWriter, r *http.Request) {
    data := controller.NewResponse()
    data.Add("object", "author")
    data.Add("name", c.URLParams["name"])
    controller.RenderJSON(w, data)
}

路由

Go: routing
1
2
3
4
5
6
7
8
9
10
11
12
13
// routing/v1.go
package routing
 
import (
    "github.com/zenazn/goji/web"
 
    "github.com/eure/example-blog-golang/controller/apiv1"
)
 
// SetV1 sets api routing ver1
func SetV1(r *web.Mux) {
    r.Get("/author/:name", apiv1.GetAuthor)
}

测试

Bash: 测试
1
2
3
4
5
$ curl -s localhost:1234/api/v1/author/takuma
{"error":null,"name":"takuma","object":"author"}
 
$ curl -s localhost:1234/api/v1/author/your_sweetheart
{"error":null,"name":"your_sweetheart","object":"author"}

本文网址: https://golangnote.com/topic/115.html 转摘请注明来源

Related articles

Write a Comment to "go json response Controller 例子"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms