GolangNote

Golang笔记

goji 实现输出json 的例子

Permalink

goji 没有内置输出常见的格式,如json、xml 等,下面是实现输出json 的例子:

goji json

Go: goji json
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
package main

import (
  "encoding/json"
  "flag"
  "net/http"

  "github.com/zenazn/goji"
)

func main() {
  goji.Get("/", Root)

  flag.Set("bind", ":8000")
  goji.Serve()
}

type Hello struct {
  Message string
}

func Root(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "application/json")

  hello := &Hello{Message: "Hello, world"}

  encoder := json.NewEncoder(w)
  encoder.Encode(hello)
}

运行后访问url,输出:

JSON: out put
1
{"Message":"Hello, world"}

关于goji 没有内置一些常见的输出格式,这里有个建议,goji 作者用心的回答了为什么不!

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

Related articles

关掉goji 的log 输出

goji 默认对每个请求都输出请求时间,在项目刚起步时可以作为性能参考,但在实际生产环境里,可以关掉log...

Write a Comment to "goji 实现输出json 的例子"

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