Golang(12)Web Service - JSON Mapping Improvement

本文展示了一个使用Golang实现的WebService,包括JSON映射改进、请求解析和响应处理。通过实例演示了如何将JSON数据与结构体进行交互,并提供了HTTP方法如GET、POST、PUT和DELETE的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Golang(12)Web Service - JSON Mapping Improvement

Take the marshal and unmarshal codes out of every method.

package main

import (
     "encoding/json"
     "fmt"
     "github.com/gorilla/mux"
     "io/ioutil"
     "net/http"
)

type Bug struct {
     Id        string
     BugNumber string
     BugName   string
     BugDesn   string
}

type JSONResult map[string]interface{}

func (r JSONResult) String() (s string) {
     b, err := json.Marshal(r)
     if err != nil {
          s = "json err: " + err.Error()
          return
     }
     s = string(b)
     return
}

func ParseJSON(r *http.Request) Bug {
     var b Bug
     c, _ := ioutil.ReadAll(r.Body)
     fmt.Println("ParseJSON called with Body=" + string(c))

     json.Unmarshal(c, &b)
     return b
}

func getBug(w http.ResponseWriter, r *http.Request) {
     b1 := Bug{Id: "1", BugNumber: "bug1", BugName: "bug1", BugDesn: "desn1"}

     w.Header().Set("Content-Type", "application/json")
     fmt.Fprint(w, JSONResult{"status": "ok", "bugs": []Bug{b1}})
}

func updateBug(w http.ResponseWriter, r *http.Request) {
     b := ParseJSON(r)

     fmt.Println("updateBug called with Id=" + b.Id)
     fmt.Println("updateBug called with BugNumber=" + b.BugNumber)
     fmt.Println("updateBug called with BugName=" + b.BugName)
     fmt.Println("updateBug called with BugDesn=" + b.BugDesn)

     w.Header().Set("Content-Type", "application/json")
     fmt.Fprint(w, JSONResult{"status": "ok", "bugs": []Bug{b}})
}

func deleteBug(w http.ResponseWriter, r *http.Request) {
     id := mux.Vars(r)["Id"]
     fmt.Println("deleteBug called with Id = ", id)

     w.Header().Set("Content-Type", "application/json")
     fmt.Fprint(w, JSONResult{"status": "ok"})
}

func addBug(w http.ResponseWriter, r *http.Request) {
     b := ParseJSON(r)

     fmt.Println("addBug called with BugNumber=" + b.BugNumber)
     fmt.Println("addBug called with BugName=" + b.BugName)
     fmt.Println("addBug called with BugDesn=" + b.BugDesn)

     w.Header().Set("Content-Type", "application/json")
     fmt.Fprint(w, JSONResult{"status": "ok", "bugs": []Bug{b}})
}

func listBug(w http.ResponseWriter, r *http.Request) {
     b1 := Bug{Id: "1", BugNumber: "bug1", BugName: "bug1", BugDesn: "desn1"}
     b2 := Bug{Id: "2", BugNumber: "bug2", BugName: "bug2", BugDesn: "desn2"}

     w.Header().Set("Content-Type", "application/json")
     fmt.Fprint(w, JSONResult{"status": "ok", "bugs": []Bug{b1, b2}})
}

func main() {
     router := mux.NewRouter()
     router.HandleFunc("/bugs", listBug).Methods("GET")
     router.HandleFunc("/bugs", addBug).Methods("POST")
     router.HandleFunc("/bugs/{Id}", getBug).Methods("GET")
     router.HandleFunc("/bugs/{Id}", updateBug).Methods("PUT")
     router.HandleFunc("/bugs/{Id}", deleteBug).Methods("DELETE")

     http.Handle("/", router)
     http.ListenAndServe(":8088", nil)
}

Maybe, it will be helpful if one day I design and implement a web framework myself. Actually, it will be light and clean, only need routers, dispatcher and JSON render and parse built-in the framework.

References:
http://nesv.blogspot.com/2012/09/super-easy-json-http-responses-in-go.html
http://www.alexedwards.net/blog/golang-response-snippets#json

http://sillycat.iteye.com/blog/2056435
http://golangtutorials.blogspot.com/2011/06/methods-on-structs.html
http://stackoverflow.com/questions/18678135/go-static-method-design

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值