Goji 实现RESTful 微服务示例
🕘 Tue, 16 May 2017 by GolangNote
Golang 可以跨平台编译,部署微服务很方便,下面是用Goji 实现RESTful 微服务示例。
package main
import (
"encoding/json"
"fmt"
"net/http"
"goji.io"
"goji.io/pat"
)
type book struct {
ISBN string "json:isbn"
Title string "json:name"
Authors string "json:author"
Price string "json:price"
}
var bookStore = []book{
book{
ISBN: "0321774639",
Title: "Programming in Go: Creating Applications for the 21st Century (Developer's Library)",
Authors: "Mark Summerfield",
Price: "$34.57",
},
book{
ISBN: "0134190440",
Title: "The Go Programming Language",
Authors: "Alan A. A. Donovan, Brian W. Kernighan",
Price: "$34.57",
},
}
func main() {
mux := goji.NewMux()
mux.HandleFunc(pat.Get("/books"), allBooks)
mux.HandleFunc(pat.Get("/books/:isbn"), bookByISBN)
mux.Use(logging)
http.ListenAndServe("localhost:8080", mux)
}
func allBooks(w http.ResponseWriter, r *http.Request) {
jsonOut, _ := json.Marshal(bookStore)
fmt.Fprintf(w, string(jsonOut))
}
func bookByISBN(w http.ResponseWriter, r *http.Request) {
isbn := pat.Param(r, "isbn")
for _, b := range bookStore {
if b.ISBN == isbn {
jsonOut, _ := json.Marshal(b)
fmt.Fprintf(w, string(jsonOut))
return
}
}
w.WriteHeader(http.StatusNotFound)
}
func logging(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Received request: %v\n", r.URL)
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
本文网址: https://golangnote.com/topic/171.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Relative Articles
Recent Go Articles
- Golang 把cookie 字符串解析为cookie 结构
- Golang 计算字符串中包含某个或某些字符集的个数
- 使用Golang 对文件增删写读操作备忘
- Go Modules 使用备忘
- 使用Golang 简单删除图片exif 信息
- 谷歌翻译的 golang 库推荐
- Go 1.13.2 与1.13.3 紧急更新
- golang 人脸检测识别库
- Go build 错误 “stackcheck redeclared in this block previous declaration”的解决方法
- Golang phantomjs 动态代理实现
- Golang chrome debug protocol 库推荐
- Golang 随机打乱数组/Slice
- Golang sync.WaitGroup 的 Wait 超时处理
- Golang实现简单的Socks5代理
- Golang 用snappy + Base64 简单压缩加密进行网络传输
- Golang http IPv4/IPv6 服务
- golang 全角半角相互转换
- 在自己的网站部署TLS 1.3
- Golang 实现/打印菜单树
- Golang telegram 机器人小试
Top Go Articles
- 使用Golang 简单删除图片exif 信息
- 谷歌翻译的 golang 库推荐
- Go 1.13.2 与1.13.3 紧急更新
- golang 人脸检测识别库
- Go build 错误 “stackcheck redeclared in this block previous declaration”的解决方法
- Golang phantomjs 动态代理实现
- Golang chrome debug protocol 库推荐
- Golang 随机打乱数组/Slice
- Golang sync.WaitGroup 的 Wait 超时处理
- Golang实现简单的Socks5代理
- Golang 用snappy + Base64 简单压缩加密进行网络传输
- Golang http IPv4/IPv6 服务
- golang 全角半角相互转换
- 在自己的网站部署TLS 1.3
- Golang 实现/打印菜单树
- Golang telegram 机器人小试
- Golang get 请求忽略数字证书进行校验
- Golang字符串相等比较的性能
- an error broken: unknown escape sequence: d
- golang 正确获取绝对路径的方法