GolangNote

Golang笔记

用goji v2 开发RESTful 服务示例

Permalink

用goji v2 开发 RESTful 服务示例

Go: RESTful 服务示例
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
60
61
62
63
64
65
66
package main

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

	"goji.io"
	"goji.io/pat"
	"golang.org/x/net/context"
)

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.HandleFuncC(pat.Get("/books"), allBooks)
	mux.HandleFuncC(pat.Get("/books/:isbn"), bookByISBN)
	mux.UseC(logging)
	http.ListenAndServe("localhost:8080", mux)
}

func allBooks(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	jsonOut, _ := json.Marshal(bookStore)
	fmt.Fprintf(w, string(jsonOut))
}

func bookByISBN(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	isbn := pat.Param(ctx, "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 goji.Handler) goji.Handler {
	fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		fmt.Printf("Received request: %v\n", r.URL)
		h.ServeHTTPC(ctx, w, r)
	}
	return goji.HandlerFunc(fn)
}

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

Related articles

goji v2goji 的对接

goji 是个优秀的框架,作者说以前是弄着玩的,后来较正规的按照go 的设计原则来重构,不过尽量保持原来的接口。...

Golang Web 程序生产环境独立部署示例

一个 web 应用通常是跑在一个前端代理,如 Nginx 后,这样可以方便的在同一个服务器部署多个应用。这里说的独立部署是指让 go web 程序直接暴露在外面,独占 443、80 端口(俗称裸跑)。这样做除了性能有些提高外,更重要的是部署方便。...

golang web 框架 goji 介绍

goji 是个后起的golang web框架,避免其它golang web 框架走过的坑,在性能、简单性方面做得很好。...

golang snappy 示例

snappy 是 google 开源的一种高效的压缩算法,这里是 golang 实现的 snappy 压缩示例...

Write a Comment to "用goji v2 开发RESTful 服务示例"

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