Golang(11)Web Service - RESTful
1. Concept
Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
URL hosts and paths can have variables with an optional regular expression.
It implements the http.Handler interface so it is compatible with the standard http.ServeMux.
router := mux.NewRouter()
router.HandleFunc("/", HomeHandler)
router.HandleFunc("/products", ProductsHandler)
Once the router matches, the handler will be called passing (http.ResponseWriter, http.Requet)as parameters.
Variables in paths follow this pattern, {name} or {name:pattern}.
router.HandleFunc(“/products/{key}”, ProductHandler)
router.HandleFunc(“/articles/{category}/{id:[0-9]+}”, ArticleHandler)
We can fetch all these values from map
vars :=mux.Vars(request)
category := vars[“category"]
Some other matches
router.Host(“www.domain.com”)
router.Host(“{subdomain:[a-z]+}.domain.com”)
router.PathPrefix(“/products/“)
router.Methods(“GET”, “POST”)
router.Schemes(“https”)
router.Headers(“X-Requested-With”, “XMLHttpRequest”)
router.Queries(“key”, “value”)
Example:
router.HandleFunc(“/products”, ProductsHandler).Host(“www.domain.com”).Methods(“GET”).Schemes(“http”)
Work with Sub Router
router := mux.NewRouter()
sub := router.Host(“www.domain.com”).Subrouter()
sub.HandleFunc(“/products/“, ProductsHandler)
Name a Router and Build the URL
router := mux.NewRouter()
router.HandleFunc(“/articles/{category}/{id:[0-9]+}”, ArticleHandler).Name(“article”)
url, err := r.Get(“article”).URL(“category”, “technology”, “id”, “42”)
eg: “/articles/technology/42"
2. Installation
>go get github.com/gorilla/mux
Here is the Whole go implementation Class as follow:
package main
import (
"encoding/json” //import the json package to marshal and unmarshal JSON
"fmt"
"github.com/gorilla/mux” //here is the router and dispatcher
"io/ioutil” //io util to read/write to io
"net/http” //handle the http based request and response
)
type Bug struct { //my demo object in go
Id string
BugNumber string
BugName string
BugDesn string
}
type BugResult struct { //my common REST response object
Bugs []Bug
Status string
}
func getBug(w http.ResponseWriter, r *http.Request) { //get method
b1 := Bug{Id: "1", BugNumber: "bug1", BugName: "bug1", BugDesn: "desn1"}
re := BugResult{Status: "Ok", Bugs: []Bug{b1}}
b, err := json.Marshal(re) //marshal the object to JSON
if err != nil {
fmt.Fprint(w, "json err: %s", err)
}
fmt.Fprint(w, string(b)) //write to the response
}
func updateBug(w http.ResponseWriter, r *http.Request) {
var b Bug
c, err := ioutil.ReadAll(r.Body) //read the string from body and unmarshal
fmt.Println("updateBug called with Body=" + string(c))
json.Unmarshal(c, &b)
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)
re := BugResult{Status: "OK", Bugs: []Bug{b}}
re_json, err := json.Marshal(re)
if err != nil {
fmt.Fprint(w, "json err: %s", err)
}
fmt.Fprint(w, string(re_json))
}
func deleteBug(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["Id”] //get the param from Path
fmt.Println("deleteBug called with Id = ", id)
re := BugResult{Status: "OK"}
b, err := json.Marshal(re)
if err != nil {
fmt.Fprint(w, "json err: %s", err)
}
fmt.Fprint(w, string(b))
}
func addBug(w http.ResponseWriter, r *http.Request) {
var b Bug
content, err := ioutil.ReadAll(r.Body)
fmt.Println("addBug called with Body=" + string(content))
json.Unmarshal(content, &b)
fmt.Println("addBug called with BugNumber=" + b.BugNumber)
fmt.Println("addBug called with BugName=" + b.BugName)
fmt.Println("addBug called with BugDesn=" + b.BugDesn)
re := BugResult{Status: "OK", Bugs: []Bug{b}}
re_json, err := json.Marshal(re)
if err != nil {
fmt.Fprint(w, "json err: %s", err)
}
fmt.Fprint(w, string(re_json))
}
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"}
re := BugResult{Status: "Ok", Bugs: []Bug{b1, b2}}
b, err := json.Marshal(re)
if err != nil {
fmt.Fprint(w, "json err: %s", err)
}
fmt.Fprint(w, string(b))
}
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)
}
It is not very nice since there is repeat codes like this.
b, err := json.Marshal(re)
if err != nil {
fmt.Fprint(w, "json err: %s", err)
}
fmt.Fprint(w, string(b))
I will check how to avoid that.
References:
https://github.com/drone/routes
https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/08.3.md
https://github.com/gorilla/mux
http://www.gorillatoolkit.org/pkg/mux
JSON handle
http://sillycat.iteye.com/blog/2065585
- 浏览: 2552716 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 476NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 337Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 436Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 385Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 479NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 424Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 337Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 248GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 452GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 328GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 314Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 319Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 294Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 312Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 288NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 261Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 574NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 266Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 368Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 371Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
【标题】:“Python-Web-Guide:Python与Golang Web开发入门教程” 【描述】:“Python-Web-Guide:Python与Golang -Web入坑指南”是一个专为初学者设计的资源,旨在帮助那些对使用Python和Golang进行Web开发感兴趣...
Singo: Simple Single Golang Web Service go-crud正式改名为Singo! 使用Singo开发Web服务: 用最简单的架构,实现够用的框架,服务海量用户 https://github.com/Gourouting/singo Singo文档 ...
在本文中,我们将深入探讨如何使用Golang(Go语言)构建SOAP(Simple Object Access Protocol)Web服务。SOAP是一种基于XML的协议,用于在应用程序之间交换结构化和类型化的信息,通常用于企业级服务和跨平台通信。 ...
Singo: Simple Single Golang Web Service go-crud正式改名为Singo! 使用Singo开发Web服务: 用最简单的架构,实现够用的框架,服务海量用户 Singo文档 视频实况教程 使用Singo开发的项目实例 目的 本项目采用了一...
本资料包"Go Web Service.zip"主要探讨了如何使用Go语言来构建Web服务,包括RESTful API和SOAP两种常见的Web服务协议。 **REST API的实现** REST(Representational State Transfer,表述性状态转移)是一种网络...
About This Book, Effectively deploy and integrate Go web services with applications in the real worldFamiliarize yourself with RESTful practices and apply them in GoA comprehensive tutorial with lots ...
RESTful API是现代Web服务的主流,T大树洞的后端很可能提供了基于HTTP的API接口。API的设计原则、参数验证和响应结构都在接口定义中体现。同时,项目中的`tests`包包含单元测试和集成测试,以确保代码质量。 8. **...
在构建“Amazon Clone Account Service”时,我们关注的是利用GoLang(Golang)的强大功能来设计和实现一个高效、可扩展且可靠的微服务。Go语言以其简洁的语法、高效的并发模型以及内置的垃圾回收机制而受到青睐,...
trygo ======= trygo 是基于Golang的http、web服务框架。... It is mainly used to develop the underlying HTTP service, Support feature:RESTful,MVC,Methods the routing and regular routing,JSON/JSO
【标题】"基于golang+vue搭建小说书城"揭示了这个项目是使用Go语言(golang)作为后端开发语言,Vue.js作为前端框架来构建一个在线小说平台。Go语言以其高性能、简洁的语法和内置并发支持在服务器端开发中越来越受...
2. **路由管理(Routing)**:框架提供了灵活的路由规则,可以方便地定义 RESTful API,支持动态路由参数和路径匹配,为Web服务提供强大路由能力。 3. **依赖注入(Dependency Injection)**:`go-zero` 通过依赖注入...
因此,我们可以预期my-todo-service是用Go的web框架,如Gin或Echo,来构建的,它可能利用了Go的并发特性来优化请求处理。 基于提供的文件名称"my-todo-service-master",我们可以推测这是一个开源项目,可能包含了...
基于Golang开发维护; 支持Windows,Linux,macOS平台; 支持RTSP推流分配(推模式转发); 支持RTSP拉流分配(拉模式转发); 服务端录像参考: : 服务端录像检索与重新参考: ://blog.csdn.net/jyt0551/article/...
开源项目“jontonsoup4-taco-bell-optimizer.zip”是一个基于Go语言编写的API服务器,其核心目的是...这个开源项目体现了现代Web开发的最佳实践,包括使用RESTful API、版本控制和微服务架构,并鼓励社区参与和贡献。
9. **API设计**:鉴于标题中没有提到前端部分,blog-service可能主要关注API设计,如RESTful API,用于与其他应用或客户端进行交互。 10. **安全性考虑**:包括但不限于输入验证、防止SQL注入、XSS攻击等,Go语言的...
整体来看,“xuesou-backend-service”项目是使用Go语言构建的一个高效、稳定的后端服务,旨在支持微信小程序"xuesou wxapp"的功能实现,通过RESTful API与前端交互,提供数据检索、存储等服务。开发者可以深入研究...
综上所述,"userpost-service"是一个基于Golang构建的后台服务,专注于处理用户帖子和评论的相关操作,涉及到了多个IT领域的技术和实践,包括但不限于编程语言、后端开发、API设计、数据库管理、并发处理、错误处理...
总结来说,ATC是一个强大的Go语言Web框架,它结合了RESTful API和Thrift RPC的优势,提供了高度定制化的中间件系统,使得开发者能快速高效地构建健壮的Web服务。通过深入理解并熟练运用ATC,开发者可以显著提升开发...